3 * @file include/dfrn.php
4 * @brief The implementation of the dfrn protocol
6 * @see https://github.com/friendica/friendica/wiki/Protocol and
7 * https://github.com/friendica/friendica/blob/master/spec/dfrn2.pdf
10 require_once("include/Contact.php");
11 require_once("include/ostatus.php");
12 require_once("include/enotify.php");
13 require_once("include/threads.php");
14 require_once("include/socgraph.php");
15 require_once("include/items.php");
16 require_once("include/tags.php");
17 require_once("include/files.php");
18 require_once("include/event.php");
19 require_once("include/text.php");
20 require_once("include/oembed.php");
21 require_once("include/html2bbcode.php");
22 require_once("include/bbcode.php");
23 require_once("include/xml.php");
26 * @brief This class contain functions to create and send DFRN XML files
31 const DFRN_TOP_LEVEL = 0; // Top level posting
32 const DFRN_REPLY = 1; // Regular reply that is stored locally
33 const DFRN_REPLY_RC = 2; // Reply that will be relayed
36 * @brief Generates the atom entries for delivery.php
38 * This function is used whenever content is transmitted via DFRN.
40 * @param array $items Item elements
41 * @param array $owner Owner record
43 * @return string DFRN entries
45 public static function entries($items,$owner) {
47 $doc = new DOMDocument('1.0', 'utf-8');
48 $doc->formatOutput = true;
50 $root = self::add_header($doc, $owner, "dfrn:owner", "", false);
53 return trim($doc->saveXML());
55 foreach($items as $item) {
56 $entry = self::entry($doc, "text", $item, $owner, $item["entry:comment-allow"], $item["entry:cid"]);
57 $root->appendChild($entry);
60 return(trim($doc->saveXML()));
64 * @brief Generate an atom feed for the given user
66 * This function is called when another server is pulling data from the user feed.
68 * @param string $dfrn_id DFRN ID from the requesting party
69 * @param string $owner_nick Owner nick name
70 * @param string $last_update Date of the last update
71 * @param int $direction Can be -1, 0 or 1.
72 * @param boolean $onlyheader Output only the header without content? (Default is "no")
74 * @return string DFRN feed entries
76 public static function feed($dfrn_id, $owner_nick, $last_update, $direction = 0, $onlyheader = false) {
80 $sitefeed = ((strlen($owner_nick)) ? false : true); // not yet implemented, need to rewrite huge chunks of following logic
81 $public_feed = (($dfrn_id) ? false : true);
82 $starred = false; // not yet implemented, possible security issues
85 if($public_feed && $a->argc > 2) {
86 for($x = 2; $x < $a->argc; $x++) {
87 if($a->argv[$x] == 'converse')
89 if($a->argv[$x] == 'starred')
91 if($a->argv[$x] == 'category' && $a->argc > ($x + 1) && strlen($a->argv[$x+1]))
92 $category = $a->argv[$x+1];
98 // default permissions - anonymous user
100 $sql_extra = " AND `item`.`allow_cid` = '' AND `item`.`allow_gid` = '' AND `item`.`deny_cid` = '' AND `item`.`deny_gid` = '' ";
102 $r = q("SELECT `contact`.*, `user`.`nickname`, `user`.`timezone`, `user`.`page-flags`, `user`.`account-type`
103 FROM `contact` INNER JOIN `user` ON `user`.`uid` = `contact`.`uid`
104 WHERE `contact`.`self` AND `user`.`nickname` = '%s' LIMIT 1",
112 $owner_id = $owner['uid'];
113 $owner_nick = $owner['nickname'];
115 $sql_post_table = "";
122 $sql_extra = sprintf(" AND `issued-id` = '%s' ", dbesc($dfrn_id));
126 $sql_extra = sprintf(" AND `issued-id` = '%s' AND `duplex` = 1 ", dbesc($dfrn_id));
127 $my_id = '1:' . $dfrn_id;
130 $sql_extra = sprintf(" AND `dfrn-id` = '%s' AND `duplex` = 1 ", dbesc($dfrn_id));
131 $my_id = '0:' . $dfrn_id;
138 $r = q("SELECT * FROM `contact` WHERE NOT `blocked` AND `contact`.`uid` = %d $sql_extra LIMIT 1",
146 require_once('include/security.php');
147 $groups = init_groups_visitor($contact['id']);
150 for($x = 0; $x < count($groups); $x ++)
151 $groups[$x] = '<' . intval($groups[$x]) . '>' ;
152 $gs = implode('|', $groups);
154 $gs = '<<>>' ; // Impossible to match
156 $sql_extra = sprintf("
157 AND ( `allow_cid` = '' OR `allow_cid` REGEXP '<%d>' )
158 AND ( `deny_cid` = '' OR NOT `deny_cid` REGEXP '<%d>' )
159 AND ( `allow_gid` = '' OR `allow_gid` REGEXP '%s' )
160 AND ( `deny_gid` = '' OR NOT `deny_gid` REGEXP '%s')
162 intval($contact['id']),
163 intval($contact['id']),
174 if(! strlen($last_update))
175 $last_update = 'now -30 days';
177 if(isset($category)) {
178 $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` ",
179 dbesc(protect_sprintf($category)), intval(TERM_OBJ_POST), intval(TERM_CATEGORY), intval($owner_id));
180 //$sql_extra .= file_tag_file_query('item',$category,'category');
185 $sql_extra .= " AND `contact`.`self` = 1 ";
188 $check_date = datetime_convert('UTC','UTC',$last_update,'Y-m-d H:i:s');
190 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`,
191 `contact`.`name`, `contact`.`network`, `contact`.`photo`, `contact`.`url`,
192 `contact`.`name-date`, `contact`.`uri-date`, `contact`.`avatar-date`,
193 `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
194 `sign`.`signed_text`, `sign`.`signature`, `sign`.`signer`
195 FROM `item` USE INDEX (`uid_wall_changed`, `uid_type_changed`) $sql_post_table
196 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
197 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
198 LEFT JOIN `sign` ON `sign`.`iid` = `item`.`id`
199 WHERE `item`.`uid` = %d AND `item`.`visible` AND NOT `item`.`moderated` AND `item`.`parent` != 0
200 AND `item`.`wall` AND `item`.`changed` > '%s'
202 ORDER BY `item`.`parent` ".$sort.", `item`.`created` ASC LIMIT 0, 300",
208 // Will check further below if this actually returned results.
209 // We will provide an empty feed if that is the case.
213 $doc = new DOMDocument('1.0', 'utf-8');
214 $doc->formatOutput = true;
216 $alternatelink = $owner['url'];
219 $alternatelink .= "/category/".$category;
222 $author = "dfrn:owner";
226 $root = self::add_header($doc, $owner, $author, $alternatelink, true);
228 // This hook can't work anymore
229 // call_hooks('atom_feed', $atom);
231 if (!count($items) OR $onlyheader) {
232 $atom = trim($doc->saveXML());
234 call_hooks('atom_feed_end', $atom);
239 foreach($items as $item) {
241 // prevent private email from leaking.
242 if($item['network'] == NETWORK_MAIL)
245 // public feeds get html, our own nodes use bbcode
249 // catch any email that's in a public conversation and make sure it doesn't leak
255 $entry = self::entry($doc, $type, $item, $owner, true);
256 $root->appendChild($entry);
260 $atom = trim($doc->saveXML());
262 call_hooks('atom_feed_end', $atom);
268 * @brief Create XML text for DFRN mails
270 * @param array $item message elements
271 * @param array $owner Owner record
273 * @return string DFRN mail
275 public static function mail($item, $owner) {
276 $doc = new DOMDocument('1.0', 'utf-8');
277 $doc->formatOutput = true;
279 $root = self::add_header($doc, $owner, "dfrn:owner", "", false);
281 $mail = $doc->createElement("dfrn:mail");
282 $sender = $doc->createElement("dfrn:sender");
284 xml::add_element($doc, $sender, "dfrn:name", $owner['name']);
285 xml::add_element($doc, $sender, "dfrn:uri", $owner['url']);
286 xml::add_element($doc, $sender, "dfrn:avatar", $owner['thumb']);
288 $mail->appendChild($sender);
290 xml::add_element($doc, $mail, "dfrn:id", $item['uri']);
291 xml::add_element($doc, $mail, "dfrn:in-reply-to", $item['parent-uri']);
292 xml::add_element($doc, $mail, "dfrn:sentdate", datetime_convert('UTC', 'UTC', $item['created'] . '+00:00' , ATOM_TIME));
293 xml::add_element($doc, $mail, "dfrn:subject", $item['title']);
294 xml::add_element($doc, $mail, "dfrn:content", $item['body']);
296 $root->appendChild($mail);
298 return(trim($doc->saveXML()));
302 * @brief Create XML text for DFRN friend suggestions
304 * @param array $item suggestion elements
305 * @param array $owner Owner record
307 * @return string DFRN suggestions
309 public static function fsuggest($item, $owner) {
310 $doc = new DOMDocument('1.0', 'utf-8');
311 $doc->formatOutput = true;
313 $root = self::add_header($doc, $owner, "dfrn:owner", "", false);
315 $suggest = $doc->createElement("dfrn:suggest");
317 xml::add_element($doc, $suggest, "dfrn:url", $item['url']);
318 xml::add_element($doc, $suggest, "dfrn:name", $item['name']);
319 xml::add_element($doc, $suggest, "dfrn:photo", $item['photo']);
320 xml::add_element($doc, $suggest, "dfrn:request", $item['request']);
321 xml::add_element($doc, $suggest, "dfrn:note", $item['note']);
323 $root->appendChild($suggest);
325 return(trim($doc->saveXML()));
329 * @brief Create XML text for DFRN relocations
331 * @param array $owner Owner record
332 * @param int $uid User ID
334 * @return string DFRN relocations
336 public static function relocate($owner, $uid) {
338 /* get site pubkey. this could be a new installation with no site keys*/
339 $pubkey = get_config('system','site_pubkey');
341 $res = new_keypair(1024);
342 set_config('system','site_prvkey', $res['prvkey']);
343 set_config('system','site_pubkey', $res['pubkey']);
346 $rp = q("SELECT `resource-id` , `scale`, type FROM `photo`
347 WHERE `profile` = 1 AND `uid` = %d ORDER BY scale;", $uid);
349 $ext = Photo::supportedTypes();
352 $photos[$p['scale']] = app::get_baseurl().'/photo/'.$p['resource-id'].'-'.$p['scale'].'.'.$ext[$p['type']];
356 $doc = new DOMDocument('1.0', 'utf-8');
357 $doc->formatOutput = true;
359 $root = self::add_header($doc, $owner, "dfrn:owner", "", false);
361 $relocate = $doc->createElement("dfrn:relocate");
363 xml::add_element($doc, $relocate, "dfrn:url", $owner['url']);
364 xml::add_element($doc, $relocate, "dfrn:name", $owner['name']);
365 xml::add_element($doc, $relocate, "dfrn:addr", $owner['addr']);
366 xml::add_element($doc, $relocate, "dfrn:avatar", $owner['avatar']);
367 xml::add_element($doc, $relocate, "dfrn:photo", $photos[4]);
368 xml::add_element($doc, $relocate, "dfrn:thumb", $photos[5]);
369 xml::add_element($doc, $relocate, "dfrn:micro", $photos[6]);
370 xml::add_element($doc, $relocate, "dfrn:request", $owner['request']);
371 xml::add_element($doc, $relocate, "dfrn:confirm", $owner['confirm']);
372 xml::add_element($doc, $relocate, "dfrn:notify", $owner['notify']);
373 xml::add_element($doc, $relocate, "dfrn:poll", $owner['poll']);
374 xml::add_element($doc, $relocate, "dfrn:sitepubkey", get_config('system','site_pubkey'));
376 $root->appendChild($relocate);
378 return(trim($doc->saveXML()));
382 * @brief Adds the header elements for the DFRN protocol
384 * @param object $doc XML document
385 * @param array $owner Owner record
386 * @param string $authorelement Element name for the author
387 * @param string $alternatelink link to profile or category
388 * @param bool $public Is it a header for public posts?
390 * @return object XML root object
392 private function add_header($doc, $owner, $authorelement, $alternatelink = "", $public = false) {
394 if ($alternatelink == "")
395 $alternatelink = $owner['url'];
397 $root = $doc->createElementNS(NAMESPACE_ATOM1, 'feed');
398 $doc->appendChild($root);
400 $root->setAttribute("xmlns:thr", NAMESPACE_THREAD);
401 $root->setAttribute("xmlns:at", NAMESPACE_TOMB);
402 $root->setAttribute("xmlns:media", NAMESPACE_MEDIA);
403 $root->setAttribute("xmlns:dfrn", NAMESPACE_DFRN);
404 $root->setAttribute("xmlns:activity", NAMESPACE_ACTIVITY);
405 $root->setAttribute("xmlns:georss", NAMESPACE_GEORSS);
406 $root->setAttribute("xmlns:poco", NAMESPACE_POCO);
407 $root->setAttribute("xmlns:ostatus", NAMESPACE_OSTATUS);
408 $root->setAttribute("xmlns:statusnet", NAMESPACE_STATUSNET);
410 xml::add_element($doc, $root, "id", app::get_baseurl()."/profile/".$owner["nick"]);
411 xml::add_element($doc, $root, "title", $owner["name"]);
413 $attributes = array("uri" => "https://friendi.ca", "version" => FRIENDICA_VERSION."-".DB_UPDATE_VERSION);
414 xml::add_element($doc, $root, "generator", FRIENDICA_PLATFORM, $attributes);
416 $attributes = array("rel" => "license", "href" => "http://creativecommons.org/licenses/by/3.0/");
417 xml::add_element($doc, $root, "link", "", $attributes);
419 $attributes = array("rel" => "alternate", "type" => "text/html", "href" => $alternatelink);
420 xml::add_element($doc, $root, "link", "", $attributes);
424 // DFRN itself doesn't uses this. But maybe someone else wants to subscribe to the public feed.
425 ostatus::hublinks($doc, $root);
427 $attributes = array("rel" => "salmon", "href" => app::get_baseurl()."/salmon/".$owner["nick"]);
428 xml::add_element($doc, $root, "link", "", $attributes);
430 $attributes = array("rel" => "http://salmon-protocol.org/ns/salmon-replies", "href" => app::get_baseurl()."/salmon/".$owner["nick"]);
431 xml::add_element($doc, $root, "link", "", $attributes);
433 $attributes = array("rel" => "http://salmon-protocol.org/ns/salmon-mention", "href" => app::get_baseurl()."/salmon/".$owner["nick"]);
434 xml::add_element($doc, $root, "link", "", $attributes);
437 // For backward compatibility we keep this element
438 if ($owner['page-flags'] == PAGE_COMMUNITY)
439 xml::add_element($doc, $root, "dfrn:community", 1);
441 // The former element is replaced by this one
442 xml::add_element($doc, $root, "dfrn:account_type", $owner["account-type"]);
444 /// @todo We need a way to transmit the different page flags like "PAGE_PRVGROUP"
446 xml::add_element($doc, $root, "updated", datetime_convert("UTC", "UTC", "now", ATOM_TIME));
448 $author = self::add_author($doc, $owner, $authorelement, $public);
449 $root->appendChild($author);
455 * @brief Adds the author element in the header for the DFRN protocol
457 * @param object $doc XML document
458 * @param array $owner Owner record
459 * @param string $authorelement Element name for the author
461 * @return object XML author object
463 private function add_author($doc, $owner, $authorelement, $public) {
465 // Is the profile hidden or shouldn't be published in the net? Then add the "hide" element
466 $r = q("SELECT `id` FROM `profile` INNER JOIN `user` ON `user`.`uid` = `profile`.`uid`
467 WHERE (`hidewall` OR NOT `net-publish`) AND `user`.`uid` = %d",
468 intval($owner['uid']));
474 $author = $doc->createElement($authorelement);
476 $namdate = datetime_convert('UTC', 'UTC', $owner['name-date'].'+00:00', ATOM_TIME);
477 $uridate = datetime_convert('UTC', 'UTC', $owner['uri-date'].'+00:00', ATOM_TIME);
478 $picdate = datetime_convert('UTC', 'UTC', $owner['avatar-date'].'+00:00', ATOM_TIME);
480 if (!$public OR !$hidewall)
481 $attributes = array("dfrn:updated" => $namdate);
483 $attributes = array();
485 xml::add_element($doc, $author, "name", $owner["name"], $attributes);
486 xml::add_element($doc, $author, "uri", app::get_baseurl().'/profile/'.$owner["nickname"], $attributes);
487 xml::add_element($doc, $author, "dfrn:handle", $owner["addr"], $attributes);
489 $attributes = array("rel" => "photo", "type" => "image/jpeg",
490 "media:width" => 175, "media:height" => 175, "href" => $owner['photo']);
492 if (!$public OR !$hidewall)
493 $attributes["dfrn:updated"] = $picdate;
495 xml::add_element($doc, $author, "link", "", $attributes);
497 $attributes["rel"] = "avatar";
498 xml::add_element($doc, $author, "link", "", $attributes);
501 xml::add_element($doc, $author, "dfrn:hide", "true");
503 // The following fields will only be generated if the data isn't meant for a public feed
507 $birthday = feed_birthday($owner['uid'], $owner['timezone']);
510 xml::add_element($doc, $author, "dfrn:birthday", $birthday);
512 // Only show contact details when we are allowed to
513 $r = q("SELECT `profile`.`about`, `profile`.`name`, `profile`.`homepage`, `user`.`nickname`,
514 `user`.`timezone`, `profile`.`locality`, `profile`.`region`, `profile`.`country-name`,
515 `profile`.`pub_keywords`, `profile`.`xmpp`, `profile`.`dob`
517 INNER JOIN `user` ON `user`.`uid` = `profile`.`uid`
518 WHERE `profile`.`is-default` AND NOT `user`.`hidewall` AND `user`.`uid` = %d",
519 intval($owner['uid']));
523 xml::add_element($doc, $author, "poco:displayName", $profile["name"]);
524 xml::add_element($doc, $author, "poco:updated", $namdate);
526 if (trim($profile["dob"]) != "0000-00-00")
527 xml::add_element($doc, $author, "poco:birthday", "0000-".date("m-d", strtotime($profile["dob"])));
529 xml::add_element($doc, $author, "poco:note", $profile["about"]);
530 xml::add_element($doc, $author, "poco:preferredUsername", $profile["nickname"]);
532 $savetz = date_default_timezone_get();
533 date_default_timezone_set($profile["timezone"]);
534 xml::add_element($doc, $author, "poco:utcOffset", date("P"));
535 date_default_timezone_set($savetz);
537 if (trim($profile["homepage"]) != "") {
538 $urls = $doc->createElement("poco:urls");
539 xml::add_element($doc, $urls, "poco:type", "homepage");
540 xml::add_element($doc, $urls, "poco:value", $profile["homepage"]);
541 xml::add_element($doc, $urls, "poco:primary", "true");
542 $author->appendChild($urls);
545 if (trim($profile["pub_keywords"]) != "") {
546 $keywords = explode(",", $profile["pub_keywords"]);
548 foreach ($keywords AS $keyword)
549 xml::add_element($doc, $author, "poco:tags", trim($keyword));
553 if (trim($profile["xmpp"]) != "") {
554 $ims = $doc->createElement("poco:ims");
555 xml::add_element($doc, $ims, "poco:type", "xmpp");
556 xml::add_element($doc, $ims, "poco:value", $profile["xmpp"]);
557 xml::add_element($doc, $ims, "poco:primary", "true");
558 $author->appendChild($ims);
561 if (trim($profile["locality"].$profile["region"].$profile["country-name"]) != "") {
562 $element = $doc->createElement("poco:address");
564 xml::add_element($doc, $element, "poco:formatted", formatted_location($profile));
566 if (trim($profile["locality"]) != "")
567 xml::add_element($doc, $element, "poco:locality", $profile["locality"]);
569 if (trim($profile["region"]) != "")
570 xml::add_element($doc, $element, "poco:region", $profile["region"]);
572 if (trim($profile["country-name"]) != "")
573 xml::add_element($doc, $element, "poco:country", $profile["country-name"]);
575 $author->appendChild($element);
583 * @brief Adds the author elements in the "entry" elements of the DFRN protocol
585 * @param object $doc XML document
586 * @param string $element Element name for the author
587 * @param string $contact_url Link of the contact
588 * @param array $items Item elements
590 * @return object XML author object
592 private function add_entry_author($doc, $element, $contact_url, $item) {
594 $contact = get_contact_details_by_url($contact_url, $item["uid"]);
596 $author = $doc->createElement($element);
597 xml::add_element($doc, $author, "name", $contact["name"]);
598 xml::add_element($doc, $author, "uri", $contact["url"]);
599 xml::add_element($doc, $author, "dfrn:handle", $contact["addr"]);
602 /// - Check real image type and image size
603 /// - Check which of these boths elements we should use
606 "type" => "image/jpeg",
608 "media:height" => 80,
609 "href" => $contact["photo"]);
610 xml::add_element($doc, $author, "link", "", $attributes);
614 "type" => "image/jpeg",
616 "media:height" => 80,
617 "href" => $contact["photo"]);
618 xml::add_element($doc, $author, "link", "", $attributes);
624 * @brief Adds the activity elements
626 * @param object $doc XML document
627 * @param string $element Element name for the activity
628 * @param string $activity activity value
630 * @return object XML activity object
632 private function create_activity($doc, $element, $activity) {
635 $entry = $doc->createElement($element);
637 $r = parse_xml_string($activity, false);
641 xml::add_element($doc, $entry, "activity:object-type", $r->type);
643 xml::add_element($doc, $entry, "id", $r->id);
645 xml::add_element($doc, $entry, "title", $r->title);
647 if(substr($r->link,0,1) == '<') {
648 if(strstr($r->link,'&') && (! strstr($r->link,'&')))
649 $r->link = str_replace('&','&', $r->link);
651 $r->link = preg_replace('/\<link(.*?)\"\>/','<link$1"/>',$r->link);
653 // XML does need a single element as root element so we add a dummy element here
654 $data = parse_xml_string("<dummy>".$r->link."</dummy>", false);
655 if (is_object($data)) {
656 foreach ($data->link AS $link) {
657 $attributes = array();
658 foreach ($link->attributes() AS $parameter => $value)
659 $attributes[$parameter] = $value;
660 xml::add_element($doc, $entry, "link", "", $attributes);
664 $attributes = array("rel" => "alternate", "type" => "text/html", "href" => $r->link);
665 xml::add_element($doc, $entry, "link", "", $attributes);
669 xml::add_element($doc, $entry, "content", bbcode($r->content), array("type" => "html"));
678 * @brief Adds the elements for attachments
680 * @param object $doc XML document
681 * @param object $root XML root
682 * @param array $item Item element
684 * @return object XML attachment object
686 private function get_attachment($doc, $root, $item) {
687 $arr = explode('[/attach],',$item['attach']);
689 foreach($arr as $r) {
691 $cnt = preg_match('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\" title=\"(.*?)\"|',$r,$matches);
693 $attributes = array("rel" => "enclosure",
694 "href" => $matches[1],
695 "type" => $matches[3]);
697 if(intval($matches[2]))
698 $attributes["length"] = intval($matches[2]);
700 if(trim($matches[4]) != "")
701 $attributes["title"] = trim($matches[4]);
703 xml::add_element($doc, $root, "link", "", $attributes);
710 * @brief Adds the "entry" elements for the DFRN protocol
712 * @param object $doc XML document
713 * @param string $type "text" or "html"
714 * @param array $item Item element
715 * @param array $owner Owner record
716 * @param bool $comment Trigger the sending of the "comment" element
717 * @param int $cid Contact ID of the recipient
719 * @return object XML entry object
721 private function entry($doc, $type, $item, $owner, $comment = false, $cid = 0) {
723 $mentioned = array();
728 if($item['deleted']) {
729 $attributes = array("ref" => $item['uri'], "when" => datetime_convert('UTC','UTC',$item['edited'] . '+00:00',ATOM_TIME));
730 return xml::create_element($doc, "at:deleted-entry", "", $attributes);
733 $entry = $doc->createElement("entry");
735 if($item['allow_cid'] || $item['allow_gid'] || $item['deny_cid'] || $item['deny_gid'])
736 $body = fix_private_photos($item['body'],$owner['uid'],$item,$cid);
738 $body = $item['body'];
740 // Remove the abstract element. It is only locally important.
741 $body = remove_abstract($body);
743 if ($type == 'html') {
746 if ($item['title'] != "")
747 $htmlbody = "[b]".$item['title']."[/b]\n\n".$htmlbody;
749 $htmlbody = bbcode($htmlbody, false, false, 7);
752 $author = self::add_entry_author($doc, "author", $item["author-link"], $item);
753 $entry->appendChild($author);
755 $dfrnowner = self::add_entry_author($doc, "dfrn:owner", $item["owner-link"], $item);
756 $entry->appendChild($dfrnowner);
758 if(($item['parent'] != $item['id']) || ($item['parent-uri'] !== $item['uri']) || (($item['thr-parent'] !== '') && ($item['thr-parent'] !== $item['uri']))) {
759 $parent = q("SELECT `guid` FROM `item` WHERE `id` = %d", intval($item["parent"]));
760 $parent_item = (($item['thr-parent']) ? $item['thr-parent'] : $item['parent-uri']);
761 $attributes = array("ref" => $parent_item, "type" => "text/html",
762 "href" => app::get_baseurl().'/display/'.$parent[0]['guid'],
763 "dfrn:diaspora_guid" => $parent[0]['guid']);
764 xml::add_element($doc, $entry, "thr:in-reply-to", "", $attributes);
767 xml::add_element($doc, $entry, "id", $item["uri"]);
768 xml::add_element($doc, $entry, "title", $item["title"]);
770 xml::add_element($doc, $entry, "published", datetime_convert("UTC","UTC",$item["created"]."+00:00",ATOM_TIME));
771 xml::add_element($doc, $entry, "updated", datetime_convert("UTC","UTC",$item["edited"]."+00:00",ATOM_TIME));
773 // "dfrn:env" is used to read the content
774 xml::add_element($doc, $entry, "dfrn:env", base64url_encode($body, true));
776 // The "content" field is not read by the receiver. We could remove it when the type is "text"
777 // We keep it at the moment, maybe there is some old version that doesn't read "dfrn:env"
778 xml::add_element($doc, $entry, "content", (($type == 'html') ? $htmlbody : $body), array("type" => $type));
780 // We save this value in "plink". Maybe we should read it from there as well?
781 xml::add_element($doc, $entry, "link", "", array("rel" => "alternate", "type" => "text/html",
782 "href" => app::get_baseurl()."/display/".$item["guid"]));
784 // "comment-allow" is some old fashioned stuff for old Friendica versions.
785 // It is included in the rewritten code for completeness
787 xml::add_element($doc, $entry, "dfrn:comment-allow", intval($item['last-child']));
789 if($item['location'])
790 xml::add_element($doc, $entry, "dfrn:location", $item['location']);
793 xml::add_element($doc, $entry, "georss:point", $item['coord']);
795 if(($item['private']) || strlen($item['allow_cid']) || strlen($item['allow_gid']) || strlen($item['deny_cid']) || strlen($item['deny_gid']))
796 xml::add_element($doc, $entry, "dfrn:private", (($item['private']) ? $item['private'] : 1));
799 xml::add_element($doc, $entry, "dfrn:extid", $item['extid']);
801 if($item['bookmark'])
802 xml::add_element($doc, $entry, "dfrn:bookmark", "true");
805 xml::add_element($doc, $entry, "statusnet:notice_info", "", array("local_id" => $item['id'], "source" => $item['app']));
807 xml::add_element($doc, $entry, "dfrn:diaspora_guid", $item["guid"]);
809 // The signed text contains the content in Markdown, the sender handle and the signatur for the content
810 // It is needed for relayed comments to Diaspora.
811 if($item['signed_text']) {
812 $sign = base64_encode(json_encode(array('signed_text' => $item['signed_text'],'signature' => $item['signature'],'signer' => $item['signer'])));
813 xml::add_element($doc, $entry, "dfrn:diaspora_signature", $sign);
816 xml::add_element($doc, $entry, "activity:verb", construct_verb($item));
818 if ($item['object-type'] != "")
819 xml::add_element($doc, $entry, "activity:object-type", $item['object-type']);
820 elseif ($item['id'] == $item['parent'])
821 xml::add_element($doc, $entry, "activity:object-type", ACTIVITY_OBJ_NOTE);
823 xml::add_element($doc, $entry, "activity:object-type", ACTIVITY_OBJ_COMMENT);
825 $actobj = self::create_activity($doc, "activity:object", $item['object']);
827 $entry->appendChild($actobj);
829 $actarg = self::create_activity($doc, "activity:target", $item['target']);
831 $entry->appendChild($actarg);
833 $tags = item_getfeedtags($item);
837 if (($type != 'html') OR ($t[0] != "@"))
838 xml::add_element($doc, $entry, "category", "", array("scheme" => "X-DFRN:".$t[0].":".$t[1], "term" => $t[2]));
844 $mentioned[$t[1]] = $t[1];
846 foreach ($mentioned AS $mention) {
847 $r = q("SELECT `forum`, `prv` FROM `contact` WHERE `uid` = %d AND `nurl` = '%s'",
848 intval($owner["uid"]),
849 dbesc(normalise_link($mention)));
850 if ($r[0]["forum"] OR $r[0]["prv"])
851 xml::add_element($doc, $entry, "link", "", array("rel" => "mentioned",
852 "ostatus:object-type" => ACTIVITY_OBJ_GROUP,
853 "href" => $mention));
855 xml::add_element($doc, $entry, "link", "", array("rel" => "mentioned",
856 "ostatus:object-type" => ACTIVITY_OBJ_PERSON,
857 "href" => $mention));
860 self::get_attachment($doc, $entry, $item);
866 * @brief Delivers the atom content to the contacts
868 * @param array $owner Owner record
869 * @param array $contactr Contact record of the receiver
870 * @param string $atom Content that will be transmitted
871 * @param bool $dissolve (to be documented)
873 * @return int Deliver status. -1 means an error.
875 public static function deliver($owner,$contact,$atom, $dissolve = false) {
879 $idtosend = $orig_id = (($contact['dfrn-id']) ? $contact['dfrn-id'] : $contact['issued-id']);
881 if($contact['duplex'] && $contact['dfrn-id'])
882 $idtosend = '0:' . $orig_id;
883 if($contact['duplex'] && $contact['issued-id'])
884 $idtosend = '1:' . $orig_id;
887 $rino = get_config('system','rino_encrypt');
888 $rino = intval($rino);
889 // use RINO1 if mcrypt isn't installed and RINO2 was selected
890 if ($rino==2 and !function_exists('mcrypt_create_iv')) $rino=1;
892 logger("Local rino version: ". $rino, LOGGER_DEBUG);
894 $ssl_val = intval(get_config('system','ssl_policy'));
898 case SSL_POLICY_FULL:
899 $ssl_policy = 'full';
901 case SSL_POLICY_SELFSIGN:
902 $ssl_policy = 'self';
904 case SSL_POLICY_NONE:
906 $ssl_policy = 'none';
910 $url = $contact['notify'] . '&dfrn_id=' . $idtosend . '&dfrn_version=' . DFRN_PROTOCOL_VERSION . (($rino) ? '&rino='.$rino : '');
912 logger('dfrn_deliver: ' . $url);
914 $xml = fetch_url($url);
916 $curl_stat = $a->get_curl_code();
918 return(-1); // timed out
920 logger('dfrn_deliver: ' . $xml, LOGGER_DATA);
925 if(strpos($xml,'<?xml') === false) {
926 logger('dfrn_deliver: no valid XML returned');
927 logger('dfrn_deliver: returned XML: ' . $xml, LOGGER_DATA);
931 $res = parse_xml_string($xml);
933 if((intval($res->status) != 0) || (! strlen($res->challenge)) || (! strlen($res->dfrn_id)))
934 return (($res->status) ? $res->status : 3);
937 $sent_dfrn_id = hex2bin((string) $res->dfrn_id);
938 $challenge = hex2bin((string) $res->challenge);
939 $perm = (($res->perm) ? $res->perm : null);
940 $dfrn_version = (float) (($res->dfrn_version) ? $res->dfrn_version : 2.0);
941 $rino_remote_version = intval($res->rino);
942 $page = (($owner['page-flags'] == PAGE_COMMUNITY) ? 1 : 0);
944 logger("Remote rino version: ".$rino_remote_version." for ".$contact["url"], LOGGER_DEBUG);
946 if($owner['page-flags'] == PAGE_PRVGROUP)
952 if((($perm == 'rw') && (! intval($contact['writable'])))
953 || (($perm == 'r') && (intval($contact['writable'])))) {
954 q("update contact set writable = %d where id = %d",
955 intval(($perm == 'rw') ? 1 : 0),
956 intval($contact['id'])
958 $contact['writable'] = (string) 1 - intval($contact['writable']);
962 if(($contact['duplex'] && strlen($contact['pubkey']))
963 || ($owner['page-flags'] == PAGE_COMMUNITY && strlen($contact['pubkey']))
964 || ($contact['rel'] == CONTACT_IS_SHARING && strlen($contact['pubkey']))) {
965 openssl_public_decrypt($sent_dfrn_id,$final_dfrn_id,$contact['pubkey']);
966 openssl_public_decrypt($challenge,$postvars['challenge'],$contact['pubkey']);
968 openssl_private_decrypt($sent_dfrn_id,$final_dfrn_id,$contact['prvkey']);
969 openssl_private_decrypt($challenge,$postvars['challenge'],$contact['prvkey']);
972 $final_dfrn_id = substr($final_dfrn_id, 0, strpos($final_dfrn_id, '.'));
974 if(strpos($final_dfrn_id,':') == 1)
975 $final_dfrn_id = substr($final_dfrn_id,2);
977 if($final_dfrn_id != $orig_id) {
978 logger('dfrn_deliver: wrong dfrn_id.');
979 // did not decode properly - cannot trust this site
983 $postvars['dfrn_id'] = $idtosend;
984 $postvars['dfrn_version'] = DFRN_PROTOCOL_VERSION;
986 $postvars['dissolve'] = '1';
989 if((($contact['rel']) && ($contact['rel'] != CONTACT_IS_SHARING) && (! $contact['blocked'])) || ($owner['page-flags'] == PAGE_COMMUNITY)) {
990 $postvars['data'] = $atom;
991 $postvars['perm'] = 'rw';
993 $postvars['data'] = str_replace('<dfrn:comment-allow>1','<dfrn:comment-allow>0',$atom);
994 $postvars['perm'] = 'r';
997 $postvars['ssl_policy'] = $ssl_policy;
1000 $postvars['page'] = $page;
1003 if($rino>0 && $rino_remote_version>0 && (! $dissolve)) {
1004 logger('rino version: '. $rino_remote_version);
1006 switch($rino_remote_version) {
1008 // Deprecated rino version!
1009 $key = substr(random_string(),0,16);
1010 $data = aes_encrypt($postvars['data'],$key);
1013 // RINO 2 based on php-encryption
1015 $key = Crypto::createNewRandomKey();
1016 } catch (CryptoTestFailed $ex) {
1017 logger('Cannot safely create a key');
1019 } catch (CannotPerformOperation $ex) {
1020 logger('Cannot safely create a key');
1024 $data = Crypto::encrypt($postvars['data'], $key);
1025 } catch (CryptoTestFailed $ex) {
1026 logger('Cannot safely perform encryption');
1028 } catch (CannotPerformOperation $ex) {
1029 logger('Cannot safely perform encryption');
1034 logger("rino: invalid requested verision '$rino_remote_version'");
1038 $postvars['rino'] = $rino_remote_version;
1039 $postvars['data'] = bin2hex($data);
1041 #logger('rino: sent key = ' . $key, LOGGER_DEBUG);
1044 if($dfrn_version >= 2.1) {
1045 if(($contact['duplex'] && strlen($contact['pubkey']))
1046 || ($owner['page-flags'] == PAGE_COMMUNITY && strlen($contact['pubkey']))
1047 || ($contact['rel'] == CONTACT_IS_SHARING && strlen($contact['pubkey'])))
1049 openssl_public_encrypt($key,$postvars['key'],$contact['pubkey']);
1051 openssl_private_encrypt($key,$postvars['key'],$contact['prvkey']);
1054 if(($contact['duplex'] && strlen($contact['prvkey'])) || ($owner['page-flags'] == PAGE_COMMUNITY))
1055 openssl_private_encrypt($key,$postvars['key'],$contact['prvkey']);
1057 openssl_public_encrypt($key,$postvars['key'],$contact['pubkey']);
1061 logger('md5 rawkey ' . md5($postvars['key']));
1063 $postvars['key'] = bin2hex($postvars['key']);
1067 logger('dfrn_deliver: ' . "SENDING: " . print_r($postvars,true), LOGGER_DATA);
1069 $xml = post_url($contact['notify'],$postvars);
1071 logger('dfrn_deliver: ' . "RECEIVED: " . $xml, LOGGER_DATA);
1073 $curl_stat = $a->get_curl_code();
1074 if((! $curl_stat) || (! strlen($xml)))
1075 return(-1); // timed out
1077 if(($curl_stat == 503) && (stristr($a->get_curl_headers(),'retry-after')))
1080 if(strpos($xml,'<?xml') === false) {
1081 logger('dfrn_deliver: phase 2: no valid XML returned');
1082 logger('dfrn_deliver: phase 2: returned XML: ' . $xml, LOGGER_DATA);
1086 if($contact['term-date'] != '0000-00-00 00:00:00') {
1087 logger("dfrn_deliver: $url back from the dead - removing mark for death");
1088 require_once('include/Contact.php');
1089 unmark_for_death($contact);
1092 $res = parse_xml_string($xml);
1094 return $res->status;
1098 * @brief Add new birthday event for this person
1100 * @param array $contact Contact record
1101 * @param string $birthday Birthday of the contact
1104 private function birthday_event($contact, $birthday) {
1106 logger("updating birthday: ".$birthday." for contact ".$contact["id"]);
1108 $bdtext = sprintf(t("%s\'s birthday"), $contact["name"]);
1109 $bdtext2 = sprintf(t("Happy Birthday %s"), " [url=".$contact["url"]."]".$contact["name"]."[/url]") ;
1112 $r = q("INSERT INTO `event` (`uid`,`cid`,`created`,`edited`,`start`,`finish`,`summary`,`desc`,`type`)
1113 VALUES ( %d, %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s') ",
1114 intval($contact["uid"]),
1115 intval($contact["id"]),
1116 dbesc(datetime_convert()),
1117 dbesc(datetime_convert()),
1118 dbesc(datetime_convert("UTC","UTC", $birthday)),
1119 dbesc(datetime_convert("UTC","UTC", $birthday." + 1 day ")),
1127 * @brief Fetch the author data from head or entry items
1129 * @param object $xpath XPath object
1130 * @param object $context In which context should the data be searched
1131 * @param array $importer Record of the importer user mixed with contact of the content
1132 * @param string $element Element name from which the data is fetched
1133 * @param bool $onlyfetch Should the data only be fetched or should it update the contact record as well
1135 * @return Returns an array with relevant data of the author
1137 private function fetchauthor($xpath, $context, $importer, $element, $onlyfetch, $xml = "") {
1140 $author["name"] = $xpath->evaluate($element."/atom:name/text()", $context)->item(0)->nodeValue;
1141 $author["link"] = $xpath->evaluate($element."/atom:uri/text()", $context)->item(0)->nodeValue;
1143 $r = q("SELECT `id`, `uid`, `url`, `network`, `avatar-date`, `name-date`, `uri-date`, `addr`,
1144 `name`, `nick`, `about`, `location`, `keywords`, `xmpp`, `bdyear`, `bd`, `hidden`, `contact-type`
1145 FROM `contact` WHERE `uid` = %d AND `nurl` = '%s' AND `network` != '%s'",
1146 intval($importer["uid"]), dbesc(normalise_link($author["link"])), dbesc(NETWORK_STATUSNET));
1149 $author["contact-id"] = $r[0]["id"];
1150 $author["network"] = $r[0]["network"];
1153 logger("Contact ".$author["link"]." wasn't found for user ".$importer["uid"]." XML: ".$xml, LOGGER_DEBUG);
1155 $author["contact-id"] = $importer["id"];
1156 $author["network"] = $importer["network"];
1160 // Until now we aren't serving different sizes - but maybe later
1161 $avatarlist = array();
1162 // @todo check if "avatar" or "photo" would be the best field in the specification
1163 $avatars = $xpath->query($element."/atom:link[@rel='avatar']", $context);
1164 foreach($avatars AS $avatar) {
1167 foreach($avatar->attributes AS $attributes) {
1168 if ($attributes->name == "href")
1169 $href = $attributes->textContent;
1170 if ($attributes->name == "width")
1171 $width = $attributes->textContent;
1172 if ($attributes->name == "updated")
1173 $contact["avatar-date"] = $attributes->textContent;
1175 if (($width > 0) AND ($href != ""))
1176 $avatarlist[$width] = $href;
1178 if (count($avatarlist) > 0) {
1179 krsort($avatarlist);
1180 $author["avatar"] = current($avatarlist);
1183 if ($r AND !$onlyfetch) {
1184 logger("Check if contact details for contact ".$r[0]["id"]." (".$r[0]["nick"].") have to be updated.", LOGGER_DEBUG);
1186 $poco = array("url" => $contact["url"]);
1188 // When was the last change to name or uri?
1189 $name_element = $xpath->query($element."/atom:name", $context)->item(0);
1190 foreach($name_element->attributes AS $attributes)
1191 if ($attributes->name == "updated")
1192 $poco["name-date"] = $attributes->textContent;
1194 $link_element = $xpath->query($element."/atom:link", $context)->item(0);
1195 foreach($link_element->attributes AS $attributes)
1196 if ($attributes->name == "updated")
1197 $poco["uri-date"] = $attributes->textContent;
1199 // Update contact data
1200 $value = $xpath->evaluate($element."/dfrn:handle/text()", $context)->item(0)->nodeValue;
1202 $poco["addr"] = $value;
1204 $value = $xpath->evaluate($element."/poco:displayName/text()", $context)->item(0)->nodeValue;
1206 $poco["name"] = $value;
1208 $value = $xpath->evaluate($element."/poco:preferredUsername/text()", $context)->item(0)->nodeValue;
1210 $poco["nick"] = $value;
1212 $value = $xpath->evaluate($element."/poco:note/text()", $context)->item(0)->nodeValue;
1214 $poco["about"] = $value;
1216 $value = $xpath->evaluate($element."/poco:address/poco:formatted/text()", $context)->item(0)->nodeValue;
1218 $poco["location"] = $value;
1220 /// @todo Only search for elements with "poco:type" = "xmpp"
1221 $value = $xpath->evaluate($element."/poco:ims/poco:value/text()", $context)->item(0)->nodeValue;
1223 $poco["xmpp"] = $value;
1225 /// @todo Add support for the following fields that we don't support by now in the contact table:
1226 /// - poco:utcOffset
1232 // If the "hide" element is present then the profile isn't searchable.
1233 $hide = intval($xpath->evaluate($element."/dfrn:hide/text()", $context)->item(0)->nodeValue == "true");
1235 logger("Hidden status for contact ".$contact["url"].": ".$hide, LOGGER_DEBUG);
1237 // If the contact isn't searchable then set the contact to "hidden".
1238 // Problem: This can be manually overridden by the user.
1240 $contact["hidden"] = true;
1242 // Save the keywords into the contact table
1244 $tagelements = $xpath->evaluate($element."/poco:tags/text()", $context);
1245 foreach($tagelements AS $tag)
1246 $tags[$tag->nodeValue] = $tag->nodeValue;
1249 $poco["keywords"] = implode(", ", $tags);
1251 // "dfrn:birthday" contains the birthday converted to UTC
1252 $old_bdyear = $contact["bdyear"];
1254 $birthday = $xpath->evaluate($element."/dfrn:birthday/text()", $context)->item(0)->nodeValue;
1256 if (strtotime($birthday) > time()) {
1257 $bd_timestamp = strtotime($birthday);
1259 $poco["bdyear"] = date("Y", $bd_timestamp);
1262 // "poco:birthday" is the birthday in the format "yyyy-mm-dd"
1263 $value = $xpath->evaluate($element."/poco:birthday/text()", $context)->item(0)->nodeValue;
1265 if (!in_array($value, array("", "0000-00-00"))) {
1266 $bdyear = date("Y");
1267 $value = str_replace("0000", $bdyear, $value);
1269 if (strtotime($value) < time()) {
1270 $value = str_replace($bdyear, $bdyear + 1, $value);
1271 $bdyear = $bdyear + 1;
1274 $poco["bd"] = $value;
1277 $contact = array_merge($contact, $poco);
1279 if ($old_bdyear != $contact["bdyear"])
1280 self::birthday_event($contact, $birthday);
1282 // Get all field names
1284 foreach ($r[0] AS $field => $data)
1285 $fields[$field] = $data;
1287 unset($fields["id"]);
1288 unset($fields["uid"]);
1289 unset($fields["url"]);
1290 unset($fields["avatar-date"]);
1291 unset($fields["name-date"]);
1292 unset($fields["uri-date"]);
1294 // Update check for this field has to be done differently
1295 $datefields = array("name-date", "uri-date");
1296 foreach ($datefields AS $field)
1297 if (strtotime($contact[$field]) > strtotime($r[0][$field])) {
1298 logger("Difference for contact ".$contact["id"]." in field '".$field."'. New value: '".$contact[$field]."', old value '".$r[0][$field]."'", LOGGER_DEBUG);
1302 foreach ($fields AS $field => $data)
1303 if ($contact[$field] != $r[0][$field]) {
1304 logger("Difference for contact ".$contact["id"]." in field '".$field."'. New value: '".$contact[$field]."', old value '".$r[0][$field]."'", LOGGER_DEBUG);
1309 logger("Update contact data for contact ".$contact["id"]." (".$contact["nick"].")", LOGGER_DEBUG);
1311 q("UPDATE `contact` SET `name` = '%s', `nick` = '%s', `about` = '%s', `location` = '%s',
1312 `addr` = '%s', `keywords` = '%s', `bdyear` = '%s', `bd` = '%s', `hidden` = %d,
1313 `xmpp` = '%s', `name-date` = '%s', `uri-date` = '%s'
1314 WHERE `id` = %d AND `network` = '%s'",
1315 dbesc($contact["name"]), dbesc($contact["nick"]), dbesc($contact["about"]), dbesc($contact["location"]),
1316 dbesc($contact["addr"]), dbesc($contact["keywords"]), dbesc($contact["bdyear"]),
1317 dbesc($contact["bd"]), intval($contact["hidden"]), dbesc($contact["xmpp"]),
1318 dbesc($contact["name-date"]), dbesc($contact["uri-date"]),
1319 intval($contact["id"]), dbesc($contact["network"]));
1322 update_contact_avatar($author["avatar"], $importer["uid"], $contact["id"],
1323 (strtotime($contact["avatar-date"]) > strtotime($r[0]["avatar-date"])));
1325 // The generation is a sign for the reliability of the provided data.
1326 // It is used in the socgraph.php to prevent that old contact data
1327 // that was relayed over several servers can overwrite contact
1328 // data that we received directly.
1330 $poco["generation"] = 2;
1331 $poco["photo"] = $author["avatar"];
1332 $poco["hide"] = $hide;
1333 $poco["contact-type"] = $contact["contact-type"];
1334 update_gcontact($poco);
1341 * @brief Transforms activity objects into an XML string
1343 * @param object $xpath XPath object
1344 * @param object $activity Activity object
1345 * @param text $element element name
1347 * @return string XML string
1349 private function transform_activity($xpath, $activity, $element) {
1350 if (!is_object($activity))
1353 $obj_doc = new DOMDocument("1.0", "utf-8");
1354 $obj_doc->formatOutput = true;
1356 $obj_element = $obj_doc->createElementNS(NAMESPACE_ATOM1, $element);
1358 $activity_type = $xpath->query("activity:object-type/text()", $activity)->item(0)->nodeValue;
1359 xml::add_element($obj_doc, $obj_element, "type", $activity_type);
1361 $id = $xpath->query("atom:id", $activity)->item(0);
1363 $obj_element->appendChild($obj_doc->importNode($id, true));
1365 $title = $xpath->query("atom:title", $activity)->item(0);
1366 if (is_object($title))
1367 $obj_element->appendChild($obj_doc->importNode($title, true));
1369 $links = $xpath->query("atom:link", $activity);
1370 if (is_object($links))
1371 foreach ($links AS $link)
1372 $obj_element->appendChild($obj_doc->importNode($link, true));
1374 $content = $xpath->query("atom:content", $activity)->item(0);
1375 if (is_object($content))
1376 $obj_element->appendChild($obj_doc->importNode($content, true));
1378 $obj_doc->appendChild($obj_element);
1380 $objxml = $obj_doc->saveXML($obj_element);
1382 // @todo This isn't totally clean. We should find a way to transform the namespaces
1383 $objxml = str_replace("<".$element.' xmlns="http://www.w3.org/2005/Atom">', "<".$element.">", $objxml);
1388 * @brief Processes the mail elements
1390 * @param object $xpath XPath object
1391 * @param object $mail mail elements
1392 * @param array $importer Record of the importer user mixed with contact of the content
1394 private function process_mail($xpath, $mail, $importer) {
1396 logger("Processing mails");
1399 $msg["uid"] = $importer["importer_uid"];
1400 $msg["from-name"] = $xpath->query("dfrn:sender/dfrn:name/text()", $mail)->item(0)->nodeValue;
1401 $msg["from-url"] = $xpath->query("dfrn:sender/dfrn:uri/text()", $mail)->item(0)->nodeValue;
1402 $msg["from-photo"] = $xpath->query("dfrn:sender/dfrn:avatar/text()", $mail)->item(0)->nodeValue;
1403 $msg["contact-id"] = $importer["id"];
1404 $msg["uri"] = $xpath->query("dfrn:id/text()", $mail)->item(0)->nodeValue;
1405 $msg["parent-uri"] = $xpath->query("dfrn:in-reply-to/text()", $mail)->item(0)->nodeValue;
1406 $msg["created"] = $xpath->query("dfrn:sentdate/text()", $mail)->item(0)->nodeValue;
1407 $msg["title"] = $xpath->query("dfrn:subject/text()", $mail)->item(0)->nodeValue;
1408 $msg["body"] = $xpath->query("dfrn:content/text()", $mail)->item(0)->nodeValue;
1410 $msg["replied"] = 0;
1414 $r = dbq("INSERT INTO `mail` (`".implode("`, `", array_keys($msg))."`) VALUES ('".implode("', '", array_values($msg))."')");
1416 // send notifications.
1418 $notif_params = array(
1419 "type" => NOTIFY_MAIL,
1420 "notify_flags" => $importer["notify-flags"],
1421 "language" => $importer["language"],
1422 "to_name" => $importer["username"],
1423 "to_email" => $importer["email"],
1424 "uid" => $importer["importer_uid"],
1426 "source_name" => $msg["from-name"],
1427 "source_link" => $importer["url"],
1428 "source_photo" => $importer["thumb"],
1429 "verb" => ACTIVITY_POST,
1433 notification($notif_params);
1435 logger("Mail is processed, notification was sent.");
1439 * @brief Processes the suggestion elements
1441 * @param object $xpath XPath object
1442 * @param object $suggestion suggestion elements
1443 * @param array $importer Record of the importer user mixed with contact of the content
1445 private function process_suggestion($xpath, $suggestion, $importer) {
1447 logger("Processing suggestions");
1450 $suggest["uid"] = $importer["importer_uid"];
1451 $suggest["cid"] = $importer["id"];
1452 $suggest["url"] = $xpath->query("dfrn:url/text()", $suggestion)->item(0)->nodeValue;
1453 $suggest["name"] = $xpath->query("dfrn:name/text()", $suggestion)->item(0)->nodeValue;
1454 $suggest["photo"] = $xpath->query("dfrn:photo/text()", $suggestion)->item(0)->nodeValue;
1455 $suggest["request"] = $xpath->query("dfrn:request/text()", $suggestion)->item(0)->nodeValue;
1456 $suggest["body"] = $xpath->query("dfrn:note/text()", $suggestion)->item(0)->nodeValue;
1458 // Does our member already have a friend matching this description?
1460 $r = q("SELECT `id` FROM `contact` WHERE `name` = '%s' AND `nurl` = '%s' AND `uid` = %d LIMIT 1",
1461 dbesc($suggest["name"]),
1462 dbesc(normalise_link($suggest["url"])),
1463 intval($suggest["uid"])
1468 // Do we already have an fcontact record for this person?
1471 $r = q("SELECT `id` FROM `fcontact` WHERE `url` = '%s' AND `name` = '%s' AND `request` = '%s' LIMIT 1",
1472 dbesc($suggest["url"]),
1473 dbesc($suggest["name"]),
1474 dbesc($suggest["request"])
1479 // OK, we do. Do we already have an introduction for this person ?
1480 $r = q("SELECT `id` FROM `intro` WHERE `uid` = %d AND `fid` = %d LIMIT 1",
1481 intval($suggest["uid"]),
1488 $r = q("INSERT INTO `fcontact` (`name`,`url`,`photo`,`request`) VALUES ('%s', '%s', '%s', '%s')",
1489 dbesc($suggest["name"]),
1490 dbesc($suggest["url"]),
1491 dbesc($suggest["photo"]),
1492 dbesc($suggest["request"])
1494 $r = q("SELECT `id` FROM `fcontact` WHERE `url` = '%s' AND `name` = '%s' AND `request` = '%s' LIMIT 1",
1495 dbesc($suggest["url"]),
1496 dbesc($suggest["name"]),
1497 dbesc($suggest["request"])
1502 // database record did not get created. Quietly give up.
1506 $hash = random_string();
1508 $r = q("INSERT INTO `intro` (`uid`, `fid`, `contact-id`, `note`, `hash`, `datetime`, `blocked`)
1509 VALUES(%d, %d, %d, '%s', '%s', '%s', %d)",
1510 intval($suggest["uid"]),
1512 intval($suggest["cid"]),
1513 dbesc($suggest["body"]),
1515 dbesc(datetime_convert()),
1520 "type" => NOTIFY_SUGGEST,
1521 "notify_flags" => $importer["notify-flags"],
1522 "language" => $importer["language"],
1523 "to_name" => $importer["username"],
1524 "to_email" => $importer["email"],
1525 "uid" => $importer["importer_uid"],
1527 "link" => App::get_baseurl()."/notifications/intros",
1528 "source_name" => $importer["name"],
1529 "source_link" => $importer["url"],
1530 "source_photo" => $importer["photo"],
1531 "verb" => ACTIVITY_REQ_FRIEND,
1540 * @brief Processes the relocation elements
1542 * @param object $xpath XPath object
1543 * @param object $relocation relocation elements
1544 * @param array $importer Record of the importer user mixed with contact of the content
1546 private function process_relocation($xpath, $relocation, $importer) {
1548 logger("Processing relocations");
1550 $relocate = array();
1551 $relocate["uid"] = $importer["importer_uid"];
1552 $relocate["cid"] = $importer["id"];
1553 $relocate["url"] = $xpath->query("dfrn:url/text()", $relocation)->item(0)->nodeValue;
1554 $relocate["addr"] = $xpath->query("dfrn:addr/text()", $relocation)->item(0)->nodeValue;
1555 $relocate["name"] = $xpath->query("dfrn:name/text()", $relocation)->item(0)->nodeValue;
1556 $relocate["avatar"] = $xpath->query("dfrn:avatar/text()", $relocation)->item(0)->nodeValue;
1557 $relocate["photo"] = $xpath->query("dfrn:photo/text()", $relocation)->item(0)->nodeValue;
1558 $relocate["thumb"] = $xpath->query("dfrn:thumb/text()", $relocation)->item(0)->nodeValue;
1559 $relocate["micro"] = $xpath->query("dfrn:micro/text()", $relocation)->item(0)->nodeValue;
1560 $relocate["request"] = $xpath->query("dfrn:request/text()", $relocation)->item(0)->nodeValue;
1561 $relocate["confirm"] = $xpath->query("dfrn:confirm/text()", $relocation)->item(0)->nodeValue;
1562 $relocate["notify"] = $xpath->query("dfrn:notify/text()", $relocation)->item(0)->nodeValue;
1563 $relocate["poll"] = $xpath->query("dfrn:poll/text()", $relocation)->item(0)->nodeValue;
1564 $relocate["sitepubkey"] = $xpath->query("dfrn:sitepubkey/text()", $relocation)->item(0)->nodeValue;
1566 if (($relocate["avatar"] == "") AND ($relocate["photo"] != ""))
1567 $relocate["avatar"] = $relocate["photo"];
1569 if ($relocate["addr"] == "")
1570 $relocate["addr"] = preg_replace("=(https?://)(.*)/profile/(.*)=ism", "$3@$2", $relocate["url"]);
1573 $r = q("SELECT `photo`, `url` FROM `contact` WHERE `id` = %d AND `uid` = %d;",
1574 intval($importer["id"]),
1575 intval($importer["importer_uid"]));
1581 // Update the gcontact entry
1582 $relocate["server_url"] = preg_replace("=(https?://)(.*)/profile/(.*)=ism", "$1$2", $relocate["url"]);
1584 $x = q("UPDATE `gcontact` SET
1593 WHERE `nurl` = '%s';",
1594 dbesc($relocate["name"]),
1595 dbesc($relocate["avatar"]),
1596 dbesc($relocate["url"]),
1597 dbesc(normalise_link($relocate["url"])),
1598 dbesc($relocate["addr"]),
1599 dbesc($relocate["addr"]),
1600 dbesc($relocate["notify"]),
1601 dbesc($relocate["server_url"]),
1602 dbesc(normalise_link($old["url"])));
1604 // Update the contact table. We try to find every entry.
1605 $x = q("UPDATE `contact` SET
1615 `site-pubkey` = '%s'
1616 WHERE (`id` = %d AND `uid` = %d) OR (`nurl` = '%s');",
1617 dbesc($relocate["name"]),
1618 dbesc($relocate["avatar"]),
1619 dbesc($relocate["url"]),
1620 dbesc(normalise_link($relocate["url"])),
1621 dbesc($relocate["addr"]),
1622 dbesc($relocate["request"]),
1623 dbesc($relocate["confirm"]),
1624 dbesc($relocate["notify"]),
1625 dbesc($relocate["poll"]),
1626 dbesc($relocate["sitepubkey"]),
1627 intval($importer["id"]),
1628 intval($importer["importer_uid"]),
1629 dbesc(normalise_link($old["url"])));
1631 update_contact_avatar($relocate["avatar"], $importer["importer_uid"], $importer["id"], true);
1637 /// @todo This is an extreme performance killer
1639 'owner-link' => array($old["url"], $relocate["url"]),
1640 'author-link' => array($old["url"], $relocate["url"]),
1641 //'owner-avatar' => array($old["photo"], $relocate["photo"]),
1642 //'author-avatar' => array($old["photo"], $relocate["photo"]),
1644 foreach ($fields as $n=>$f) {
1645 $r = q("SELECT `id` FROM `item` WHERE `%s` = '%s' AND `uid` = %d LIMIT 1",
1647 intval($importer["importer_uid"]));
1650 $x = q("UPDATE `item` SET `%s` = '%s' WHERE `%s` = '%s' AND `uid` = %d",
1653 intval($importer["importer_uid"]));
1660 /// merge with current record, current contents have priority
1661 /// update record, set url-updated
1662 /// update profile photos
1663 /// schedule a scan?
1668 * @brief Updates an item
1670 * @param array $current the current item record
1671 * @param array $item the new item record
1672 * @param array $importer Record of the importer user mixed with contact of the content
1673 * @param int $entrytype Is it a toplevel entry, a comment or a relayed comment?
1675 private function update_content($current, $item, $importer, $entrytype) {
1678 if (edited_timestamp_is_newer($current, $item)) {
1680 // do not accept (ignore) an earlier edit than one we currently have.
1681 if(datetime_convert("UTC","UTC",$item["edited"]) < $current["edited"])
1684 $r = q("UPDATE `item` SET `title` = '%s', `body` = '%s', `tag` = '%s', `edited` = '%s', `changed` = '%s' WHERE `uri` = '%s' AND `uid` = %d",
1685 dbesc($item["title"]),
1686 dbesc($item["body"]),
1687 dbesc($item["tag"]),
1688 dbesc(datetime_convert("UTC","UTC",$item["edited"])),
1689 dbesc(datetime_convert()),
1690 dbesc($item["uri"]),
1691 intval($importer["importer_uid"])
1693 create_tags_from_itemuri($item["uri"], $importer["importer_uid"]);
1694 update_thread_uri($item["uri"], $importer["importer_uid"]);
1698 if ($entrytype == DFRN_REPLY_RC)
1699 proc_run(PRIORITY_HIGH, "include/notifier.php","comment-import", $current["id"]);
1702 // update last-child if it changes
1703 if($item["last-child"] AND ($item["last-child"] != $current["last-child"])) {
1704 $r = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d",
1705 dbesc(datetime_convert()),
1706 dbesc($item["parent-uri"]),
1707 intval($importer["importer_uid"])
1709 $r = q("UPDATE `item` SET `last-child` = %d , `changed` = '%s' WHERE `uri` = '%s' AND `uid` = %d",
1710 intval($item["last-child"]),
1711 dbesc(datetime_convert()),
1712 dbesc($item["uri"]),
1713 intval($importer["importer_uid"])
1720 * @brief Detects the entry type of the item
1722 * @param array $importer Record of the importer user mixed with contact of the content
1723 * @param array $item the new item record
1725 * @return int Is it a toplevel entry, a comment or a relayed comment?
1727 private function get_entry_type($importer, $item) {
1728 if ($item["parent-uri"] != $item["uri"]) {
1731 if($importer["page-flags"] == PAGE_COMMUNITY || $importer["page-flags"] == PAGE_PRVGROUP) {
1734 logger("possible community action");
1736 $sql_extra = " AND `contact`.`self` AND `item`.`wall` ";
1738 // was the top-level post for this action written by somebody on this site?
1739 // Specifically, the recipient?
1741 $is_a_remote_action = false;
1743 $r = q("SELECT `item`.`parent-uri` FROM `item`
1744 WHERE `item`.`uri` = '%s'
1746 dbesc($item["parent-uri"])
1748 if($r && count($r)) {
1749 $r = q("SELECT `item`.`forum_mode`, `item`.`wall` FROM `item`
1750 INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
1751 WHERE `item`.`uri` = '%s' AND (`item`.`parent-uri` = '%s' OR `item`.`thr-parent` = '%s')
1752 AND `item`.`uid` = %d
1755 dbesc($r[0]["parent-uri"]),
1756 dbesc($r[0]["parent-uri"]),
1757 dbesc($r[0]["parent-uri"]),
1758 intval($importer["importer_uid"])
1761 $is_a_remote_action = true;
1764 // Does this have the characteristics of a community or private group action?
1765 // If it's an action to a wall post on a community/prvgroup page it's a
1766 // valid community action. Also forum_mode makes it valid for sure.
1767 // If neither, it's not.
1769 if($is_a_remote_action && $community) {
1770 if((!$r[0]["forum_mode"]) && (!$r[0]["wall"])) {
1771 $is_a_remote_action = false;
1772 logger("not a community action");
1776 if ($is_a_remote_action)
1777 return DFRN_REPLY_RC;
1782 return DFRN_TOP_LEVEL;
1787 * @brief Send a "poke"
1789 * @param array $item the new item record
1790 * @param array $importer Record of the importer user mixed with contact of the content
1791 * @param int $posted_id The record number of item record that was just posted
1793 private function do_poke($item, $importer, $posted_id) {
1794 $verb = urldecode(substr($item["verb"],strpos($item["verb"], "#")+1));
1797 $xo = parse_xml_string($item["object"],false);
1799 if(($xo->type == ACTIVITY_OBJ_PERSON) && ($xo->id)) {
1801 // somebody was poked/prodded. Was it me?
1802 foreach($xo->link as $l) {
1803 $atts = $l->attributes();
1804 switch($atts["rel"]) {
1806 $Blink = $atts["href"];
1813 if($Blink && link_compare($Blink,App::get_baseurl()."/profile/".$importer["nickname"])) {
1815 // send a notification
1817 "type" => NOTIFY_POKE,
1818 "notify_flags" => $importer["notify-flags"],
1819 "language" => $importer["language"],
1820 "to_name" => $importer["username"],
1821 "to_email" => $importer["email"],
1822 "uid" => $importer["importer_uid"],
1824 "link" => App::get_baseurl()."/display/".urlencode(get_item_guid($posted_id)),
1825 "source_name" => stripslashes($item["author-name"]),
1826 "source_link" => $item["author-link"],
1827 "source_photo" => ((link_compare($item["author-link"],$importer["url"]))
1828 ? $importer["thumb"] : $item["author-avatar"]),
1829 "verb" => $item["verb"],
1830 "otype" => "person",
1831 "activity" => $verb,
1832 "parent" => $item["parent"]
1839 * @brief Processes several actions, depending on the verb
1841 * @param int $entrytype Is it a toplevel entry, a comment or a relayed comment?
1842 * @param array $importer Record of the importer user mixed with contact of the content
1843 * @param array $item the new item record
1844 * @param bool $is_like Is the verb a "like"?
1846 * @return bool Should the processing of the entries be continued?
1848 private function process_verbs($entrytype, $importer, &$item, &$is_like) {
1850 logger("Process verb ".$item["verb"]." and object-type ".$item["object-type"]." for entrytype ".$entrytype, LOGGER_DEBUG);
1852 if (($entrytype == DFRN_TOP_LEVEL)) {
1853 // The filling of the the "contact" variable is done for legcy reasons
1854 // The functions below are partly used by ostatus.php as well - where we have this variable
1855 $r = q("SELECT * FROM `contact` WHERE `id` = %d", intval($importer["id"]));
1857 $nickname = $contact["nick"];
1859 // Big question: Do we need these functions? They were part of the "consume_feed" function.
1860 // This function once was responsible for DFRN and OStatus.
1861 if(activity_match($item["verb"],ACTIVITY_FOLLOW)) {
1862 logger("New follower");
1863 new_follower($importer, $contact, $item, $nickname);
1866 if(activity_match($item["verb"],ACTIVITY_UNFOLLOW)) {
1867 logger("Lost follower");
1868 lose_follower($importer, $contact, $item);
1871 if(activity_match($item["verb"],ACTIVITY_REQ_FRIEND)) {
1872 logger("New friend request");
1873 new_follower($importer, $contact, $item, $nickname, true);
1876 if(activity_match($item["verb"],ACTIVITY_UNFRIEND)) {
1877 logger("Lost sharer");
1878 lose_sharer($importer, $contact, $item);
1882 if(($item["verb"] == ACTIVITY_LIKE)
1883 || ($item["verb"] == ACTIVITY_DISLIKE)
1884 || ($item["verb"] == ACTIVITY_ATTEND)
1885 || ($item["verb"] == ACTIVITY_ATTENDNO)
1886 || ($item["verb"] == ACTIVITY_ATTENDMAYBE)) {
1888 $item["type"] = "activity";
1889 $item["gravity"] = GRAVITY_LIKE;
1890 // only one like or dislike per person
1891 // splitted into two queries for performance issues
1892 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `author-link` = '%s' AND `verb` = '%s' AND `parent-uri` = '%s' AND NOT `deleted` LIMIT 1",
1893 intval($item["uid"]),
1894 dbesc($item["author-link"]),
1895 dbesc($item["verb"]),
1896 dbesc($item["parent-uri"])
1901 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `author-link` = '%s' AND `verb` = '%s' AND `thr-parent` = '%s' AND NOT `deleted` LIMIT 1",
1902 intval($item["uid"]),
1903 dbesc($item["author-link"]),
1904 dbesc($item["verb"]),
1905 dbesc($item["parent-uri"])
1912 if(($item["verb"] == ACTIVITY_TAG) && ($item["object-type"] == ACTIVITY_OBJ_TAGTERM)) {
1914 $xo = parse_xml_string($item["object"],false);
1915 $xt = parse_xml_string($item["target"],false);
1917 if($xt->type == ACTIVITY_OBJ_NOTE) {
1918 $r = q("SELECT `id`, `tag` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1920 intval($importer["importer_uid"])
1926 // extract tag, if not duplicate, add to parent item
1928 if(!(stristr($r[0]["tag"],trim($xo->content)))) {
1929 q("UPDATE `item` SET `tag` = '%s' WHERE `id` = %d",
1930 dbesc($r[0]["tag"] . (strlen($r[0]["tag"]) ? ',' : '') . '#[url=' . $xo->id . ']'. $xo->content . '[/url]'),
1933 create_tags_from_item($r[0]["id"]);
1943 * @brief Processes the link elements
1945 * @param object $links link elements
1946 * @param array $item the item record
1948 private function parse_links($links, &$item) {
1954 foreach ($links AS $link) {
1955 foreach($link->attributes AS $attributes) {
1956 if ($attributes->name == "href")
1957 $href = $attributes->textContent;
1958 if ($attributes->name == "rel")
1959 $rel = $attributes->textContent;
1960 if ($attributes->name == "type")
1961 $type = $attributes->textContent;
1962 if ($attributes->name == "length")
1963 $length = $attributes->textContent;
1964 if ($attributes->name == "title")
1965 $title = $attributes->textContent;
1967 if (($rel != "") AND ($href != ""))
1970 $item["plink"] = $href;
1974 if(strlen($item["attach"]))
1975 $item["attach"] .= ",";
1977 $item["attach"] .= '[attach]href="'.$href.'" length="'.$length.'" type="'.$type.'" title="'.$title.'"[/attach]';
1984 * @brief Processes the entry elements which contain the items and comments
1986 * @param array $header Array of the header elements that always stay the same
1987 * @param object $xpath XPath object
1988 * @param object $entry entry elements
1989 * @param array $importer Record of the importer user mixed with contact of the content
1991 private function process_entry($header, $xpath, $entry, $importer) {
1993 logger("Processing entries");
1998 $item["uri"] = $xpath->query("atom:id/text()", $entry)->item(0)->nodeValue;
2001 $owner = self::fetchauthor($xpath, $entry, $importer, "dfrn:owner", true);
2003 $item["owner-name"] = $owner["name"];
2004 $item["owner-link"] = $owner["link"];
2005 $item["owner-avatar"] = $owner["avatar"];
2008 $author = self::fetchauthor($xpath, $entry, $importer, "atom:author", true);
2010 $item["author-name"] = $author["name"];
2011 $item["author-link"] = $author["link"];
2012 $item["author-avatar"] = $author["avatar"];
2014 $item["title"] = $xpath->query("atom:title/text()", $entry)->item(0)->nodeValue;
2016 $item["created"] = $xpath->query("atom:published/text()", $entry)->item(0)->nodeValue;
2017 $item["edited"] = $xpath->query("atom:updated/text()", $entry)->item(0)->nodeValue;
2019 $item["body"] = $xpath->query("dfrn:env/text()", $entry)->item(0)->nodeValue;
2020 $item["body"] = str_replace(array(' ',"\t","\r","\n"), array('','','',''),$item["body"]);
2021 // make sure nobody is trying to sneak some html tags by us
2022 $item["body"] = notags(base64url_decode($item["body"]));
2024 $item["body"] = limit_body_size($item["body"]);
2026 /// @todo Do we really need this check for HTML elements? (It was copied from the old function)
2027 if((strpos($item['body'],'<') !== false) && (strpos($item['body'],'>') !== false)) {
2029 $item['body'] = reltoabs($item['body'],$base_url);
2031 $item['body'] = html2bb_video($item['body']);
2033 $item['body'] = oembed_html2bbcode($item['body']);
2035 $config = HTMLPurifier_Config::createDefault();
2036 $config->set('Cache.DefinitionImpl', null);
2038 // we shouldn't need a whitelist, because the bbcode converter
2039 // will strip out any unsupported tags.
2041 $purifier = new HTMLPurifier($config);
2042 $item['body'] = $purifier->purify($item['body']);
2044 $item['body'] = @html2bbcode($item['body']);
2047 /// @todo We should check for a repeated post and if we know the repeated author.
2049 // We don't need the content element since "dfrn:env" is always present
2050 //$item["body"] = $xpath->query("atom:content/text()", $entry)->item(0)->nodeValue;
2052 $item["last-child"] = $xpath->query("dfrn:comment-allow/text()", $entry)->item(0)->nodeValue;
2053 $item["location"] = $xpath->query("dfrn:location/text()", $entry)->item(0)->nodeValue;
2055 $georsspoint = $xpath->query("georss:point", $entry);
2057 $item["coord"] = $georsspoint->item(0)->nodeValue;
2059 $item["private"] = $xpath->query("dfrn:private/text()", $entry)->item(0)->nodeValue;
2061 $item["extid"] = $xpath->query("dfrn:extid/text()", $entry)->item(0)->nodeValue;
2063 if ($xpath->query("dfrn:bookmark/text()", $entry)->item(0)->nodeValue == "true")
2064 $item["bookmark"] = true;
2066 $notice_info = $xpath->query("statusnet:notice_info", $entry);
2067 if ($notice_info AND ($notice_info->length > 0)) {
2068 foreach($notice_info->item(0)->attributes AS $attributes) {
2069 if ($attributes->name == "source")
2070 $item["app"] = strip_tags($attributes->textContent);
2074 $item["guid"] = $xpath->query("dfrn:diaspora_guid/text()", $entry)->item(0)->nodeValue;
2076 // We store the data from "dfrn:diaspora_signature" in a different table, this is done in "item_store"
2077 $dsprsig = unxmlify($xpath->query("dfrn:diaspora_signature/text()", $entry)->item(0)->nodeValue);
2079 $item["dsprsig"] = $dsprsig;
2081 $item["verb"] = $xpath->query("activity:verb/text()", $entry)->item(0)->nodeValue;
2083 if ($xpath->query("activity:object-type/text()", $entry)->item(0)->nodeValue != "")
2084 $item["object-type"] = $xpath->query("activity:object-type/text()", $entry)->item(0)->nodeValue;
2086 $object = $xpath->query("activity:object", $entry)->item(0);
2087 $item["object"] = self::transform_activity($xpath, $object, "object");
2089 if (trim($item["object"]) != "") {
2090 $r = parse_xml_string($item["object"], false);
2091 if (isset($r->type))
2092 $item["object-type"] = $r->type;
2095 $target = $xpath->query("activity:target", $entry)->item(0);
2096 $item["target"] = self::transform_activity($xpath, $target, "target");
2098 $categories = $xpath->query("atom:category", $entry);
2100 foreach ($categories AS $category) {
2103 foreach($category->attributes AS $attributes) {
2104 if ($attributes->name == "term")
2105 $term = $attributes->textContent;
2107 if ($attributes->name == "scheme")
2108 $scheme = $attributes->textContent;
2111 if (($term != "") AND ($scheme != "")) {
2112 $parts = explode(":", $scheme);
2113 if ((count($parts) >= 4) AND (array_shift($parts) == "X-DFRN")) {
2114 $termhash = array_shift($parts);
2115 $termurl = implode(":", $parts);
2117 if(strlen($item["tag"]))
2118 $item["tag"] .= ",";
2120 $item["tag"] .= $termhash."[url=".$termurl."]".$term."[/url]";
2128 $links = $xpath->query("atom:link", $entry);
2130 self::parse_links($links, $item);
2132 // Is it a reply or a top level posting?
2133 $item["parent-uri"] = $item["uri"];
2135 $inreplyto = $xpath->query("thr:in-reply-to", $entry);
2136 if (is_object($inreplyto->item(0)))
2137 foreach($inreplyto->item(0)->attributes AS $attributes)
2138 if ($attributes->name == "ref")
2139 $item["parent-uri"] = $attributes->textContent;
2141 // Get the type of the item (Top level post, reply or remote reply)
2142 $entrytype = self::get_entry_type($importer, $item);
2144 // Now assign the rest of the values that depend on the type of the message
2145 if (in_array($entrytype, array(DFRN_REPLY, DFRN_REPLY_RC))) {
2146 if (!isset($item["object-type"]))
2147 $item["object-type"] = ACTIVITY_OBJ_COMMENT;
2149 if ($item["contact-id"] != $owner["contact-id"])
2150 $item["contact-id"] = $owner["contact-id"];
2152 if (($item["network"] != $owner["network"]) AND ($owner["network"] != ""))
2153 $item["network"] = $owner["network"];
2155 if ($item["contact-id"] != $author["contact-id"])
2156 $item["contact-id"] = $author["contact-id"];
2158 if (($item["network"] != $author["network"]) AND ($author["network"] != ""))
2159 $item["network"] = $author["network"];
2161 // This code was taken from the old DFRN code
2162 // When activated, forums don't work.
2163 // And: Why should we disallow commenting by followers?
2164 // the behaviour is now similar to the Diaspora part.
2165 //if($importer["rel"] == CONTACT_IS_FOLLOWER) {
2166 // logger("Contact ".$importer["id"]." is only follower. Quitting", LOGGER_DEBUG);
2171 if ($entrytype == DFRN_REPLY_RC) {
2172 $item["type"] = "remote-comment";
2174 } elseif ($entrytype == DFRN_TOP_LEVEL) {
2175 if (!isset($item["object-type"]))
2176 $item["object-type"] = ACTIVITY_OBJ_NOTE;
2179 if ($item["object-type"] == ACTIVITY_OBJ_EVENT) {
2180 logger("Item ".$item["uri"]." seems to contain an event.", LOGGER_DEBUG);
2181 $ev = bbtoevent($item["body"]);
2182 if((x($ev, "desc") || x($ev, "summary")) && x($ev, "start")) {
2183 logger("Event in item ".$item["uri"]." was found.", LOGGER_DEBUG);
2184 $ev["cid"] = $importer["id"];
2185 $ev["uid"] = $importer["uid"];
2186 $ev["uri"] = $item["uri"];
2187 $ev["edited"] = $item["edited"];
2188 $ev['private'] = $item['private'];
2189 $ev["guid"] = $item["guid"];
2191 $r = q("SELECT `id` FROM `event` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2192 dbesc($item["uri"]),
2193 intval($importer["uid"])
2196 $ev["id"] = $r[0]["id"];
2198 $event_id = event_store($ev);
2199 logger("Event ".$event_id." was stored", LOGGER_DEBUG);
2205 $r = q("SELECT `id`, `uid`, `last-child`, `edited`, `body` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2206 dbesc($item["uri"]),
2207 intval($importer["importer_uid"])
2210 if (!self::process_verbs($entrytype, $importer, $item, $is_like)) {
2211 logger("Exiting because 'process_verbs' told us so", LOGGER_DEBUG);
2215 // Update content if 'updated' changes
2217 if (self::update_content($r[0], $item, $importer, $entrytype))
2218 logger("Item ".$item["uri"]." was updated.", LOGGER_DEBUG);
2220 logger("Item ".$item["uri"]." already existed.", LOGGER_DEBUG);
2224 if (in_array($entrytype, array(DFRN_REPLY, DFRN_REPLY_RC))) {
2225 $posted_id = item_store($item);
2230 logger("Reply from contact ".$item["contact-id"]." was stored with id ".$posted_id, LOGGER_DEBUG);
2232 $item["id"] = $posted_id;
2234 $r = q("SELECT `parent`, `parent-uri` FROM `item` WHERE `id` = %d AND `uid` = %d LIMIT 1",
2236 intval($importer["importer_uid"])
2239 $parent = $r[0]["parent"];
2240 $parent_uri = $r[0]["parent-uri"];
2244 $r1 = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `uid` = %d AND `parent` = %d",
2245 dbesc(datetime_convert()),
2246 intval($importer["importer_uid"]),
2247 intval($r[0]["parent"])
2250 $r2 = q("UPDATE `item` SET `last-child` = 1, `changed` = '%s' WHERE `uid` = %d AND `id` = %d",
2251 dbesc(datetime_convert()),
2252 intval($importer["importer_uid"]),
2257 if($posted_id AND $parent AND ($entrytype == DFRN_REPLY_RC)) {
2258 logger("Notifying followers about comment ".$posted_id, LOGGER_DEBUG);
2259 proc_run(PRIORITY_HIGH, "include/notifier.php", "comment-import", $posted_id);
2264 } else { // $entrytype == DFRN_TOP_LEVEL
2265 if(!link_compare($item["owner-link"],$importer["url"])) {
2266 // The item owner info is not our contact. It's OK and is to be expected if this is a tgroup delivery,
2267 // but otherwise there's a possible data mixup on the sender's system.
2268 // the tgroup delivery code called from item_store will correct it if it's a forum,
2269 // but we're going to unconditionally correct it here so that the post will always be owned by our contact.
2270 logger('Correcting item owner.', LOGGER_DEBUG);
2271 $item["owner-name"] = $importer["senderName"];
2272 $item["owner-link"] = $importer["url"];
2273 $item["owner-avatar"] = $importer["thumb"];
2276 if(($importer["rel"] == CONTACT_IS_FOLLOWER) && (!tgroup_check($importer["importer_uid"], $item))) {
2277 logger("Contact ".$importer["id"]." is only follower and tgroup check was negative.", LOGGER_DEBUG);
2281 // This is my contact on another system, but it's really me.
2282 // Turn this into a wall post.
2283 $notify = item_is_remote_self($importer, $item);
2285 $posted_id = item_store($item, false, $notify);
2287 logger("Item was stored with id ".$posted_id, LOGGER_DEBUG);
2289 if(stristr($item["verb"],ACTIVITY_POKE))
2290 self::do_poke($item, $importer, $posted_id);
2295 * @brief Deletes items
2297 * @param object $xpath XPath object
2298 * @param object $deletion deletion elements
2299 * @param array $importer Record of the importer user mixed with contact of the content
2301 private function process_deletion($xpath, $deletion, $importer) {
2303 logger("Processing deletions");
2305 foreach($deletion->attributes AS $attributes) {
2306 if ($attributes->name == "ref")
2307 $uri = $attributes->textContent;
2308 if ($attributes->name == "when")
2309 $when = $attributes->textContent;
2312 $when = datetime_convert("UTC", "UTC", $when, "Y-m-d H:i:s");
2314 $when = datetime_convert("UTC", "UTC", "now", "Y-m-d H:i:s");
2316 if (!$uri OR !$importer["id"])
2319 /// @todo Only select the used fields
2320 $r = q("SELECT `item`.*, `contact`.`self` FROM `item` INNER JOIN `contact` on `item`.`contact-id` = `contact`.`id`
2321 WHERE `uri` = '%s' AND `item`.`uid` = %d AND `contact-id` = %d AND NOT `item`.`file` LIKE '%%[%%' LIMIT 1",
2323 intval($importer["uid"]),
2324 intval($importer["id"])
2327 logger("Item with uri ".$uri." from contact ".$importer["id"]." for user ".$importer["uid"]." wasn't found.", LOGGER_DEBUG);
2333 $entrytype = self::get_entry_type($importer, $item);
2335 if(!$item["deleted"])
2336 logger('deleting item '.$item["id"].' uri='.$uri, LOGGER_DEBUG);
2340 if($item["object-type"] == ACTIVITY_OBJ_EVENT) {
2341 logger("Deleting event ".$item["event-id"], LOGGER_DEBUG);
2342 event_delete($item["event-id"]);
2345 if(($item["verb"] == ACTIVITY_TAG) && ($item["object-type"] == ACTIVITY_OBJ_TAGTERM)) {
2347 $xo = parse_xml_string($item["object"],false);
2348 $xt = parse_xml_string($item["target"],false);
2350 if($xt->type == ACTIVITY_OBJ_NOTE) {
2351 $i = q("SELECT `id`, `contact-id`, `tag` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2353 intval($importer["importer_uid"])
2357 // For tags, the owner cannot remove the tag on the author's copy of the post.
2359 $owner_remove = (($item["contact-id"] == $i[0]["contact-id"]) ? true: false);
2360 $author_remove = (($item["origin"] && $item["self"]) ? true : false);
2361 $author_copy = (($item["origin"]) ? true : false);
2363 if($owner_remove && $author_copy)
2365 if($author_remove || $owner_remove) {
2366 $tags = explode(',',$i[0]["tag"]);
2369 foreach($tags as $tag)
2370 if(trim($tag) !== trim($xo->body))
2371 $newtags[] = trim($tag);
2373 q("UPDATE `item` SET `tag` = '%s' WHERE `id` = %d",
2374 dbesc(implode(',',$newtags)),
2377 create_tags_from_item($i[0]["id"]);
2383 if($entrytype == DFRN_TOP_LEVEL) {
2384 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s',
2385 `body` = '', `title` = ''
2386 WHERE `parent-uri` = '%s' AND `uid` = %d",
2388 dbesc(datetime_convert()),
2390 intval($importer["uid"])
2392 create_tags_from_itemuri($uri, $importer["uid"]);
2393 create_files_from_itemuri($uri, $importer["uid"]);
2394 update_thread_uri($uri, $importer["uid"]);
2396 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s',
2397 `body` = '', `title` = ''
2398 WHERE `uri` = '%s' AND `uid` = %d",
2400 dbesc(datetime_convert()),
2402 intval($importer["uid"])
2404 create_tags_from_itemuri($uri, $importer["uid"]);
2405 create_files_from_itemuri($uri, $importer["uid"]);
2406 update_thread_uri($uri, $importer["importer_uid"]);
2407 if($item["last-child"]) {
2408 // ensure that last-child is set in case the comment that had it just got wiped.
2409 q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d ",
2410 dbesc(datetime_convert()),
2411 dbesc($item["parent-uri"]),
2412 intval($item["uid"])
2414 // who is the last child now?
2415 $r = q("SELECT `id` FROM `item` WHERE `parent-uri` = '%s' AND `type` != 'activity' AND `deleted` = 0 AND `moderated` = 0 AND `uid` = %d
2416 ORDER BY `created` DESC LIMIT 1",
2417 dbesc($item["parent-uri"]),
2418 intval($importer["uid"])
2421 q("UPDATE `item` SET `last-child` = 1 WHERE `id` = %d",
2426 // if this is a relayed delete, propagate it to other recipients
2428 if($entrytype == DFRN_REPLY_RC) {
2429 logger("Notifying followers about deletion of post ".$item["id"], LOGGER_DEBUG);
2430 proc_run(PRIORITY_HIGH, "include/notifier.php","drop", $item["id"]);
2437 * @brief Imports a DFRN message
2439 * @param text $xml The DFRN message
2440 * @param array $importer Record of the importer user mixed with contact of the content
2441 * @param bool $sort_by_date Is used when feeds are polled
2443 public static function import($xml,$importer, $sort_by_date = false) {
2448 if($importer["readonly"]) {
2449 // We aren't receiving stuff from this person. But we will quietly ignore them
2450 // rather than a blatant "go away" message.
2451 logger('ignoring contact '.$importer["id"]);
2455 $doc = new DOMDocument();
2456 @$doc->loadXML($xml);
2458 $xpath = new DomXPath($doc);
2459 $xpath->registerNamespace("atom", NAMESPACE_ATOM1);
2460 $xpath->registerNamespace("thr", NAMESPACE_THREAD);
2461 $xpath->registerNamespace("at", NAMESPACE_TOMB);
2462 $xpath->registerNamespace("media", NAMESPACE_MEDIA);
2463 $xpath->registerNamespace("dfrn", NAMESPACE_DFRN);
2464 $xpath->registerNamespace("activity", NAMESPACE_ACTIVITY);
2465 $xpath->registerNamespace("georss", NAMESPACE_GEORSS);
2466 $xpath->registerNamespace("poco", NAMESPACE_POCO);
2467 $xpath->registerNamespace("ostatus", NAMESPACE_OSTATUS);
2468 $xpath->registerNamespace("statusnet", NAMESPACE_STATUSNET);
2471 $header["uid"] = $importer["uid"];
2472 $header["network"] = NETWORK_DFRN;
2473 $header["type"] = "remote";
2474 $header["wall"] = 0;
2475 $header["origin"] = 0;
2476 $header["contact-id"] = $importer["id"];
2478 // Update the contact table if the data has changed
2480 // The "atom:author" is only present in feeds
2481 if ($xpath->query("/atom:feed/atom:author")->length > 0)
2482 self::fetchauthor($xpath, $doc->firstChild, $importer, "atom:author", false, $xml);
2484 // Only the "dfrn:owner" in the head section contains all data
2485 if ($xpath->query("/atom:feed/dfrn:owner")->length > 0)
2486 self::fetchauthor($xpath, $doc->firstChild, $importer, "dfrn:owner", false, $xml);
2488 logger("Import DFRN message for user ".$importer["uid"]." from contact ".$importer["id"], LOGGER_DEBUG);
2490 // The account type is new since 3.5.1
2491 if ($xpath->query("/atom:feed/dfrn:account_type")->length > 0) {
2492 $accounttype = intval($xpath->evaluate("/atom:feed/dfrn:account_type/text()", $context)->item(0)->nodeValue);
2494 if ($accounttype != $importer["contact-type"])
2495 q("UPDATE `contact` SET `contact-type` = %d WHERE `id` = %d",
2496 intval($accounttype),
2497 intval($importer["id"])
2501 // is it a public forum? Private forums aren't supported with this method
2502 // This is deprecated since 3.5.1
2503 $forum = intval($xpath->evaluate("/atom:feed/dfrn:community/text()", $context)->item(0)->nodeValue);
2505 if ($forum != $importer["forum"])
2506 q("UPDATE `contact` SET `forum` = %d WHERE `forum` != %d AND `id` = %d",
2507 intval($forum), intval($forum),
2508 intval($importer["id"])
2511 $mails = $xpath->query("/atom:feed/dfrn:mail");
2512 foreach ($mails AS $mail)
2513 self::process_mail($xpath, $mail, $importer);
2515 $suggestions = $xpath->query("/atom:feed/dfrn:suggest");
2516 foreach ($suggestions AS $suggestion)
2517 self::process_suggestion($xpath, $suggestion, $importer);
2519 $relocations = $xpath->query("/atom:feed/dfrn:relocate");
2520 foreach ($relocations AS $relocation)
2521 self::process_relocation($xpath, $relocation, $importer);
2523 $deletions = $xpath->query("/atom:feed/at:deleted-entry");
2524 foreach ($deletions AS $deletion)
2525 self::process_deletion($xpath, $deletion, $importer);
2527 if (!$sort_by_date) {
2528 $entries = $xpath->query("/atom:feed/atom:entry");
2529 foreach ($entries AS $entry)
2530 self::process_entry($header, $xpath, $entry, $importer);
2532 $newentries = array();
2533 $entries = $xpath->query("/atom:feed/atom:entry");
2534 foreach ($entries AS $entry) {
2535 $created = $xpath->query("atom:published/text()", $entry)->item(0)->nodeValue;
2536 $newentries[strtotime($created)] = $entry;
2539 // Now sort after the publishing date
2542 foreach ($newentries AS $entry)
2543 self::process_entry($header, $xpath, $entry, $importer);
2545 logger("Import done for user ".$importer["uid"]." from contact ".$importer["id"], LOGGER_DEBUG);