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",
108 if (! dbm::is_result($r)) {
113 $owner_id = $owner['uid'];
114 $owner_nick = $owner['nickname'];
116 $sql_post_table = "";
123 $sql_extra = sprintf(" AND `issued-id` = '%s' ", dbesc($dfrn_id));
127 $sql_extra = sprintf(" AND `issued-id` = '%s' AND `duplex` = 1 ", dbesc($dfrn_id));
128 $my_id = '1:' . $dfrn_id;
131 $sql_extra = sprintf(" AND `dfrn-id` = '%s' AND `duplex` = 1 ", dbesc($dfrn_id));
132 $my_id = '0:' . $dfrn_id;
139 $r = q("SELECT * FROM `contact` WHERE NOT `blocked` AND `contact`.`uid` = %d $sql_extra LIMIT 1",
143 if (! dbm::is_result($r)) {
148 require_once('include/security.php');
149 $groups = init_groups_visitor($contact['id']);
152 for($x = 0; $x < count($groups); $x ++)
153 $groups[$x] = '<' . intval($groups[$x]) . '>' ;
154 $gs = implode('|', $groups);
156 $gs = '<<>>' ; // Impossible to match
158 $sql_extra = sprintf("
159 AND ( `allow_cid` = '' OR `allow_cid` REGEXP '<%d>' )
160 AND ( `deny_cid` = '' OR NOT `deny_cid` REGEXP '<%d>' )
161 AND ( `allow_gid` = '' OR `allow_gid` REGEXP '%s' )
162 AND ( `deny_gid` = '' OR NOT `deny_gid` REGEXP '%s')
164 intval($contact['id']),
165 intval($contact['id']),
176 if(! strlen($last_update))
177 $last_update = 'now -30 days';
179 if(isset($category)) {
180 $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` ",
181 dbesc(protect_sprintf($category)), intval(TERM_OBJ_POST), intval(TERM_CATEGORY), intval($owner_id));
182 //$sql_extra .= file_tag_file_query('item',$category,'category');
187 $sql_extra .= " AND `contact`.`self` = 1 ";
190 $check_date = datetime_convert('UTC','UTC',$last_update,'Y-m-d H:i:s');
192 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`,
193 `contact`.`name`, `contact`.`network`, `contact`.`photo`, `contact`.`url`,
194 `contact`.`name-date`, `contact`.`uri-date`, `contact`.`avatar-date`,
195 `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
196 `sign`.`signed_text`, `sign`.`signature`, `sign`.`signer`
197 FROM `item` USE INDEX (`uid_wall_changed`) $sql_post_table
198 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
199 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
200 LEFT JOIN `sign` ON `sign`.`iid` = `item`.`id`
201 WHERE `item`.`uid` = %d AND `item`.`visible` AND NOT `item`.`moderated` AND `item`.`parent` != 0
202 AND `item`.`wall` AND `item`.`changed` > '%s'
204 ORDER BY `item`.`parent` ".$sort.", `item`.`created` ASC LIMIT 0, 300",
210 // Will check further below if this actually returned results.
211 // We will provide an empty feed if that is the case.
215 $doc = new DOMDocument('1.0', 'utf-8');
216 $doc->formatOutput = true;
218 $alternatelink = $owner['url'];
221 $alternatelink .= "/category/".$category;
224 $author = "dfrn:owner";
228 $root = self::add_header($doc, $owner, $author, $alternatelink, true);
230 // This hook can't work anymore
231 // call_hooks('atom_feed', $atom);
233 if (!count($items) OR $onlyheader) {
234 $atom = trim($doc->saveXML());
236 call_hooks('atom_feed_end', $atom);
241 foreach($items as $item) {
243 // prevent private email from leaking.
244 if($item['network'] == NETWORK_MAIL)
247 // public feeds get html, our own nodes use bbcode
251 // catch any email that's in a public conversation and make sure it doesn't leak
257 $entry = self::entry($doc, $type, $item, $owner, true);
258 $root->appendChild($entry);
262 $atom = trim($doc->saveXML());
264 call_hooks('atom_feed_end', $atom);
270 * @brief Create XML text for DFRN mails
272 * @param array $item message elements
273 * @param array $owner Owner record
275 * @return string DFRN mail
277 public static function mail($item, $owner) {
278 $doc = new DOMDocument('1.0', 'utf-8');
279 $doc->formatOutput = true;
281 $root = self::add_header($doc, $owner, "dfrn:owner", "", false);
283 $mail = $doc->createElement("dfrn:mail");
284 $sender = $doc->createElement("dfrn:sender");
286 xml::add_element($doc, $sender, "dfrn:name", $owner['name']);
287 xml::add_element($doc, $sender, "dfrn:uri", $owner['url']);
288 xml::add_element($doc, $sender, "dfrn:avatar", $owner['thumb']);
290 $mail->appendChild($sender);
292 xml::add_element($doc, $mail, "dfrn:id", $item['uri']);
293 xml::add_element($doc, $mail, "dfrn:in-reply-to", $item['parent-uri']);
294 xml::add_element($doc, $mail, "dfrn:sentdate", datetime_convert('UTC', 'UTC', $item['created'] . '+00:00' , ATOM_TIME));
295 xml::add_element($doc, $mail, "dfrn:subject", $item['title']);
296 xml::add_element($doc, $mail, "dfrn:content", $item['body']);
298 $root->appendChild($mail);
300 return(trim($doc->saveXML()));
304 * @brief Create XML text for DFRN friend suggestions
306 * @param array $item suggestion elements
307 * @param array $owner Owner record
309 * @return string DFRN suggestions
311 public static function fsuggest($item, $owner) {
312 $doc = new DOMDocument('1.0', 'utf-8');
313 $doc->formatOutput = true;
315 $root = self::add_header($doc, $owner, "dfrn:owner", "", false);
317 $suggest = $doc->createElement("dfrn:suggest");
319 xml::add_element($doc, $suggest, "dfrn:url", $item['url']);
320 xml::add_element($doc, $suggest, "dfrn:name", $item['name']);
321 xml::add_element($doc, $suggest, "dfrn:photo", $item['photo']);
322 xml::add_element($doc, $suggest, "dfrn:request", $item['request']);
323 xml::add_element($doc, $suggest, "dfrn:note", $item['note']);
325 $root->appendChild($suggest);
327 return(trim($doc->saveXML()));
331 * @brief Create XML text for DFRN relocations
333 * @param array $owner Owner record
334 * @param int $uid User ID
336 * @return string DFRN relocations
338 public static function relocate($owner, $uid) {
340 /* get site pubkey. this could be a new installation with no site keys*/
341 $pubkey = get_config('system','site_pubkey');
343 $res = new_keypair(1024);
344 set_config('system','site_prvkey', $res['prvkey']);
345 set_config('system','site_pubkey', $res['pubkey']);
348 $rp = q("SELECT `resource-id` , `scale`, type FROM `photo`
349 WHERE `profile` = 1 AND `uid` = %d ORDER BY scale;", $uid);
351 $ext = Photo::supportedTypes();
354 $photos[$p['scale']] = app::get_baseurl().'/photo/'.$p['resource-id'].'-'.$p['scale'].'.'.$ext[$p['type']];
358 $doc = new DOMDocument('1.0', 'utf-8');
359 $doc->formatOutput = true;
361 $root = self::add_header($doc, $owner, "dfrn:owner", "", false);
363 $relocate = $doc->createElement("dfrn:relocate");
365 xml::add_element($doc, $relocate, "dfrn:url", $owner['url']);
366 xml::add_element($doc, $relocate, "dfrn:name", $owner['name']);
367 xml::add_element($doc, $relocate, "dfrn:addr", $owner['addr']);
368 xml::add_element($doc, $relocate, "dfrn:avatar", $owner['avatar']);
369 xml::add_element($doc, $relocate, "dfrn:photo", $photos[4]);
370 xml::add_element($doc, $relocate, "dfrn:thumb", $photos[5]);
371 xml::add_element($doc, $relocate, "dfrn:micro", $photos[6]);
372 xml::add_element($doc, $relocate, "dfrn:request", $owner['request']);
373 xml::add_element($doc, $relocate, "dfrn:confirm", $owner['confirm']);
374 xml::add_element($doc, $relocate, "dfrn:notify", $owner['notify']);
375 xml::add_element($doc, $relocate, "dfrn:poll", $owner['poll']);
376 xml::add_element($doc, $relocate, "dfrn:sitepubkey", get_config('system','site_pubkey'));
378 $root->appendChild($relocate);
380 return(trim($doc->saveXML()));
384 * @brief Adds the header elements for the DFRN protocol
386 * @param object $doc XML document
387 * @param array $owner Owner record
388 * @param string $authorelement Element name for the author
389 * @param string $alternatelink link to profile or category
390 * @param bool $public Is it a header for public posts?
392 * @return object XML root object
394 private static function add_header($doc, $owner, $authorelement, $alternatelink = "", $public = false) {
396 if ($alternatelink == "")
397 $alternatelink = $owner['url'];
399 $root = $doc->createElementNS(NAMESPACE_ATOM1, 'feed');
400 $doc->appendChild($root);
402 $root->setAttribute("xmlns:thr", NAMESPACE_THREAD);
403 $root->setAttribute("xmlns:at", NAMESPACE_TOMB);
404 $root->setAttribute("xmlns:media", NAMESPACE_MEDIA);
405 $root->setAttribute("xmlns:dfrn", NAMESPACE_DFRN);
406 $root->setAttribute("xmlns:activity", NAMESPACE_ACTIVITY);
407 $root->setAttribute("xmlns:georss", NAMESPACE_GEORSS);
408 $root->setAttribute("xmlns:poco", NAMESPACE_POCO);
409 $root->setAttribute("xmlns:ostatus", NAMESPACE_OSTATUS);
410 $root->setAttribute("xmlns:statusnet", NAMESPACE_STATUSNET);
412 xml::add_element($doc, $root, "id", app::get_baseurl()."/profile/".$owner["nick"]);
413 xml::add_element($doc, $root, "title", $owner["name"]);
415 $attributes = array("uri" => "https://friendi.ca", "version" => FRIENDICA_VERSION."-".DB_UPDATE_VERSION);
416 xml::add_element($doc, $root, "generator", FRIENDICA_PLATFORM, $attributes);
418 $attributes = array("rel" => "license", "href" => "http://creativecommons.org/licenses/by/3.0/");
419 xml::add_element($doc, $root, "link", "", $attributes);
421 $attributes = array("rel" => "alternate", "type" => "text/html", "href" => $alternatelink);
422 xml::add_element($doc, $root, "link", "", $attributes);
426 // DFRN itself doesn't uses this. But maybe someone else wants to subscribe to the public feed.
427 ostatus::hublinks($doc, $root);
429 $attributes = array("rel" => "salmon", "href" => app::get_baseurl()."/salmon/".$owner["nick"]);
430 xml::add_element($doc, $root, "link", "", $attributes);
432 $attributes = array("rel" => "http://salmon-protocol.org/ns/salmon-replies", "href" => app::get_baseurl()."/salmon/".$owner["nick"]);
433 xml::add_element($doc, $root, "link", "", $attributes);
435 $attributes = array("rel" => "http://salmon-protocol.org/ns/salmon-mention", "href" => app::get_baseurl()."/salmon/".$owner["nick"]);
436 xml::add_element($doc, $root, "link", "", $attributes);
439 // For backward compatibility we keep this element
440 if ($owner['page-flags'] == PAGE_COMMUNITY)
441 xml::add_element($doc, $root, "dfrn:community", 1);
443 // The former element is replaced by this one
444 xml::add_element($doc, $root, "dfrn:account_type", $owner["account-type"]);
446 /// @todo We need a way to transmit the different page flags like "PAGE_PRVGROUP"
448 xml::add_element($doc, $root, "updated", datetime_convert("UTC", "UTC", "now", ATOM_TIME));
450 $author = self::add_author($doc, $owner, $authorelement, $public);
451 $root->appendChild($author);
457 * @brief Adds the author element in the header for the DFRN protocol
459 * @param object $doc XML document
460 * @param array $owner Owner record
461 * @param string $authorelement Element name for the author
463 * @return object XML author object
465 private static function add_author($doc, $owner, $authorelement, $public) {
467 // Is the profile hidden or shouldn't be published in the net? Then add the "hide" element
468 $r = q("SELECT `id` FROM `profile` INNER JOIN `user` ON `user`.`uid` = `profile`.`uid`
469 WHERE (`hidewall` OR NOT `net-publish`) AND `user`.`uid` = %d",
470 intval($owner['uid']));
476 $author = $doc->createElement($authorelement);
478 $namdate = datetime_convert('UTC', 'UTC', $owner['name-date'].'+00:00', ATOM_TIME);
479 $uridate = datetime_convert('UTC', 'UTC', $owner['uri-date'].'+00:00', ATOM_TIME);
480 $picdate = datetime_convert('UTC', 'UTC', $owner['avatar-date'].'+00:00', ATOM_TIME);
482 if (!$public OR !$hidewall)
483 $attributes = array("dfrn:updated" => $namdate);
485 $attributes = array();
487 xml::add_element($doc, $author, "name", $owner["name"], $attributes);
488 xml::add_element($doc, $author, "uri", app::get_baseurl().'/profile/'.$owner["nickname"], $attributes);
489 xml::add_element($doc, $author, "dfrn:handle", $owner["addr"], $attributes);
491 $attributes = array("rel" => "photo", "type" => "image/jpeg",
492 "media:width" => 175, "media:height" => 175, "href" => $owner['photo']);
494 if (!$public OR !$hidewall)
495 $attributes["dfrn:updated"] = $picdate;
497 xml::add_element($doc, $author, "link", "", $attributes);
499 $attributes["rel"] = "avatar";
500 xml::add_element($doc, $author, "link", "", $attributes);
503 xml::add_element($doc, $author, "dfrn:hide", "true");
505 // The following fields will only be generated if the data isn't meant for a public feed
509 $birthday = feed_birthday($owner['uid'], $owner['timezone']);
512 xml::add_element($doc, $author, "dfrn:birthday", $birthday);
514 // Only show contact details when we are allowed to
515 $r = q("SELECT `profile`.`about`, `profile`.`name`, `profile`.`homepage`, `user`.`nickname`,
516 `user`.`timezone`, `profile`.`locality`, `profile`.`region`, `profile`.`country-name`,
517 `profile`.`pub_keywords`, `profile`.`xmpp`, `profile`.`dob`
519 INNER JOIN `user` ON `user`.`uid` = `profile`.`uid`
520 WHERE `profile`.`is-default` AND NOT `user`.`hidewall` AND `user`.`uid` = %d",
521 intval($owner['uid']));
525 xml::add_element($doc, $author, "poco:displayName", $profile["name"]);
526 xml::add_element($doc, $author, "poco:updated", $namdate);
528 if (trim($profile["dob"]) != "0000-00-00")
529 xml::add_element($doc, $author, "poco:birthday", "0000-".date("m-d", strtotime($profile["dob"])));
531 xml::add_element($doc, $author, "poco:note", $profile["about"]);
532 xml::add_element($doc, $author, "poco:preferredUsername", $profile["nickname"]);
534 $savetz = date_default_timezone_get();
535 date_default_timezone_set($profile["timezone"]);
536 xml::add_element($doc, $author, "poco:utcOffset", date("P"));
537 date_default_timezone_set($savetz);
539 if (trim($profile["homepage"]) != "") {
540 $urls = $doc->createElement("poco:urls");
541 xml::add_element($doc, $urls, "poco:type", "homepage");
542 xml::add_element($doc, $urls, "poco:value", $profile["homepage"]);
543 xml::add_element($doc, $urls, "poco:primary", "true");
544 $author->appendChild($urls);
547 if (trim($profile["pub_keywords"]) != "") {
548 $keywords = explode(",", $profile["pub_keywords"]);
550 foreach ($keywords AS $keyword)
551 xml::add_element($doc, $author, "poco:tags", trim($keyword));
555 if (trim($profile["xmpp"]) != "") {
556 $ims = $doc->createElement("poco:ims");
557 xml::add_element($doc, $ims, "poco:type", "xmpp");
558 xml::add_element($doc, $ims, "poco:value", $profile["xmpp"]);
559 xml::add_element($doc, $ims, "poco:primary", "true");
560 $author->appendChild($ims);
563 if (trim($profile["locality"].$profile["region"].$profile["country-name"]) != "") {
564 $element = $doc->createElement("poco:address");
566 xml::add_element($doc, $element, "poco:formatted", formatted_location($profile));
568 if (trim($profile["locality"]) != "")
569 xml::add_element($doc, $element, "poco:locality", $profile["locality"]);
571 if (trim($profile["region"]) != "")
572 xml::add_element($doc, $element, "poco:region", $profile["region"]);
574 if (trim($profile["country-name"]) != "")
575 xml::add_element($doc, $element, "poco:country", $profile["country-name"]);
577 $author->appendChild($element);
585 * @brief Adds the author elements in the "entry" elements of the DFRN protocol
587 * @param object $doc XML document
588 * @param string $element Element name for the author
589 * @param string $contact_url Link of the contact
590 * @param array $items Item elements
592 * @return object XML author object
594 private static function add_entry_author($doc, $element, $contact_url, $item) {
596 $contact = get_contact_details_by_url($contact_url, $item["uid"]);
598 $author = $doc->createElement($element);
599 xml::add_element($doc, $author, "name", $contact["name"]);
600 xml::add_element($doc, $author, "uri", $contact["url"]);
601 xml::add_element($doc, $author, "dfrn:handle", $contact["addr"]);
604 /// - Check real image type and image size
605 /// - Check which of these boths elements we should use
608 "type" => "image/jpeg",
610 "media:height" => 80,
611 "href" => $contact["photo"]);
612 xml::add_element($doc, $author, "link", "", $attributes);
616 "type" => "image/jpeg",
618 "media:height" => 80,
619 "href" => $contact["photo"]);
620 xml::add_element($doc, $author, "link", "", $attributes);
626 * @brief Adds the activity elements
628 * @param object $doc XML document
629 * @param string $element Element name for the activity
630 * @param string $activity activity value
632 * @return object XML activity object
634 private static function create_activity($doc, $element, $activity) {
637 $entry = $doc->createElement($element);
639 $r = parse_xml_string($activity, false);
643 xml::add_element($doc, $entry, "activity:object-type", $r->type);
645 xml::add_element($doc, $entry, "id", $r->id);
647 xml::add_element($doc, $entry, "title", $r->title);
649 if(substr($r->link,0,1) == '<') {
650 if(strstr($r->link,'&') && (! strstr($r->link,'&')))
651 $r->link = str_replace('&','&', $r->link);
653 $r->link = preg_replace('/\<link(.*?)\"\>/','<link$1"/>',$r->link);
655 // XML does need a single element as root element so we add a dummy element here
656 $data = parse_xml_string("<dummy>".$r->link."</dummy>", false);
657 if (is_object($data)) {
658 foreach ($data->link AS $link) {
659 $attributes = array();
660 foreach ($link->attributes() AS $parameter => $value)
661 $attributes[$parameter] = $value;
662 xml::add_element($doc, $entry, "link", "", $attributes);
666 $attributes = array("rel" => "alternate", "type" => "text/html", "href" => $r->link);
667 xml::add_element($doc, $entry, "link", "", $attributes);
671 xml::add_element($doc, $entry, "content", bbcode($r->content), array("type" => "html"));
680 * @brief Adds the elements for attachments
682 * @param object $doc XML document
683 * @param object $root XML root
684 * @param array $item Item element
686 * @return object XML attachment object
688 private static function get_attachment($doc, $root, $item) {
689 $arr = explode('[/attach],',$item['attach']);
691 foreach($arr as $r) {
693 $cnt = preg_match('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\" title=\"(.*?)\"|',$r,$matches);
695 $attributes = array("rel" => "enclosure",
696 "href" => $matches[1],
697 "type" => $matches[3]);
699 if(intval($matches[2]))
700 $attributes["length"] = intval($matches[2]);
702 if(trim($matches[4]) != "")
703 $attributes["title"] = trim($matches[4]);
705 xml::add_element($doc, $root, "link", "", $attributes);
712 * @brief Adds the "entry" elements for the DFRN protocol
714 * @param object $doc XML document
715 * @param string $type "text" or "html"
716 * @param array $item Item element
717 * @param array $owner Owner record
718 * @param bool $comment Trigger the sending of the "comment" element
719 * @param int $cid Contact ID of the recipient
721 * @return object XML entry object
723 private static function entry($doc, $type, $item, $owner, $comment = false, $cid = 0) {
725 $mentioned = array();
730 if($item['deleted']) {
731 $attributes = array("ref" => $item['uri'], "when" => datetime_convert('UTC','UTC',$item['edited'] . '+00:00',ATOM_TIME));
732 return xml::create_element($doc, "at:deleted-entry", "", $attributes);
735 $entry = $doc->createElement("entry");
737 if($item['allow_cid'] || $item['allow_gid'] || $item['deny_cid'] || $item['deny_gid'])
738 $body = fix_private_photos($item['body'],$owner['uid'],$item,$cid);
740 $body = $item['body'];
742 // Remove the abstract element. It is only locally important.
743 $body = remove_abstract($body);
745 if ($type == 'html') {
748 if ($item['title'] != "")
749 $htmlbody = "[b]".$item['title']."[/b]\n\n".$htmlbody;
751 $htmlbody = bbcode($htmlbody, false, false, 7);
754 $author = self::add_entry_author($doc, "author", $item["author-link"], $item);
755 $entry->appendChild($author);
757 $dfrnowner = self::add_entry_author($doc, "dfrn:owner", $item["owner-link"], $item);
758 $entry->appendChild($dfrnowner);
760 if(($item['parent'] != $item['id']) || ($item['parent-uri'] !== $item['uri']) || (($item['thr-parent'] !== '') && ($item['thr-parent'] !== $item['uri']))) {
761 $parent = q("SELECT `guid` FROM `item` WHERE `id` = %d", intval($item["parent"]));
762 $parent_item = (($item['thr-parent']) ? $item['thr-parent'] : $item['parent-uri']);
763 $attributes = array("ref" => $parent_item, "type" => "text/html",
764 "href" => app::get_baseurl().'/display/'.$parent[0]['guid'],
765 "dfrn:diaspora_guid" => $parent[0]['guid']);
766 xml::add_element($doc, $entry, "thr:in-reply-to", "", $attributes);
769 xml::add_element($doc, $entry, "id", $item["uri"]);
770 xml::add_element($doc, $entry, "title", $item["title"]);
772 xml::add_element($doc, $entry, "published", datetime_convert("UTC","UTC",$item["created"]."+00:00",ATOM_TIME));
773 xml::add_element($doc, $entry, "updated", datetime_convert("UTC","UTC",$item["edited"]."+00:00",ATOM_TIME));
775 // "dfrn:env" is used to read the content
776 xml::add_element($doc, $entry, "dfrn:env", base64url_encode($body, true));
778 // The "content" field is not read by the receiver. We could remove it when the type is "text"
779 // We keep it at the moment, maybe there is some old version that doesn't read "dfrn:env"
780 xml::add_element($doc, $entry, "content", (($type == 'html') ? $htmlbody : $body), array("type" => $type));
782 // We save this value in "plink". Maybe we should read it from there as well?
783 xml::add_element($doc, $entry, "link", "", array("rel" => "alternate", "type" => "text/html",
784 "href" => app::get_baseurl()."/display/".$item["guid"]));
786 // "comment-allow" is some old fashioned stuff for old Friendica versions.
787 // It is included in the rewritten code for completeness
789 xml::add_element($doc, $entry, "dfrn:comment-allow", intval($item['last-child']));
791 if($item['location'])
792 xml::add_element($doc, $entry, "dfrn:location", $item['location']);
795 xml::add_element($doc, $entry, "georss:point", $item['coord']);
797 if(($item['private']) || strlen($item['allow_cid']) || strlen($item['allow_gid']) || strlen($item['deny_cid']) || strlen($item['deny_gid']))
798 xml::add_element($doc, $entry, "dfrn:private", (($item['private']) ? $item['private'] : 1));
801 xml::add_element($doc, $entry, "dfrn:extid", $item['extid']);
803 if($item['bookmark'])
804 xml::add_element($doc, $entry, "dfrn:bookmark", "true");
807 xml::add_element($doc, $entry, "statusnet:notice_info", "", array("local_id" => $item['id'], "source" => $item['app']));
809 xml::add_element($doc, $entry, "dfrn:diaspora_guid", $item["guid"]);
811 // The signed text contains the content in Markdown, the sender handle and the signatur for the content
812 // It is needed for relayed comments to Diaspora.
813 if($item['signed_text']) {
814 $sign = base64_encode(json_encode(array('signed_text' => $item['signed_text'],'signature' => $item['signature'],'signer' => $item['signer'])));
815 xml::add_element($doc, $entry, "dfrn:diaspora_signature", $sign);
818 xml::add_element($doc, $entry, "activity:verb", construct_verb($item));
820 if ($item['object-type'] != "")
821 xml::add_element($doc, $entry, "activity:object-type", $item['object-type']);
822 elseif ($item['id'] == $item['parent'])
823 xml::add_element($doc, $entry, "activity:object-type", ACTIVITY_OBJ_NOTE);
825 xml::add_element($doc, $entry, "activity:object-type", ACTIVITY_OBJ_COMMENT);
827 $actobj = self::create_activity($doc, "activity:object", $item['object']);
829 $entry->appendChild($actobj);
831 $actarg = self::create_activity($doc, "activity:target", $item['target']);
833 $entry->appendChild($actarg);
835 $tags = item_getfeedtags($item);
839 if (($type != 'html') OR ($t[0] != "@"))
840 xml::add_element($doc, $entry, "category", "", array("scheme" => "X-DFRN:".$t[0].":".$t[1], "term" => $t[2]));
846 $mentioned[$t[1]] = $t[1];
848 foreach ($mentioned AS $mention) {
849 $r = q("SELECT `forum`, `prv` FROM `contact` WHERE `uid` = %d AND `nurl` = '%s'",
850 intval($owner["uid"]),
851 dbesc(normalise_link($mention)));
852 if ($r[0]["forum"] OR $r[0]["prv"])
853 xml::add_element($doc, $entry, "link", "", array("rel" => "mentioned",
854 "ostatus:object-type" => ACTIVITY_OBJ_GROUP,
855 "href" => $mention));
857 xml::add_element($doc, $entry, "link", "", array("rel" => "mentioned",
858 "ostatus:object-type" => ACTIVITY_OBJ_PERSON,
859 "href" => $mention));
862 self::get_attachment($doc, $entry, $item);
868 * @brief encrypts data via AES
870 * @param string $data The data that is to be encrypted
871 * @param string $key The AES key
873 * @return string encrypted data
875 private static function aes_encrypt($data, $key) {
876 return openssl_encrypt($data, 'aes-128-ecb', $key, OPENSSL_RAW_DATA);
880 * @brief decrypts data via AES
882 * @param string $encrypted The encrypted data
883 * @param string $key The AES key
885 * @return string decrypted data
887 public static function aes_decrypt($encrypted, $key) {
888 return openssl_decrypt($encrypted, 'aes-128-ecb', $key, OPENSSL_RAW_DATA);
892 * @brief Delivers the atom content to the contacts
894 * @param array $owner Owner record
895 * @param array $contactr Contact record of the receiver
896 * @param string $atom Content that will be transmitted
897 * @param bool $dissolve (to be documented)
899 * @return int Deliver status. -1 means an error.
901 public static function deliver($owner,$contact,$atom, $dissolve = false) {
905 $idtosend = $orig_id = (($contact['dfrn-id']) ? $contact['dfrn-id'] : $contact['issued-id']);
907 if($contact['duplex'] && $contact['dfrn-id'])
908 $idtosend = '0:' . $orig_id;
909 if($contact['duplex'] && $contact['issued-id'])
910 $idtosend = '1:' . $orig_id;
913 $rino = get_config('system','rino_encrypt');
914 $rino = intval($rino);
916 logger("Local rino version: ". $rino, LOGGER_DEBUG);
918 $ssl_val = intval(get_config('system','ssl_policy'));
922 case SSL_POLICY_FULL:
923 $ssl_policy = 'full';
925 case SSL_POLICY_SELFSIGN:
926 $ssl_policy = 'self';
928 case SSL_POLICY_NONE:
930 $ssl_policy = 'none';
934 $url = $contact['notify'] . '&dfrn_id=' . $idtosend . '&dfrn_version=' . DFRN_PROTOCOL_VERSION . (($rino) ? '&rino='.$rino : '');
936 logger('dfrn_deliver: ' . $url);
938 $ret = z_fetch_url($url);
940 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
941 return -2; // timed out
946 $curl_stat = $a->get_curl_code();
948 return -3; // timed out
951 logger('dfrn_deliver: ' . $xml, LOGGER_DATA);
956 if(strpos($xml,'<?xml') === false) {
957 logger('dfrn_deliver: no valid XML returned');
958 logger('dfrn_deliver: returned XML: ' . $xml, LOGGER_DATA);
962 $res = parse_xml_string($xml);
964 if((intval($res->status) != 0) || (! strlen($res->challenge)) || (! strlen($res->dfrn_id)))
965 return (($res->status) ? $res->status : 3);
968 $sent_dfrn_id = hex2bin((string) $res->dfrn_id);
969 $challenge = hex2bin((string) $res->challenge);
970 $perm = (($res->perm) ? $res->perm : null);
971 $dfrn_version = (float) (($res->dfrn_version) ? $res->dfrn_version : 2.0);
972 $rino_remote_version = intval($res->rino);
973 $page = (($owner['page-flags'] == PAGE_COMMUNITY) ? 1 : 0);
975 logger("Remote rino version: ".$rino_remote_version." for ".$contact["url"], LOGGER_DEBUG);
977 if($owner['page-flags'] == PAGE_PRVGROUP)
983 if((($perm == 'rw') && (! intval($contact['writable'])))
984 || (($perm == 'r') && (intval($contact['writable'])))) {
985 q("update contact set writable = %d where id = %d",
986 intval(($perm == 'rw') ? 1 : 0),
987 intval($contact['id'])
989 $contact['writable'] = (string) 1 - intval($contact['writable']);
993 if(($contact['duplex'] && strlen($contact['pubkey']))
994 || ($owner['page-flags'] == PAGE_COMMUNITY && strlen($contact['pubkey']))
995 || ($contact['rel'] == CONTACT_IS_SHARING && strlen($contact['pubkey']))) {
996 openssl_public_decrypt($sent_dfrn_id,$final_dfrn_id,$contact['pubkey']);
997 openssl_public_decrypt($challenge,$postvars['challenge'],$contact['pubkey']);
999 openssl_private_decrypt($sent_dfrn_id,$final_dfrn_id,$contact['prvkey']);
1000 openssl_private_decrypt($challenge,$postvars['challenge'],$contact['prvkey']);
1003 $final_dfrn_id = substr($final_dfrn_id, 0, strpos($final_dfrn_id, '.'));
1005 if(strpos($final_dfrn_id,':') == 1)
1006 $final_dfrn_id = substr($final_dfrn_id,2);
1008 if($final_dfrn_id != $orig_id) {
1009 logger('dfrn_deliver: wrong dfrn_id.');
1010 // did not decode properly - cannot trust this site
1014 $postvars['dfrn_id'] = $idtosend;
1015 $postvars['dfrn_version'] = DFRN_PROTOCOL_VERSION;
1017 $postvars['dissolve'] = '1';
1020 if((($contact['rel']) && ($contact['rel'] != CONTACT_IS_SHARING) && (! $contact['blocked'])) || ($owner['page-flags'] == PAGE_COMMUNITY)) {
1021 $postvars['data'] = $atom;
1022 $postvars['perm'] = 'rw';
1024 $postvars['data'] = str_replace('<dfrn:comment-allow>1','<dfrn:comment-allow>0',$atom);
1025 $postvars['perm'] = 'r';
1028 $postvars['ssl_policy'] = $ssl_policy;
1031 $postvars['page'] = $page;
1034 if($rino>0 && $rino_remote_version>0 && (! $dissolve)) {
1035 logger('rino version: '. $rino_remote_version);
1037 switch($rino_remote_version) {
1039 // Deprecated rino version!
1040 $key = openssl_random_pseudo_bytes(16);
1041 $data = self::aes_encrypt($postvars['data'], $key);
1044 // RINO 2 based on php-encryption
1046 $key = Crypto::createNewRandomKey();
1047 } catch (CryptoTestFailed $ex) {
1048 logger('Cannot safely create a key');
1050 } catch (CannotPerformOperation $ex) {
1051 logger('Cannot safely create a key');
1055 $data = Crypto::encrypt($postvars['data'], $key);
1056 } catch (CryptoTestFailed $ex) {
1057 logger('Cannot safely perform encryption');
1059 } catch (CannotPerformOperation $ex) {
1060 logger('Cannot safely perform encryption');
1065 logger("rino: invalid requested verision '$rino_remote_version'");
1069 $postvars['rino'] = $rino_remote_version;
1070 $postvars['data'] = bin2hex($data);
1072 #logger('rino: sent key = ' . $key, LOGGER_DEBUG);
1075 if($dfrn_version >= 2.1) {
1076 if(($contact['duplex'] && strlen($contact['pubkey']))
1077 || ($owner['page-flags'] == PAGE_COMMUNITY && strlen($contact['pubkey']))
1078 || ($contact['rel'] == CONTACT_IS_SHARING && strlen($contact['pubkey'])))
1080 openssl_public_encrypt($key,$postvars['key'],$contact['pubkey']);
1082 openssl_private_encrypt($key,$postvars['key'],$contact['prvkey']);
1085 if(($contact['duplex'] && strlen($contact['prvkey'])) || ($owner['page-flags'] == PAGE_COMMUNITY))
1086 openssl_private_encrypt($key,$postvars['key'],$contact['prvkey']);
1088 openssl_public_encrypt($key,$postvars['key'],$contact['pubkey']);
1092 logger('md5 rawkey ' . md5($postvars['key']));
1094 $postvars['key'] = bin2hex($postvars['key']);
1098 logger('dfrn_deliver: ' . "SENDING: " . print_r($postvars,true), LOGGER_DATA);
1100 $xml = post_url($contact['notify'], $postvars);
1102 logger('dfrn_deliver: ' . "RECEIVED: " . $xml, LOGGER_DATA);
1104 $curl_stat = $a->get_curl_code();
1105 if ((!$curl_stat) || (!strlen($xml))) {
1106 return -9; // timed out
1109 if (($curl_stat == 503) && (stristr($a->get_curl_headers(),'retry-after'))) {
1113 if(strpos($xml,'<?xml') === false) {
1114 logger('dfrn_deliver: phase 2: no valid XML returned');
1115 logger('dfrn_deliver: phase 2: returned XML: ' . $xml, LOGGER_DATA);
1119 if ($contact['term-date'] > NULL_DATE) {
1120 logger("dfrn_deliver: $url back from the dead - removing mark for death");
1121 require_once('include/Contact.php');
1122 unmark_for_death($contact);
1125 $res = parse_xml_string($xml);
1127 return $res->status;
1131 * @brief Add new birthday event for this person
1133 * @param array $contact Contact record
1134 * @param string $birthday Birthday of the contact
1137 private static function birthday_event($contact, $birthday) {
1139 // Check for duplicates
1140 $r = q("SELECT `id` FROM `event` WHERE `uid` = %d AND `cid` = %d AND `start` = '%s' AND `type` = '%s' LIMIT 1",
1141 intval($contact["uid"]),
1142 intval($contact["id"]),
1143 dbesc(datetime_convert("UTC","UTC", $birthday)),
1146 if (dbm::is_result($r)) {
1150 logger("updating birthday: ".$birthday." for contact ".$contact["id"]);
1152 $bdtext = sprintf(t("%s\'s birthday"), $contact["name"]);
1153 $bdtext2 = sprintf(t("Happy Birthday %s"), " [url=".$contact["url"]."]".$contact["name"]."[/url]") ;
1155 $r = q("INSERT INTO `event` (`uid`,`cid`,`created`,`edited`,`start`,`finish`,`summary`,`desc`,`type`)
1156 VALUES ( %d, %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s') ",
1157 intval($contact["uid"]),
1158 intval($contact["id"]),
1159 dbesc(datetime_convert()),
1160 dbesc(datetime_convert()),
1161 dbesc(datetime_convert("UTC","UTC", $birthday)),
1162 dbesc(datetime_convert("UTC","UTC", $birthday." + 1 day ")),
1170 * @brief Fetch the author data from head or entry items
1172 * @param object $xpath XPath object
1173 * @param object $context In which context should the data be searched
1174 * @param array $importer Record of the importer user mixed with contact of the content
1175 * @param string $element Element name from which the data is fetched
1176 * @param bool $onlyfetch Should the data only be fetched or should it update the contact record as well
1178 * @return Returns an array with relevant data of the author
1180 private static function fetchauthor($xpath, $context, $importer, $element, $onlyfetch, $xml = "") {
1183 $author["name"] = $xpath->evaluate($element."/atom:name/text()", $context)->item(0)->nodeValue;
1184 $author["link"] = $xpath->evaluate($element."/atom:uri/text()", $context)->item(0)->nodeValue;
1186 $r = q("SELECT `id`, `uid`, `url`, `network`, `avatar-date`, `name-date`, `uri-date`, `addr`,
1187 `name`, `nick`, `about`, `location`, `keywords`, `xmpp`, `bdyear`, `bd`, `hidden`, `contact-type`
1188 FROM `contact` WHERE `uid` = %d AND `nurl` = '%s' AND `network` != '%s'",
1189 intval($importer["uid"]), dbesc(normalise_link($author["link"])), dbesc(NETWORK_STATUSNET));
1192 $author["contact-id"] = $r[0]["id"];
1193 $author["network"] = $r[0]["network"];
1196 logger("Contact ".$author["link"]." wasn't found for user ".$importer["uid"]." XML: ".$xml, LOGGER_DEBUG);
1198 $author["contact-id"] = $importer["id"];
1199 $author["network"] = $importer["network"];
1203 // Until now we aren't serving different sizes - but maybe later
1204 $avatarlist = array();
1205 /// @todo check if "avatar" or "photo" would be the best field in the specification
1206 $avatars = $xpath->query($element."/atom:link[@rel='avatar']", $context);
1207 foreach($avatars AS $avatar) {
1210 foreach($avatar->attributes AS $attributes) {
1211 if ($attributes->name == "href")
1212 $href = $attributes->textContent;
1213 if ($attributes->name == "width")
1214 $width = $attributes->textContent;
1215 if ($attributes->name == "updated")
1216 $contact["avatar-date"] = $attributes->textContent;
1218 if (($width > 0) AND ($href != ""))
1219 $avatarlist[$width] = $href;
1221 if (count($avatarlist) > 0) {
1222 krsort($avatarlist);
1223 $author["avatar"] = current($avatarlist);
1226 if ($r AND !$onlyfetch) {
1227 logger("Check if contact details for contact ".$r[0]["id"]." (".$r[0]["nick"].") have to be updated.", LOGGER_DEBUG);
1229 $poco = array("url" => $contact["url"]);
1231 // When was the last change to name or uri?
1232 $name_element = $xpath->query($element."/atom:name", $context)->item(0);
1233 foreach($name_element->attributes AS $attributes)
1234 if ($attributes->name == "updated")
1235 $poco["name-date"] = $attributes->textContent;
1237 $link_element = $xpath->query($element."/atom:link", $context)->item(0);
1238 foreach($link_element->attributes AS $attributes)
1239 if ($attributes->name == "updated")
1240 $poco["uri-date"] = $attributes->textContent;
1242 // Update contact data
1243 $value = $xpath->evaluate($element."/dfrn:handle/text()", $context)->item(0)->nodeValue;
1245 $poco["addr"] = $value;
1247 $value = $xpath->evaluate($element."/poco:displayName/text()", $context)->item(0)->nodeValue;
1249 $poco["name"] = $value;
1251 $value = $xpath->evaluate($element."/poco:preferredUsername/text()", $context)->item(0)->nodeValue;
1253 $poco["nick"] = $value;
1255 $value = $xpath->evaluate($element."/poco:note/text()", $context)->item(0)->nodeValue;
1257 $poco["about"] = $value;
1259 $value = $xpath->evaluate($element."/poco:address/poco:formatted/text()", $context)->item(0)->nodeValue;
1261 $poco["location"] = $value;
1263 /// @todo Only search for elements with "poco:type" = "xmpp"
1264 $value = $xpath->evaluate($element."/poco:ims/poco:value/text()", $context)->item(0)->nodeValue;
1266 $poco["xmpp"] = $value;
1268 /// @todo Add support for the following fields that we don't support by now in the contact table:
1269 /// - poco:utcOffset
1275 // If the "hide" element is present then the profile isn't searchable.
1276 $hide = intval($xpath->evaluate($element."/dfrn:hide/text()", $context)->item(0)->nodeValue == "true");
1278 logger("Hidden status for contact ".$contact["url"].": ".$hide, LOGGER_DEBUG);
1280 // If the contact isn't searchable then set the contact to "hidden".
1281 // Problem: This can be manually overridden by the user.
1283 $contact["hidden"] = true;
1285 // Save the keywords into the contact table
1287 $tagelements = $xpath->evaluate($element."/poco:tags/text()", $context);
1288 foreach($tagelements AS $tag)
1289 $tags[$tag->nodeValue] = $tag->nodeValue;
1292 $poco["keywords"] = implode(", ", $tags);
1294 // "dfrn:birthday" contains the birthday converted to UTC
1295 $old_bdyear = $contact["bdyear"];
1297 $birthday = $xpath->evaluate($element."/dfrn:birthday/text()", $context)->item(0)->nodeValue;
1299 if (strtotime($birthday) > time()) {
1300 $bd_timestamp = strtotime($birthday);
1302 $poco["bdyear"] = date("Y", $bd_timestamp);
1305 // "poco:birthday" is the birthday in the format "yyyy-mm-dd"
1306 $value = $xpath->evaluate($element."/poco:birthday/text()", $context)->item(0)->nodeValue;
1308 if (!in_array($value, array("", "0000-00-00"))) {
1309 $bdyear = date("Y");
1310 $value = str_replace("0000", $bdyear, $value);
1312 if (strtotime($value) < time()) {
1313 $value = str_replace($bdyear, $bdyear + 1, $value);
1314 $bdyear = $bdyear + 1;
1317 $poco["bd"] = $value;
1320 $contact = array_merge($contact, $poco);
1322 if ($old_bdyear != $contact["bdyear"])
1323 self::birthday_event($contact, $birthday);
1325 // Get all field names
1327 foreach ($r[0] AS $field => $data)
1328 $fields[$field] = $data;
1330 unset($fields["id"]);
1331 unset($fields["uid"]);
1332 unset($fields["url"]);
1333 unset($fields["avatar-date"]);
1334 unset($fields["name-date"]);
1335 unset($fields["uri-date"]);
1337 // Update check for this field has to be done differently
1338 $datefields = array("name-date", "uri-date");
1339 foreach ($datefields AS $field)
1340 if (strtotime($contact[$field]) > strtotime($r[0][$field])) {
1341 logger("Difference for contact ".$contact["id"]." in field '".$field."'. New value: '".$contact[$field]."', old value '".$r[0][$field]."'", LOGGER_DEBUG);
1345 foreach ($fields AS $field => $data)
1346 if ($contact[$field] != $r[0][$field]) {
1347 logger("Difference for contact ".$contact["id"]." in field '".$field."'. New value: '".$contact[$field]."', old value '".$r[0][$field]."'", LOGGER_DEBUG);
1352 logger("Update contact data for contact ".$contact["id"]." (".$contact["nick"].")", LOGGER_DEBUG);
1354 q("UPDATE `contact` SET `name` = '%s', `nick` = '%s', `about` = '%s', `location` = '%s',
1355 `addr` = '%s', `keywords` = '%s', `bdyear` = '%s', `bd` = '%s', `hidden` = %d,
1356 `xmpp` = '%s', `name-date` = '%s', `uri-date` = '%s'
1357 WHERE `id` = %d AND `network` = '%s'",
1358 dbesc($contact["name"]), dbesc($contact["nick"]), dbesc($contact["about"]), dbesc($contact["location"]),
1359 dbesc($contact["addr"]), dbesc($contact["keywords"]), dbesc($contact["bdyear"]),
1360 dbesc($contact["bd"]), intval($contact["hidden"]), dbesc($contact["xmpp"]),
1361 dbesc($contact["name-date"]), dbesc($contact["uri-date"]),
1362 intval($contact["id"]), dbesc($contact["network"]));
1365 update_contact_avatar($author["avatar"], $importer["uid"], $contact["id"],
1366 (strtotime($contact["avatar-date"]) > strtotime($r[0]["avatar-date"])));
1368 // The generation is a sign for the reliability of the provided data.
1369 // It is used in the socgraph.php to prevent that old contact data
1370 // that was relayed over several servers can overwrite contact
1371 // data that we received directly.
1373 $poco["generation"] = 2;
1374 $poco["photo"] = $author["avatar"];
1375 $poco["hide"] = $hide;
1376 $poco["contact-type"] = $contact["contact-type"];
1377 $gcid = update_gcontact($poco);
1379 link_gcontact($gcid, $importer["uid"], $contact["id"]);
1386 * @brief Transforms activity objects into an XML string
1388 * @param object $xpath XPath object
1389 * @param object $activity Activity object
1390 * @param text $element element name
1392 * @return string XML string
1394 private static function transform_activity($xpath, $activity, $element) {
1395 if (!is_object($activity))
1398 $obj_doc = new DOMDocument("1.0", "utf-8");
1399 $obj_doc->formatOutput = true;
1401 $obj_element = $obj_doc->createElementNS(NAMESPACE_ATOM1, $element);
1403 $activity_type = $xpath->query("activity:object-type/text()", $activity)->item(0)->nodeValue;
1404 xml::add_element($obj_doc, $obj_element, "type", $activity_type);
1406 $id = $xpath->query("atom:id", $activity)->item(0);
1408 $obj_element->appendChild($obj_doc->importNode($id, true));
1410 $title = $xpath->query("atom:title", $activity)->item(0);
1411 if (is_object($title))
1412 $obj_element->appendChild($obj_doc->importNode($title, true));
1414 $links = $xpath->query("atom:link", $activity);
1415 if (is_object($links))
1416 foreach ($links AS $link)
1417 $obj_element->appendChild($obj_doc->importNode($link, true));
1419 $content = $xpath->query("atom:content", $activity)->item(0);
1420 if (is_object($content))
1421 $obj_element->appendChild($obj_doc->importNode($content, true));
1423 $obj_doc->appendChild($obj_element);
1425 $objxml = $obj_doc->saveXML($obj_element);
1427 /// @todo This isn't totally clean. We should find a way to transform the namespaces
1428 $objxml = str_replace("<".$element.' xmlns="http://www.w3.org/2005/Atom">', "<".$element.">", $objxml);
1433 * @brief Processes the mail elements
1435 * @param object $xpath XPath object
1436 * @param object $mail mail elements
1437 * @param array $importer Record of the importer user mixed with contact of the content
1439 private static function process_mail($xpath, $mail, $importer) {
1441 logger("Processing mails");
1444 $msg["uid"] = $importer["importer_uid"];
1445 $msg["from-name"] = $xpath->query("dfrn:sender/dfrn:name/text()", $mail)->item(0)->nodeValue;
1446 $msg["from-url"] = $xpath->query("dfrn:sender/dfrn:uri/text()", $mail)->item(0)->nodeValue;
1447 $msg["from-photo"] = $xpath->query("dfrn:sender/dfrn:avatar/text()", $mail)->item(0)->nodeValue;
1448 $msg["contact-id"] = $importer["id"];
1449 $msg["uri"] = $xpath->query("dfrn:id/text()", $mail)->item(0)->nodeValue;
1450 $msg["parent-uri"] = $xpath->query("dfrn:in-reply-to/text()", $mail)->item(0)->nodeValue;
1451 $msg["created"] = $xpath->query("dfrn:sentdate/text()", $mail)->item(0)->nodeValue;
1452 $msg["title"] = $xpath->query("dfrn:subject/text()", $mail)->item(0)->nodeValue;
1453 $msg["body"] = $xpath->query("dfrn:content/text()", $mail)->item(0)->nodeValue;
1455 $msg["replied"] = 0;
1457 dbm::esc_array($msg, true);
1459 $r = dbq("INSERT INTO `mail` (`".implode("`, `", array_keys($msg))."`) VALUES (".implode(", ", array_values($msg)).")");
1461 // send notifications.
1463 $notif_params = array(
1464 "type" => NOTIFY_MAIL,
1465 "notify_flags" => $importer["notify-flags"],
1466 "language" => $importer["language"],
1467 "to_name" => $importer["username"],
1468 "to_email" => $importer["email"],
1469 "uid" => $importer["importer_uid"],
1471 "source_name" => $msg["from-name"],
1472 "source_link" => $importer["url"],
1473 "source_photo" => $importer["thumb"],
1474 "verb" => ACTIVITY_POST,
1478 notification($notif_params);
1480 logger("Mail is processed, notification was sent.");
1484 * @brief Processes the suggestion elements
1486 * @param object $xpath XPath object
1487 * @param object $suggestion suggestion elements
1488 * @param array $importer Record of the importer user mixed with contact of the content
1490 private static function process_suggestion($xpath, $suggestion, $importer) {
1493 logger("Processing suggestions");
1496 $suggest["uid"] = $importer["importer_uid"];
1497 $suggest["cid"] = $importer["id"];
1498 $suggest["url"] = $xpath->query("dfrn:url/text()", $suggestion)->item(0)->nodeValue;
1499 $suggest["name"] = $xpath->query("dfrn:name/text()", $suggestion)->item(0)->nodeValue;
1500 $suggest["photo"] = $xpath->query("dfrn:photo/text()", $suggestion)->item(0)->nodeValue;
1501 $suggest["request"] = $xpath->query("dfrn:request/text()", $suggestion)->item(0)->nodeValue;
1502 $suggest["body"] = $xpath->query("dfrn:note/text()", $suggestion)->item(0)->nodeValue;
1504 // Does our member already have a friend matching this description?
1506 $r = q("SELECT `id` FROM `contact` WHERE `name` = '%s' AND `nurl` = '%s' AND `uid` = %d LIMIT 1",
1507 dbesc($suggest["name"]),
1508 dbesc(normalise_link($suggest["url"])),
1509 intval($suggest["uid"])
1511 if (dbm::is_result($r))
1514 // Do we already have an fcontact record for this person?
1517 $r = q("SELECT `id` FROM `fcontact` WHERE `url` = '%s' AND `name` = '%s' AND `request` = '%s' LIMIT 1",
1518 dbesc($suggest["url"]),
1519 dbesc($suggest["name"]),
1520 dbesc($suggest["request"])
1522 if (dbm::is_result($r)) {
1525 // OK, we do. Do we already have an introduction for this person ?
1526 $r = q("SELECT `id` FROM `intro` WHERE `uid` = %d AND `fid` = %d LIMIT 1",
1527 intval($suggest["uid"]),
1530 if (dbm::is_result($r))
1534 $r = q("INSERT INTO `fcontact` (`name`,`url`,`photo`,`request`) VALUES ('%s', '%s', '%s', '%s')",
1535 dbesc($suggest["name"]),
1536 dbesc($suggest["url"]),
1537 dbesc($suggest["photo"]),
1538 dbesc($suggest["request"])
1540 $r = q("SELECT `id` FROM `fcontact` WHERE `url` = '%s' AND `name` = '%s' AND `request` = '%s' LIMIT 1",
1541 dbesc($suggest["url"]),
1542 dbesc($suggest["name"]),
1543 dbesc($suggest["request"])
1545 if (dbm::is_result($r))
1548 // database record did not get created. Quietly give up.
1552 $hash = random_string();
1554 $r = q("INSERT INTO `intro` (`uid`, `fid`, `contact-id`, `note`, `hash`, `datetime`, `blocked`)
1555 VALUES(%d, %d, %d, '%s', '%s', '%s', %d)",
1556 intval($suggest["uid"]),
1558 intval($suggest["cid"]),
1559 dbesc($suggest["body"]),
1561 dbesc(datetime_convert()),
1566 "type" => NOTIFY_SUGGEST,
1567 "notify_flags" => $importer["notify-flags"],
1568 "language" => $importer["language"],
1569 "to_name" => $importer["username"],
1570 "to_email" => $importer["email"],
1571 "uid" => $importer["importer_uid"],
1573 "link" => App::get_baseurl()."/notifications/intros",
1574 "source_name" => $importer["name"],
1575 "source_link" => $importer["url"],
1576 "source_photo" => $importer["photo"],
1577 "verb" => ACTIVITY_REQ_FRIEND,
1586 * @brief Processes the relocation elements
1588 * @param object $xpath XPath object
1589 * @param object $relocation relocation elements
1590 * @param array $importer Record of the importer user mixed with contact of the content
1592 private static function process_relocation($xpath, $relocation, $importer) {
1594 logger("Processing relocations");
1596 $relocate = array();
1597 $relocate["uid"] = $importer["importer_uid"];
1598 $relocate["cid"] = $importer["id"];
1599 $relocate["url"] = $xpath->query("dfrn:url/text()", $relocation)->item(0)->nodeValue;
1600 $relocate["addr"] = $xpath->query("dfrn:addr/text()", $relocation)->item(0)->nodeValue;
1601 $relocate["name"] = $xpath->query("dfrn:name/text()", $relocation)->item(0)->nodeValue;
1602 $relocate["avatar"] = $xpath->query("dfrn:avatar/text()", $relocation)->item(0)->nodeValue;
1603 $relocate["photo"] = $xpath->query("dfrn:photo/text()", $relocation)->item(0)->nodeValue;
1604 $relocate["thumb"] = $xpath->query("dfrn:thumb/text()", $relocation)->item(0)->nodeValue;
1605 $relocate["micro"] = $xpath->query("dfrn:micro/text()", $relocation)->item(0)->nodeValue;
1606 $relocate["request"] = $xpath->query("dfrn:request/text()", $relocation)->item(0)->nodeValue;
1607 $relocate["confirm"] = $xpath->query("dfrn:confirm/text()", $relocation)->item(0)->nodeValue;
1608 $relocate["notify"] = $xpath->query("dfrn:notify/text()", $relocation)->item(0)->nodeValue;
1609 $relocate["poll"] = $xpath->query("dfrn:poll/text()", $relocation)->item(0)->nodeValue;
1610 $relocate["sitepubkey"] = $xpath->query("dfrn:sitepubkey/text()", $relocation)->item(0)->nodeValue;
1612 if (($relocate["avatar"] == "") AND ($relocate["photo"] != ""))
1613 $relocate["avatar"] = $relocate["photo"];
1615 if ($relocate["addr"] == "")
1616 $relocate["addr"] = preg_replace("=(https?://)(.*)/profile/(.*)=ism", "$3@$2", $relocate["url"]);
1619 $r = q("SELECT `photo`, `url` FROM `contact` WHERE `id` = %d AND `uid` = %d;",
1620 intval($importer["id"]),
1621 intval($importer["importer_uid"]));
1627 // Update the gcontact entry
1628 $relocate["server_url"] = preg_replace("=(https?://)(.*)/profile/(.*)=ism", "$1$2", $relocate["url"]);
1630 $x = q("UPDATE `gcontact` SET
1639 WHERE `nurl` = '%s';",
1640 dbesc($relocate["name"]),
1641 dbesc($relocate["avatar"]),
1642 dbesc($relocate["url"]),
1643 dbesc(normalise_link($relocate["url"])),
1644 dbesc($relocate["addr"]),
1645 dbesc($relocate["addr"]),
1646 dbesc($relocate["notify"]),
1647 dbesc($relocate["server_url"]),
1648 dbesc(normalise_link($old["url"])));
1650 // Update the contact table. We try to find every entry.
1651 $x = q("UPDATE `contact` SET
1661 `site-pubkey` = '%s'
1662 WHERE (`id` = %d AND `uid` = %d) OR (`nurl` = '%s');",
1663 dbesc($relocate["name"]),
1664 dbesc($relocate["avatar"]),
1665 dbesc($relocate["url"]),
1666 dbesc(normalise_link($relocate["url"])),
1667 dbesc($relocate["addr"]),
1668 dbesc($relocate["request"]),
1669 dbesc($relocate["confirm"]),
1670 dbesc($relocate["notify"]),
1671 dbesc($relocate["poll"]),
1672 dbesc($relocate["sitepubkey"]),
1673 intval($importer["id"]),
1674 intval($importer["importer_uid"]),
1675 dbesc(normalise_link($old["url"])));
1677 update_contact_avatar($relocate["avatar"], $importer["importer_uid"], $importer["id"], true);
1683 /// @todo This is an extreme performance killer
1685 'owner-link' => array($old["url"], $relocate["url"]),
1686 'author-link' => array($old["url"], $relocate["url"]),
1687 //'owner-avatar' => array($old["photo"], $relocate["photo"]),
1688 //'author-avatar' => array($old["photo"], $relocate["photo"]),
1690 foreach ($fields as $n=>$f) {
1691 $r = q("SELECT `id` FROM `item` WHERE `%s` = '%s' AND `uid` = %d LIMIT 1",
1693 intval($importer["importer_uid"]));
1696 $x = q("UPDATE `item` SET `%s` = '%s' WHERE `%s` = '%s' AND `uid` = %d",
1699 intval($importer["importer_uid"]));
1706 /// merge with current record, current contents have priority
1707 /// update record, set url-updated
1708 /// update profile photos
1709 /// schedule a scan?
1714 * @brief Updates an item
1716 * @param array $current the current item record
1717 * @param array $item the new item record
1718 * @param array $importer Record of the importer user mixed with contact of the content
1719 * @param int $entrytype Is it a toplevel entry, a comment or a relayed comment?
1721 private static function update_content($current, $item, $importer, $entrytype) {
1724 if (edited_timestamp_is_newer($current, $item)) {
1726 // do not accept (ignore) an earlier edit than one we currently have.
1727 if(datetime_convert("UTC","UTC",$item["edited"]) < $current["edited"])
1730 $r = q("UPDATE `item` SET `title` = '%s', `body` = '%s', `tag` = '%s', `edited` = '%s', `changed` = '%s' WHERE `uri` = '%s' AND `uid` = %d",
1731 dbesc($item["title"]),
1732 dbesc($item["body"]),
1733 dbesc($item["tag"]),
1734 dbesc(datetime_convert("UTC","UTC",$item["edited"])),
1735 dbesc(datetime_convert()),
1736 dbesc($item["uri"]),
1737 intval($importer["importer_uid"])
1739 create_tags_from_itemuri($item["uri"], $importer["importer_uid"]);
1740 update_thread_uri($item["uri"], $importer["importer_uid"]);
1744 if ($entrytype == DFRN_REPLY_RC)
1745 proc_run(PRIORITY_HIGH, "include/notifier.php","comment-import", $current["id"]);
1748 // update last-child if it changes
1749 if($item["last-child"] AND ($item["last-child"] != $current["last-child"])) {
1750 $r = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d",
1751 dbesc(datetime_convert()),
1752 dbesc($item["parent-uri"]),
1753 intval($importer["importer_uid"])
1755 $r = q("UPDATE `item` SET `last-child` = %d , `changed` = '%s' WHERE `uri` = '%s' AND `uid` = %d",
1756 intval($item["last-child"]),
1757 dbesc(datetime_convert()),
1758 dbesc($item["uri"]),
1759 intval($importer["importer_uid"])
1766 * @brief Detects the entry type of the item
1768 * @param array $importer Record of the importer user mixed with contact of the content
1769 * @param array $item the new item record
1771 * @return int Is it a toplevel entry, a comment or a relayed comment?
1773 private static function get_entry_type($importer, $item) {
1774 if ($item["parent-uri"] != $item["uri"]) {
1777 if($importer["page-flags"] == PAGE_COMMUNITY || $importer["page-flags"] == PAGE_PRVGROUP) {
1780 logger("possible community action");
1782 $sql_extra = " AND `contact`.`self` AND `item`.`wall` ";
1784 // was the top-level post for this action written by somebody on this site?
1785 // Specifically, the recipient?
1787 $is_a_remote_action = false;
1789 $r = q("SELECT `item`.`parent-uri` FROM `item`
1790 WHERE `item`.`uri` = '%s'
1792 dbesc($item["parent-uri"])
1794 if (dbm::is_result($r)) {
1795 $r = q("SELECT `item`.`forum_mode`, `item`.`wall` FROM `item`
1796 INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
1797 WHERE `item`.`uri` = '%s' AND (`item`.`parent-uri` = '%s' OR `item`.`thr-parent` = '%s')
1798 AND `item`.`uid` = %d
1801 dbesc($r[0]["parent-uri"]),
1802 dbesc($r[0]["parent-uri"]),
1803 dbesc($r[0]["parent-uri"]),
1804 intval($importer["importer_uid"])
1806 if (dbm::is_result($r))
1807 $is_a_remote_action = true;
1810 // Does this have the characteristics of a community or private group action?
1811 // If it's an action to a wall post on a community/prvgroup page it's a
1812 // valid community action. Also forum_mode makes it valid for sure.
1813 // If neither, it's not.
1815 if($is_a_remote_action && $community) {
1816 if((!$r[0]["forum_mode"]) && (!$r[0]["wall"])) {
1817 $is_a_remote_action = false;
1818 logger("not a community action");
1822 if ($is_a_remote_action)
1823 return DFRN_REPLY_RC;
1828 return DFRN_TOP_LEVEL;
1833 * @brief Send a "poke"
1835 * @param array $item the new item record
1836 * @param array $importer Record of the importer user mixed with contact of the content
1837 * @param int $posted_id The record number of item record that was just posted
1839 private static function do_poke($item, $importer, $posted_id) {
1840 $verb = urldecode(substr($item["verb"],strpos($item["verb"], "#")+1));
1843 $xo = parse_xml_string($item["object"],false);
1845 if(($xo->type == ACTIVITY_OBJ_PERSON) && ($xo->id)) {
1847 // somebody was poked/prodded. Was it me?
1848 foreach($xo->link as $l) {
1849 $atts = $l->attributes();
1850 switch($atts["rel"]) {
1852 $Blink = $atts["href"];
1859 if($Blink && link_compare($Blink,App::get_baseurl()."/profile/".$importer["nickname"])) {
1861 // send a notification
1863 "type" => NOTIFY_POKE,
1864 "notify_flags" => $importer["notify-flags"],
1865 "language" => $importer["language"],
1866 "to_name" => $importer["username"],
1867 "to_email" => $importer["email"],
1868 "uid" => $importer["importer_uid"],
1870 "link" => App::get_baseurl()."/display/".urlencode(get_item_guid($posted_id)),
1871 "source_name" => stripslashes($item["author-name"]),
1872 "source_link" => $item["author-link"],
1873 "source_photo" => ((link_compare($item["author-link"],$importer["url"]))
1874 ? $importer["thumb"] : $item["author-avatar"]),
1875 "verb" => $item["verb"],
1876 "otype" => "person",
1877 "activity" => $verb,
1878 "parent" => $item["parent"]
1885 * @brief Processes several actions, depending on the verb
1887 * @param int $entrytype Is it a toplevel entry, a comment or a relayed comment?
1888 * @param array $importer Record of the importer user mixed with contact of the content
1889 * @param array $item the new item record
1890 * @param bool $is_like Is the verb a "like"?
1892 * @return bool Should the processing of the entries be continued?
1894 private static function process_verbs($entrytype, $importer, &$item, &$is_like) {
1896 logger("Process verb ".$item["verb"]." and object-type ".$item["object-type"]." for entrytype ".$entrytype, LOGGER_DEBUG);
1898 if (($entrytype == DFRN_TOP_LEVEL)) {
1899 // The filling of the the "contact" variable is done for legcy reasons
1900 // The functions below are partly used by ostatus.php as well - where we have this variable
1901 $r = q("SELECT * FROM `contact` WHERE `id` = %d", intval($importer["id"]));
1903 $nickname = $contact["nick"];
1905 // Big question: Do we need these functions? They were part of the "consume_feed" function.
1906 // This function once was responsible for DFRN and OStatus.
1907 if(activity_match($item["verb"],ACTIVITY_FOLLOW)) {
1908 logger("New follower");
1909 new_follower($importer, $contact, $item, $nickname);
1912 if(activity_match($item["verb"],ACTIVITY_UNFOLLOW)) {
1913 logger("Lost follower");
1914 lose_follower($importer, $contact, $item);
1917 if(activity_match($item["verb"],ACTIVITY_REQ_FRIEND)) {
1918 logger("New friend request");
1919 new_follower($importer, $contact, $item, $nickname, true);
1922 if(activity_match($item["verb"],ACTIVITY_UNFRIEND)) {
1923 logger("Lost sharer");
1924 lose_sharer($importer, $contact, $item);
1928 if(($item["verb"] == ACTIVITY_LIKE)
1929 || ($item["verb"] == ACTIVITY_DISLIKE)
1930 || ($item["verb"] == ACTIVITY_ATTEND)
1931 || ($item["verb"] == ACTIVITY_ATTENDNO)
1932 || ($item["verb"] == ACTIVITY_ATTENDMAYBE)) {
1934 $item["type"] = "activity";
1935 $item["gravity"] = GRAVITY_LIKE;
1936 // only one like or dislike per person
1937 // splitted into two queries for performance issues
1938 $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",
1939 intval($item["uid"]),
1940 dbesc($item["author-link"]),
1941 dbesc($item["verb"]),
1942 dbesc($item["parent-uri"])
1944 if (dbm::is_result($r))
1947 $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",
1948 intval($item["uid"]),
1949 dbesc($item["author-link"]),
1950 dbesc($item["verb"]),
1951 dbesc($item["parent-uri"])
1953 if (dbm::is_result($r))
1958 if(($item["verb"] == ACTIVITY_TAG) && ($item["object-type"] == ACTIVITY_OBJ_TAGTERM)) {
1960 $xo = parse_xml_string($item["object"],false);
1961 $xt = parse_xml_string($item["target"],false);
1963 if($xt->type == ACTIVITY_OBJ_NOTE) {
1964 $r = q("SELECT `id`, `tag` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1966 intval($importer["importer_uid"])
1969 if (!dbm::is_result($r))
1972 // extract tag, if not duplicate, add to parent item
1974 if(!(stristr($r[0]["tag"],trim($xo->content)))) {
1975 q("UPDATE `item` SET `tag` = '%s' WHERE `id` = %d",
1976 dbesc($r[0]["tag"] . (strlen($r[0]["tag"]) ? ',' : '') . '#[url=' . $xo->id . ']'. $xo->content . '[/url]'),
1979 create_tags_from_item($r[0]["id"]);
1989 * @brief Processes the link elements
1991 * @param object $links link elements
1992 * @param array $item the item record
1994 private static function parse_links($links, &$item) {
2000 foreach ($links AS $link) {
2001 foreach($link->attributes AS $attributes) {
2002 if ($attributes->name == "href")
2003 $href = $attributes->textContent;
2004 if ($attributes->name == "rel")
2005 $rel = $attributes->textContent;
2006 if ($attributes->name == "type")
2007 $type = $attributes->textContent;
2008 if ($attributes->name == "length")
2009 $length = $attributes->textContent;
2010 if ($attributes->name == "title")
2011 $title = $attributes->textContent;
2013 if (($rel != "") AND ($href != ""))
2016 $item["plink"] = $href;
2020 if(strlen($item["attach"]))
2021 $item["attach"] .= ",";
2023 $item["attach"] .= '[attach]href="'.$href.'" length="'.$length.'" type="'.$type.'" title="'.$title.'"[/attach]';
2030 * @brief Processes the entry elements which contain the items and comments
2032 * @param array $header Array of the header elements that always stay the same
2033 * @param object $xpath XPath object
2034 * @param object $entry entry elements
2035 * @param array $importer Record of the importer user mixed with contact of the content
2037 private static function process_entry($header, $xpath, $entry, $importer) {
2039 logger("Processing entries");
2044 $item["uri"] = $xpath->query("atom:id/text()", $entry)->item(0)->nodeValue;
2046 $item["edited"] = $xpath->query("atom:updated/text()", $entry)->item(0)->nodeValue;
2048 $current = q("SELECT `id`, `uid`, `last-child`, `edited`, `body` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2049 dbesc($item["uri"]),
2050 intval($importer["importer_uid"])
2053 // Is there an existing item?
2054 if (dbm::is_result($current) AND edited_timestamp_is_newer($current[0], $item) AND
2055 (datetime_convert("UTC","UTC",$item["edited"]) < $current[0]["edited"])) {
2056 logger("Item ".$item["uri"]." already existed.", LOGGER_DEBUG);
2061 $owner = self::fetchauthor($xpath, $entry, $importer, "dfrn:owner", true);
2063 $item["owner-name"] = $owner["name"];
2064 $item["owner-link"] = $owner["link"];
2065 $item["owner-avatar"] = $owner["avatar"];
2068 $author = self::fetchauthor($xpath, $entry, $importer, "atom:author", true);
2070 $item["author-name"] = $author["name"];
2071 $item["author-link"] = $author["link"];
2072 $item["author-avatar"] = $author["avatar"];
2074 $item["title"] = $xpath->query("atom:title/text()", $entry)->item(0)->nodeValue;
2076 $item["created"] = $xpath->query("atom:published/text()", $entry)->item(0)->nodeValue;
2078 $item["body"] = $xpath->query("dfrn:env/text()", $entry)->item(0)->nodeValue;
2079 $item["body"] = str_replace(array(' ',"\t","\r","\n"), array('','','',''),$item["body"]);
2080 // make sure nobody is trying to sneak some html tags by us
2081 $item["body"] = notags(base64url_decode($item["body"]));
2083 $item["body"] = limit_body_size($item["body"]);
2085 /// @todo Do we really need this check for HTML elements? (It was copied from the old function)
2086 if((strpos($item['body'],'<') !== false) && (strpos($item['body'],'>') !== false)) {
2088 $item['body'] = reltoabs($item['body'],$base_url);
2090 $item['body'] = html2bb_video($item['body']);
2092 $item['body'] = oembed_html2bbcode($item['body']);
2094 $config = HTMLPurifier_Config::createDefault();
2095 $config->set('Cache.DefinitionImpl', null);
2097 // we shouldn't need a whitelist, because the bbcode converter
2098 // will strip out any unsupported tags.
2100 $purifier = new HTMLPurifier($config);
2101 $item['body'] = $purifier->purify($item['body']);
2103 $item['body'] = @html2bbcode($item['body']);
2106 /// @todo We should check for a repeated post and if we know the repeated author.
2108 // We don't need the content element since "dfrn:env" is always present
2109 //$item["body"] = $xpath->query("atom:content/text()", $entry)->item(0)->nodeValue;
2111 $item["last-child"] = $xpath->query("dfrn:comment-allow/text()", $entry)->item(0)->nodeValue;
2112 $item["location"] = $xpath->query("dfrn:location/text()", $entry)->item(0)->nodeValue;
2114 $georsspoint = $xpath->query("georss:point", $entry);
2116 $item["coord"] = $georsspoint->item(0)->nodeValue;
2118 $item["private"] = $xpath->query("dfrn:private/text()", $entry)->item(0)->nodeValue;
2120 $item["extid"] = $xpath->query("dfrn:extid/text()", $entry)->item(0)->nodeValue;
2122 if ($xpath->query("dfrn:bookmark/text()", $entry)->item(0)->nodeValue == "true")
2123 $item["bookmark"] = true;
2125 $notice_info = $xpath->query("statusnet:notice_info", $entry);
2126 if ($notice_info AND ($notice_info->length > 0)) {
2127 foreach($notice_info->item(0)->attributes AS $attributes) {
2128 if ($attributes->name == "source")
2129 $item["app"] = strip_tags($attributes->textContent);
2133 $item["guid"] = $xpath->query("dfrn:diaspora_guid/text()", $entry)->item(0)->nodeValue;
2135 // We store the data from "dfrn:diaspora_signature" in a different table, this is done in "item_store"
2136 $dsprsig = unxmlify($xpath->query("dfrn:diaspora_signature/text()", $entry)->item(0)->nodeValue);
2138 $item["dsprsig"] = $dsprsig;
2140 $item["verb"] = $xpath->query("activity:verb/text()", $entry)->item(0)->nodeValue;
2142 if ($xpath->query("activity:object-type/text()", $entry)->item(0)->nodeValue != "")
2143 $item["object-type"] = $xpath->query("activity:object-type/text()", $entry)->item(0)->nodeValue;
2145 $object = $xpath->query("activity:object", $entry)->item(0);
2146 $item["object"] = self::transform_activity($xpath, $object, "object");
2148 if (trim($item["object"]) != "") {
2149 $r = parse_xml_string($item["object"], false);
2150 if (isset($r->type))
2151 $item["object-type"] = $r->type;
2154 $target = $xpath->query("activity:target", $entry)->item(0);
2155 $item["target"] = self::transform_activity($xpath, $target, "target");
2157 $categories = $xpath->query("atom:category", $entry);
2159 foreach ($categories AS $category) {
2162 foreach($category->attributes AS $attributes) {
2163 if ($attributes->name == "term")
2164 $term = $attributes->textContent;
2166 if ($attributes->name == "scheme")
2167 $scheme = $attributes->textContent;
2170 if (($term != "") AND ($scheme != "")) {
2171 $parts = explode(":", $scheme);
2172 if ((count($parts) >= 4) AND (array_shift($parts) == "X-DFRN")) {
2173 $termhash = array_shift($parts);
2174 $termurl = implode(":", $parts);
2176 if(strlen($item["tag"]))
2177 $item["tag"] .= ",";
2179 $item["tag"] .= $termhash."[url=".$termurl."]".$term."[/url]";
2187 $links = $xpath->query("atom:link", $entry);
2189 self::parse_links($links, $item);
2191 // Is it a reply or a top level posting?
2192 $item["parent-uri"] = $item["uri"];
2194 $inreplyto = $xpath->query("thr:in-reply-to", $entry);
2195 if (is_object($inreplyto->item(0)))
2196 foreach($inreplyto->item(0)->attributes AS $attributes)
2197 if ($attributes->name == "ref")
2198 $item["parent-uri"] = $attributes->textContent;
2200 // Get the type of the item (Top level post, reply or remote reply)
2201 $entrytype = self::get_entry_type($importer, $item);
2203 // Now assign the rest of the values that depend on the type of the message
2204 if (in_array($entrytype, array(DFRN_REPLY, DFRN_REPLY_RC))) {
2205 if (!isset($item["object-type"]))
2206 $item["object-type"] = ACTIVITY_OBJ_COMMENT;
2208 if ($item["contact-id"] != $owner["contact-id"])
2209 $item["contact-id"] = $owner["contact-id"];
2211 if (($item["network"] != $owner["network"]) AND ($owner["network"] != ""))
2212 $item["network"] = $owner["network"];
2214 if ($item["contact-id"] != $author["contact-id"])
2215 $item["contact-id"] = $author["contact-id"];
2217 if (($item["network"] != $author["network"]) AND ($author["network"] != ""))
2218 $item["network"] = $author["network"];
2220 // This code was taken from the old DFRN code
2221 // When activated, forums don't work.
2222 // And: Why should we disallow commenting by followers?
2223 // the behaviour is now similar to the Diaspora part.
2224 //if($importer["rel"] == CONTACT_IS_FOLLOWER) {
2225 // logger("Contact ".$importer["id"]." is only follower. Quitting", LOGGER_DEBUG);
2230 if ($entrytype == DFRN_REPLY_RC) {
2231 $item["type"] = "remote-comment";
2233 } elseif ($entrytype == DFRN_TOP_LEVEL) {
2234 if (!isset($item["object-type"]))
2235 $item["object-type"] = ACTIVITY_OBJ_NOTE;
2238 if ($item["object-type"] == ACTIVITY_OBJ_EVENT) {
2239 logger("Item ".$item["uri"]." seems to contain an event.", LOGGER_DEBUG);
2240 $ev = bbtoevent($item["body"]);
2241 if((x($ev, "desc") || x($ev, "summary")) && x($ev, "start")) {
2242 logger("Event in item ".$item["uri"]." was found.", LOGGER_DEBUG);
2243 $ev["cid"] = $importer["id"];
2244 $ev["uid"] = $importer["uid"];
2245 $ev["uri"] = $item["uri"];
2246 $ev["edited"] = $item["edited"];
2247 $ev['private'] = $item['private'];
2248 $ev["guid"] = $item["guid"];
2250 $r = q("SELECT `id` FROM `event` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2251 dbesc($item["uri"]),
2252 intval($importer["uid"])
2254 if (dbm::is_result($r))
2255 $ev["id"] = $r[0]["id"];
2257 $event_id = event_store($ev);
2258 logger("Event ".$event_id." was stored", LOGGER_DEBUG);
2264 if (!self::process_verbs($entrytype, $importer, $item, $is_like)) {
2265 logger("Exiting because 'process_verbs' told us so", LOGGER_DEBUG);
2269 // Update content if 'updated' changes
2270 if (dbm::is_result($current)) {
2271 if (self::update_content($r[0], $item, $importer, $entrytype))
2272 logger("Item ".$item["uri"]." was updated.", LOGGER_DEBUG);
2274 logger("Item ".$item["uri"]." already existed.", LOGGER_DEBUG);
2278 if (in_array($entrytype, array(DFRN_REPLY, DFRN_REPLY_RC))) {
2279 $posted_id = item_store($item);
2284 logger("Reply from contact ".$item["contact-id"]." was stored with id ".$posted_id, LOGGER_DEBUG);
2286 $item["id"] = $posted_id;
2288 $r = q("SELECT `parent`, `parent-uri` FROM `item` WHERE `id` = %d AND `uid` = %d LIMIT 1",
2290 intval($importer["importer_uid"])
2292 if (dbm::is_result($r)) {
2293 $parent = $r[0]["parent"];
2294 $parent_uri = $r[0]["parent-uri"];
2298 $r1 = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `uid` = %d AND `parent` = %d",
2299 dbesc(datetime_convert()),
2300 intval($importer["importer_uid"]),
2301 intval($r[0]["parent"])
2304 $r2 = q("UPDATE `item` SET `last-child` = 1, `changed` = '%s' WHERE `uid` = %d AND `id` = %d",
2305 dbesc(datetime_convert()),
2306 intval($importer["importer_uid"]),
2311 if($posted_id AND $parent AND ($entrytype == DFRN_REPLY_RC)) {
2312 logger("Notifying followers about comment ".$posted_id, LOGGER_DEBUG);
2313 proc_run(PRIORITY_HIGH, "include/notifier.php", "comment-import", $posted_id);
2318 } else { // $entrytype == DFRN_TOP_LEVEL
2319 if(!link_compare($item["owner-link"],$importer["url"])) {
2320 // The item owner info is not our contact. It's OK and is to be expected if this is a tgroup delivery,
2321 // but otherwise there's a possible data mixup on the sender's system.
2322 // the tgroup delivery code called from item_store will correct it if it's a forum,
2323 // but we're going to unconditionally correct it here so that the post will always be owned by our contact.
2324 logger('Correcting item owner.', LOGGER_DEBUG);
2325 $item["owner-name"] = $importer["senderName"];
2326 $item["owner-link"] = $importer["url"];
2327 $item["owner-avatar"] = $importer["thumb"];
2330 if(($importer["rel"] == CONTACT_IS_FOLLOWER) && (!tgroup_check($importer["importer_uid"], $item))) {
2331 logger("Contact ".$importer["id"]." is only follower and tgroup check was negative.", LOGGER_DEBUG);
2335 // This is my contact on another system, but it's really me.
2336 // Turn this into a wall post.
2337 $notify = item_is_remote_self($importer, $item);
2339 $posted_id = item_store($item, false, $notify);
2341 logger("Item was stored with id ".$posted_id, LOGGER_DEBUG);
2343 if(stristr($item["verb"],ACTIVITY_POKE))
2344 self::do_poke($item, $importer, $posted_id);
2349 * @brief Deletes items
2351 * @param object $xpath XPath object
2352 * @param object $deletion deletion elements
2353 * @param array $importer Record of the importer user mixed with contact of the content
2355 private static function process_deletion($xpath, $deletion, $importer) {
2357 logger("Processing deletions");
2359 foreach($deletion->attributes AS $attributes) {
2360 if ($attributes->name == "ref")
2361 $uri = $attributes->textContent;
2362 if ($attributes->name == "when")
2363 $when = $attributes->textContent;
2366 $when = datetime_convert("UTC", "UTC", $when, "Y-m-d H:i:s");
2368 $when = datetime_convert("UTC", "UTC", "now", "Y-m-d H:i:s");
2370 if (!$uri OR !$importer["id"])
2373 /// @todo Only select the used fields
2374 $r = q("SELECT `item`.*, `contact`.`self` FROM `item` INNER JOIN `contact` on `item`.`contact-id` = `contact`.`id`
2375 WHERE `uri` = '%s' AND `item`.`uid` = %d AND `contact-id` = %d AND NOT `item`.`file` LIKE '%%[%%' LIMIT 1",
2377 intval($importer["uid"]),
2378 intval($importer["id"])
2380 if (!dbm::is_result($r)) {
2381 logger("Item with uri ".$uri." from contact ".$importer["id"]." for user ".$importer["uid"]." wasn't found.", LOGGER_DEBUG);
2387 $entrytype = self::get_entry_type($importer, $item);
2389 if(!$item["deleted"])
2390 logger('deleting item '.$item["id"].' uri='.$uri, LOGGER_DEBUG);
2394 if($item["object-type"] == ACTIVITY_OBJ_EVENT) {
2395 logger("Deleting event ".$item["event-id"], LOGGER_DEBUG);
2396 event_delete($item["event-id"]);
2399 if(($item["verb"] == ACTIVITY_TAG) && ($item["object-type"] == ACTIVITY_OBJ_TAGTERM)) {
2401 $xo = parse_xml_string($item["object"],false);
2402 $xt = parse_xml_string($item["target"],false);
2404 if($xt->type == ACTIVITY_OBJ_NOTE) {
2405 $i = q("SELECT `id`, `contact-id`, `tag` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2407 intval($importer["importer_uid"])
2409 if (dbm::is_result($i)) {
2411 // For tags, the owner cannot remove the tag on the author's copy of the post.
2413 $owner_remove = (($item["contact-id"] == $i[0]["contact-id"]) ? true: false);
2414 $author_remove = (($item["origin"] && $item["self"]) ? true : false);
2415 $author_copy = (($item["origin"]) ? true : false);
2417 if($owner_remove && $author_copy)
2419 if($author_remove || $owner_remove) {
2420 $tags = explode(',',$i[0]["tag"]);
2423 foreach($tags as $tag)
2424 if(trim($tag) !== trim($xo->body))
2425 $newtags[] = trim($tag);
2427 q("UPDATE `item` SET `tag` = '%s' WHERE `id` = %d",
2428 dbesc(implode(',',$newtags)),
2431 create_tags_from_item($i[0]["id"]);
2437 if($entrytype == DFRN_TOP_LEVEL) {
2438 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s',
2439 `body` = '', `title` = ''
2440 WHERE `parent-uri` = '%s' AND `uid` = %d",
2442 dbesc(datetime_convert()),
2444 intval($importer["uid"])
2446 create_tags_from_itemuri($uri, $importer["uid"]);
2447 create_files_from_itemuri($uri, $importer["uid"]);
2448 update_thread_uri($uri, $importer["uid"]);
2450 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s',
2451 `body` = '', `title` = ''
2452 WHERE `uri` = '%s' AND `uid` = %d",
2454 dbesc(datetime_convert()),
2456 intval($importer["uid"])
2458 create_tags_from_itemuri($uri, $importer["uid"]);
2459 create_files_from_itemuri($uri, $importer["uid"]);
2460 update_thread_uri($uri, $importer["importer_uid"]);
2461 if($item["last-child"]) {
2462 // ensure that last-child is set in case the comment that had it just got wiped.
2463 q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d ",
2464 dbesc(datetime_convert()),
2465 dbesc($item["parent-uri"]),
2466 intval($item["uid"])
2468 // who is the last child now?
2469 $r = q("SELECT `id` FROM `item` WHERE `parent-uri` = '%s' AND `type` != 'activity' AND `deleted` = 0 AND `moderated` = 0 AND `uid` = %d
2470 ORDER BY `created` DESC LIMIT 1",
2471 dbesc($item["parent-uri"]),
2472 intval($importer["uid"])
2474 if (dbm::is_result($r)) {
2475 q("UPDATE `item` SET `last-child` = 1 WHERE `id` = %d",
2480 // if this is a relayed delete, propagate it to other recipients
2482 if($entrytype == DFRN_REPLY_RC) {
2483 logger("Notifying followers about deletion of post ".$item["id"], LOGGER_DEBUG);
2484 proc_run(PRIORITY_HIGH, "include/notifier.php","drop", $item["id"]);
2491 * @brief Imports a DFRN message
2493 * @param text $xml The DFRN message
2494 * @param array $importer Record of the importer user mixed with contact of the content
2495 * @param bool $sort_by_date Is used when feeds are polled
2497 public static function import($xml,$importer, $sort_by_date = false) {
2502 if($importer["readonly"]) {
2503 // We aren't receiving stuff from this person. But we will quietly ignore them
2504 // rather than a blatant "go away" message.
2505 logger('ignoring contact '.$importer["id"]);
2509 $doc = new DOMDocument();
2510 @$doc->loadXML($xml);
2512 $xpath = new DomXPath($doc);
2513 $xpath->registerNamespace("atom", NAMESPACE_ATOM1);
2514 $xpath->registerNamespace("thr", NAMESPACE_THREAD);
2515 $xpath->registerNamespace("at", NAMESPACE_TOMB);
2516 $xpath->registerNamespace("media", NAMESPACE_MEDIA);
2517 $xpath->registerNamespace("dfrn", NAMESPACE_DFRN);
2518 $xpath->registerNamespace("activity", NAMESPACE_ACTIVITY);
2519 $xpath->registerNamespace("georss", NAMESPACE_GEORSS);
2520 $xpath->registerNamespace("poco", NAMESPACE_POCO);
2521 $xpath->registerNamespace("ostatus", NAMESPACE_OSTATUS);
2522 $xpath->registerNamespace("statusnet", NAMESPACE_STATUSNET);
2525 $header["uid"] = $importer["uid"];
2526 $header["network"] = NETWORK_DFRN;
2527 $header["type"] = "remote";
2528 $header["wall"] = 0;
2529 $header["origin"] = 0;
2530 $header["contact-id"] = $importer["id"];
2532 // Update the contact table if the data has changed
2534 // The "atom:author" is only present in feeds
2535 if ($xpath->query("/atom:feed/atom:author")->length > 0)
2536 self::fetchauthor($xpath, $doc->firstChild, $importer, "atom:author", false, $xml);
2538 // Only the "dfrn:owner" in the head section contains all data
2539 if ($xpath->query("/atom:feed/dfrn:owner")->length > 0)
2540 self::fetchauthor($xpath, $doc->firstChild, $importer, "dfrn:owner", false, $xml);
2542 logger("Import DFRN message for user ".$importer["uid"]." from contact ".$importer["id"], LOGGER_DEBUG);
2544 // The account type is new since 3.5.1
2545 if ($xpath->query("/atom:feed/dfrn:account_type")->length > 0) {
2546 $accounttype = intval($xpath->evaluate("/atom:feed/dfrn:account_type/text()", $context)->item(0)->nodeValue);
2548 if ($accounttype != $importer["contact-type"])
2549 q("UPDATE `contact` SET `contact-type` = %d WHERE `id` = %d",
2550 intval($accounttype),
2551 intval($importer["id"])
2555 // is it a public forum? Private forums aren't supported with this method
2556 // This is deprecated since 3.5.1
2557 $forum = intval($xpath->evaluate("/atom:feed/dfrn:community/text()", $context)->item(0)->nodeValue);
2559 if ($forum != $importer["forum"])
2560 q("UPDATE `contact` SET `forum` = %d WHERE `forum` != %d AND `id` = %d",
2561 intval($forum), intval($forum),
2562 intval($importer["id"])
2565 $mails = $xpath->query("/atom:feed/dfrn:mail");
2566 foreach ($mails AS $mail)
2567 self::process_mail($xpath, $mail, $importer);
2569 $suggestions = $xpath->query("/atom:feed/dfrn:suggest");
2570 foreach ($suggestions AS $suggestion)
2571 self::process_suggestion($xpath, $suggestion, $importer);
2573 $relocations = $xpath->query("/atom:feed/dfrn:relocate");
2574 foreach ($relocations AS $relocation)
2575 self::process_relocation($xpath, $relocation, $importer);
2577 $deletions = $xpath->query("/atom:feed/at:deleted-entry");
2578 foreach ($deletions AS $deletion)
2579 self::process_deletion($xpath, $deletion, $importer);
2581 if (!$sort_by_date) {
2582 $entries = $xpath->query("/atom:feed/atom:entry");
2583 foreach ($entries AS $entry)
2584 self::process_entry($header, $xpath, $entry, $importer);
2586 $newentries = array();
2587 $entries = $xpath->query("/atom:feed/atom:entry");
2588 foreach ($entries AS $entry) {
2589 $created = $xpath->query("atom:published/text()", $entry)->item(0)->nodeValue;
2590 $newentries[strtotime($created)] = $entry;
2593 // Now sort after the publishing date
2596 foreach ($newentries AS $entry)
2597 self::process_entry($header, $xpath, $entry, $importer);
2599 logger("Import done for user ".$importer["uid"]." from contact ".$importer["id"], LOGGER_DEBUG);