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
44 * @todo Add type-hints
46 public static function entries($items,$owner) {
48 $doc = new DOMDocument('1.0', 'utf-8');
49 $doc->formatOutput = true;
51 $root = self::add_header($doc, $owner, "dfrn:owner", "", false);
53 if (! count($items)) {
54 return trim($doc->saveXML());
57 foreach ($items as $item) {
58 $entry = self::entry($doc, "text", $item, $owner, $item["entry:comment-allow"], $item["entry:cid"]);
59 $root->appendChild($entry);
62 return(trim($doc->saveXML()));
66 * @brief Generate an atom feed for the given user
68 * This function is called when another server is pulling data from the user feed.
70 * @param string $dfrn_id DFRN ID from the requesting party
71 * @param string $owner_nick Owner nick name
72 * @param string $last_update Date of the last update
73 * @param int $direction Can be -1, 0 or 1.
74 * @param boolean $onlyheader Output only the header without content? (Default is "no")
76 * @return string DFRN feed entries
78 public static function feed($dfrn_id, $owner_nick, $last_update, $direction = 0, $onlyheader = false) {
82 $sitefeed = ((strlen($owner_nick)) ? false : true); // not yet implemented, need to rewrite huge chunks of following logic
83 $public_feed = (($dfrn_id) ? false : true);
84 $starred = false; // not yet implemented, possible security issues
87 if ($public_feed && $a->argc > 2) {
88 for ($x = 2; $x < $a->argc; $x++) {
89 if ($a->argv[$x] == 'converse') {
92 if ($a->argv[$x] == 'starred') {
95 if ($a->argv[$x] == 'category' && $a->argc > ($x + 1) && strlen($a->argv[$x+1])) {
96 $category = $a->argv[$x+1];
103 // default permissions - anonymous user
105 $sql_extra = " AND `item`.`allow_cid` = '' AND `item`.`allow_gid` = '' AND `item`.`deny_cid` = '' AND `item`.`deny_gid` = '' ";
107 $r = q("SELECT `contact`.*, `user`.`nickname`, `user`.`timezone`, `user`.`page-flags`, `user`.`account-type`
108 FROM `contact` INNER JOIN `user` ON `user`.`uid` = `contact`.`uid`
109 WHERE `contact`.`self` AND `user`.`nickname` = '%s' LIMIT 1",
113 if (! dbm::is_result($r)) {
118 $owner_id = $owner['uid'];
119 $owner_nick = $owner['nickname'];
121 $sql_post_table = "";
123 if (! $public_feed) {
128 $sql_extra = sprintf(" AND `issued-id` = '%s' ", dbesc($dfrn_id));
132 $sql_extra = sprintf(" AND `issued-id` = '%s' AND `duplex` = 1 ", dbesc($dfrn_id));
133 $my_id = '1:' . $dfrn_id;
136 $sql_extra = sprintf(" AND `dfrn-id` = '%s' AND `duplex` = 1 ", dbesc($dfrn_id));
137 $my_id = '0:' . $dfrn_id;
144 $r = q("SELECT * FROM `contact` WHERE NOT `blocked` AND `contact`.`uid` = %d $sql_extra LIMIT 1",
148 if (! dbm::is_result($r)) {
153 require_once('include/security.php');
154 $groups = init_groups_visitor($contact['id']);
156 if (count($groups)) {
157 for ($x = 0; $x < count($groups); $x ++)
158 $groups[$x] = '<' . intval($groups[$x]) . '>' ;
159 $gs = implode('|', $groups);
161 $gs = '<<>>' ; // Impossible to match
164 $sql_extra = sprintf("
165 AND ( `allow_cid` = '' OR `allow_cid` REGEXP '<%d>' )
166 AND ( `deny_cid` = '' OR NOT `deny_cid` REGEXP '<%d>' )
167 AND ( `allow_gid` = '' OR `allow_gid` REGEXP '%s' )
168 AND ( `deny_gid` = '' OR NOT `deny_gid` REGEXP '%s')
170 intval($contact['id']),
171 intval($contact['id']),
183 if (! strlen($last_update)) {
184 $last_update = 'now -30 days';
187 if (isset($category)) {
188 $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` ",
189 dbesc(protect_sprintf($category)), intval(TERM_OBJ_POST), intval(TERM_CATEGORY), intval($owner_id));
190 //$sql_extra .= file_tag_file_query('item',$category,'category');
195 $sql_extra .= " AND `contact`.`self` = 1 ";
199 $check_date = datetime_convert('UTC','UTC',$last_update,'Y-m-d H:i:s');
201 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`,
202 `contact`.`name`, `contact`.`network`, `contact`.`photo`, `contact`.`url`,
203 `contact`.`name-date`, `contact`.`uri-date`, `contact`.`avatar-date`,
204 `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
205 `sign`.`signed_text`, `sign`.`signature`, `sign`.`signer`
206 FROM `item` USE INDEX (`uid_wall_changed`) $sql_post_table
207 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
208 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
209 LEFT JOIN `sign` ON `sign`.`iid` = `item`.`id`
210 WHERE `item`.`uid` = %d AND `item`.`visible` AND NOT `item`.`moderated` AND `item`.`parent` != 0
211 AND `item`.`wall` AND `item`.`changed` > '%s'
213 ORDER BY `item`.`parent` ".$sort.", `item`.`created` ASC LIMIT 0, 300",
220 * Will check further below if this actually returned results.
221 * We will provide an empty feed if that is the case.
226 $doc = new DOMDocument('1.0', 'utf-8');
227 $doc->formatOutput = true;
229 $alternatelink = $owner['url'];
231 if (isset($category)) {
232 $alternatelink .= "/category/".$category;
236 $author = "dfrn:owner";
241 $root = self::add_header($doc, $owner, $author, $alternatelink, true);
243 /// @TODO This hook can't work anymore
244 // call_hooks('atom_feed', $atom);
246 if (!dbm::is_result($items) OR $onlyheader) {
247 $atom = trim($doc->saveXML());
249 call_hooks('atom_feed_end', $atom);
254 foreach ($items as $item) {
256 // prevent private email from leaking.
257 if ($item['network'] == NETWORK_MAIL) {
261 // public feeds get html, our own nodes use bbcode
265 // catch any email that's in a public conversation and make sure it doesn't leak
266 if ($item['private']) {
273 $entry = self::entry($doc, $type, $item, $owner, true);
274 $root->appendChild($entry);
278 $atom = trim($doc->saveXML());
280 call_hooks('atom_feed_end', $atom);
286 * @brief Create XML text for DFRN mails
288 * @param array $item message elements
289 * @param array $owner Owner record
291 * @return string DFRN mail
292 * @todo Add type-hints
294 public static function mail($item, $owner) {
295 $doc = new DOMDocument('1.0', 'utf-8');
296 $doc->formatOutput = true;
298 $root = self::add_header($doc, $owner, "dfrn:owner", "", false);
300 $mail = $doc->createElement("dfrn:mail");
301 $sender = $doc->createElement("dfrn:sender");
303 xml::add_element($doc, $sender, "dfrn:name", $owner['name']);
304 xml::add_element($doc, $sender, "dfrn:uri", $owner['url']);
305 xml::add_element($doc, $sender, "dfrn:avatar", $owner['thumb']);
307 $mail->appendChild($sender);
309 xml::add_element($doc, $mail, "dfrn:id", $item['uri']);
310 xml::add_element($doc, $mail, "dfrn:in-reply-to", $item['parent-uri']);
311 xml::add_element($doc, $mail, "dfrn:sentdate", datetime_convert('UTC', 'UTC', $item['created'] . '+00:00' , ATOM_TIME));
312 xml::add_element($doc, $mail, "dfrn:subject", $item['title']);
313 xml::add_element($doc, $mail, "dfrn:content", $item['body']);
315 $root->appendChild($mail);
317 return(trim($doc->saveXML()));
321 * @brief Create XML text for DFRN friend suggestions
323 * @param array $item suggestion elements
324 * @param array $owner Owner record
326 * @return string DFRN suggestions
327 * @todo Add type-hints
329 public static function fsuggest($item, $owner) {
330 $doc = new DOMDocument('1.0', 'utf-8');
331 $doc->formatOutput = true;
333 $root = self::add_header($doc, $owner, "dfrn:owner", "", false);
335 $suggest = $doc->createElement("dfrn:suggest");
337 xml::add_element($doc, $suggest, "dfrn:url", $item['url']);
338 xml::add_element($doc, $suggest, "dfrn:name", $item['name']);
339 xml::add_element($doc, $suggest, "dfrn:photo", $item['photo']);
340 xml::add_element($doc, $suggest, "dfrn:request", $item['request']);
341 xml::add_element($doc, $suggest, "dfrn:note", $item['note']);
343 $root->appendChild($suggest);
345 return(trim($doc->saveXML()));
349 * @brief Create XML text for DFRN relocations
351 * @param array $owner Owner record
352 * @param int $uid User ID
354 * @return string DFRN relocations
355 * @todo Add type-hints
357 public static function relocate($owner, $uid) {
359 /* get site pubkey. this could be a new installation with no site keys*/
360 $pubkey = get_config('system','site_pubkey');
362 $res = new_keypair(1024);
363 set_config('system','site_prvkey', $res['prvkey']);
364 set_config('system','site_pubkey', $res['pubkey']);
367 $rp = q("SELECT `resource-id` , `scale`, type FROM `photo`
368 WHERE `profile` = 1 AND `uid` = %d ORDER BY scale;", $uid);
370 $ext = Photo::supportedTypes();
372 foreach ($rp as $p) {
373 $photos[$p['scale']] = app::get_baseurl().'/photo/'.$p['resource-id'].'-'.$p['scale'].'.'.$ext[$p['type']];
378 $doc = new DOMDocument('1.0', 'utf-8');
379 $doc->formatOutput = true;
381 $root = self::add_header($doc, $owner, "dfrn:owner", "", false);
383 $relocate = $doc->createElement("dfrn:relocate");
385 xml::add_element($doc, $relocate, "dfrn:url", $owner['url']);
386 xml::add_element($doc, $relocate, "dfrn:name", $owner['name']);
387 xml::add_element($doc, $relocate, "dfrn:addr", $owner['addr']);
388 xml::add_element($doc, $relocate, "dfrn:avatar", $owner['avatar']);
389 xml::add_element($doc, $relocate, "dfrn:photo", $photos[4]);
390 xml::add_element($doc, $relocate, "dfrn:thumb", $photos[5]);
391 xml::add_element($doc, $relocate, "dfrn:micro", $photos[6]);
392 xml::add_element($doc, $relocate, "dfrn:request", $owner['request']);
393 xml::add_element($doc, $relocate, "dfrn:confirm", $owner['confirm']);
394 xml::add_element($doc, $relocate, "dfrn:notify", $owner['notify']);
395 xml::add_element($doc, $relocate, "dfrn:poll", $owner['poll']);
396 xml::add_element($doc, $relocate, "dfrn:sitepubkey", get_config('system','site_pubkey'));
398 $root->appendChild($relocate);
400 return(trim($doc->saveXML()));
404 * @brief Adds the header elements for the DFRN protocol
406 * @param object $doc XML document
407 * @param array $owner Owner record
408 * @param string $authorelement Element name for the author
409 * @param string $alternatelink link to profile or category
410 * @param bool $public Is it a header for public posts?
412 * @return object XML root object
413 * @todo Add type-hints
415 private static function add_header($doc, $owner, $authorelement, $alternatelink = "", $public = false) {
417 if ($alternatelink == "") {
418 $alternatelink = $owner['url'];
421 $root = $doc->createElementNS(NAMESPACE_ATOM1, 'feed');
422 $doc->appendChild($root);
424 $root->setAttribute("xmlns:thr", NAMESPACE_THREAD);
425 $root->setAttribute("xmlns:at", NAMESPACE_TOMB);
426 $root->setAttribute("xmlns:media", NAMESPACE_MEDIA);
427 $root->setAttribute("xmlns:dfrn", NAMESPACE_DFRN);
428 $root->setAttribute("xmlns:activity", NAMESPACE_ACTIVITY);
429 $root->setAttribute("xmlns:georss", NAMESPACE_GEORSS);
430 $root->setAttribute("xmlns:poco", NAMESPACE_POCO);
431 $root->setAttribute("xmlns:ostatus", NAMESPACE_OSTATUS);
432 $root->setAttribute("xmlns:statusnet", NAMESPACE_STATUSNET);
434 xml::add_element($doc, $root, "id", app::get_baseurl()."/profile/".$owner["nick"]);
435 xml::add_element($doc, $root, "title", $owner["name"]);
437 $attributes = array("uri" => "https://friendi.ca", "version" => FRIENDICA_VERSION."-".DB_UPDATE_VERSION);
438 xml::add_element($doc, $root, "generator", FRIENDICA_PLATFORM, $attributes);
440 $attributes = array("rel" => "license", "href" => "http://creativecommons.org/licenses/by/3.0/");
441 xml::add_element($doc, $root, "link", "", $attributes);
443 $attributes = array("rel" => "alternate", "type" => "text/html", "href" => $alternatelink);
444 xml::add_element($doc, $root, "link", "", $attributes);
448 // DFRN itself doesn't uses this. But maybe someone else wants to subscribe to the public feed.
449 ostatus::hublinks($doc, $root);
451 $attributes = array("rel" => "salmon", "href" => app::get_baseurl()."/salmon/".$owner["nick"]);
452 xml::add_element($doc, $root, "link", "", $attributes);
454 $attributes = array("rel" => "http://salmon-protocol.org/ns/salmon-replies", "href" => app::get_baseurl()."/salmon/".$owner["nick"]);
455 xml::add_element($doc, $root, "link", "", $attributes);
457 $attributes = array("rel" => "http://salmon-protocol.org/ns/salmon-mention", "href" => app::get_baseurl()."/salmon/".$owner["nick"]);
458 xml::add_element($doc, $root, "link", "", $attributes);
461 // For backward compatibility we keep this element
462 if ($owner['page-flags'] == PAGE_COMMUNITY) {
463 xml::add_element($doc, $root, "dfrn:community", 1);
466 // The former element is replaced by this one
467 xml::add_element($doc, $root, "dfrn:account_type", $owner["account-type"]);
469 /// @todo We need a way to transmit the different page flags like "PAGE_PRVGROUP"
471 xml::add_element($doc, $root, "updated", datetime_convert("UTC", "UTC", "now", ATOM_TIME));
473 $author = self::add_author($doc, $owner, $authorelement, $public);
474 $root->appendChild($author);
480 * @brief Adds the author element in the header for the DFRN protocol
482 * @param object $doc XML document
483 * @param array $owner Owner record
484 * @param string $authorelement Element name for the author
486 * @return object XML author object
487 * @todo Add type-hints
489 private static function add_author($doc, $owner, $authorelement, $public) {
491 // Is the profile hidden or shouldn't be published in the net? Then add the "hide" element
492 $r = q("SELECT `id` FROM `profile` INNER JOIN `user` ON `user`.`uid` = `profile`.`uid`
493 WHERE (`hidewall` OR NOT `net-publish`) AND `user`.`uid` = %d",
494 intval($owner['uid']));
495 if (dbm::is_result($r)) {
501 $author = $doc->createElement($authorelement);
503 $namdate = datetime_convert('UTC', 'UTC', $owner['name-date'].'+00:00', ATOM_TIME);
504 $uridate = datetime_convert('UTC', 'UTC', $owner['uri-date'].'+00:00', ATOM_TIME);
505 $picdate = datetime_convert('UTC', 'UTC', $owner['avatar-date'].'+00:00', ATOM_TIME);
507 $attributes = array();
509 if (!$public OR !$hidewall) {
510 $attributes = array("dfrn:updated" => $namdate);
513 xml::add_element($doc, $author, "name", $owner["name"], $attributes);
514 xml::add_element($doc, $author, "uri", app::get_baseurl().'/profile/'.$owner["nickname"], $attributes);
515 xml::add_element($doc, $author, "dfrn:handle", $owner["addr"], $attributes);
517 $attributes = array("rel" => "photo", "type" => "image/jpeg",
518 "media:width" => 175, "media:height" => 175, "href" => $owner['photo']);
520 if (!$public OR !$hidewall) {
521 $attributes["dfrn:updated"] = $picdate;
524 xml::add_element($doc, $author, "link", "", $attributes);
526 $attributes["rel"] = "avatar";
527 xml::add_element($doc, $author, "link", "", $attributes);
530 xml::add_element($doc, $author, "dfrn:hide", "true");
533 // The following fields will only be generated if the data isn't meant for a public feed
538 $birthday = feed_birthday($owner['uid'], $owner['timezone']);
541 xml::add_element($doc, $author, "dfrn:birthday", $birthday);
543 // Only show contact details when we are allowed to
544 $r = q("SELECT `profile`.`about`, `profile`.`name`, `profile`.`homepage`, `user`.`nickname`,
545 `user`.`timezone`, `profile`.`locality`, `profile`.`region`, `profile`.`country-name`,
546 `profile`.`pub_keywords`, `profile`.`xmpp`, `profile`.`dob`
548 INNER JOIN `user` ON `user`.`uid` = `profile`.`uid`
549 WHERE `profile`.`is-default` AND NOT `user`.`hidewall` AND `user`.`uid` = %d",
550 intval($owner['uid']));
551 if (dbm::is_result($r)) {
554 xml::add_element($doc, $author, "poco:displayName", $profile["name"]);
555 xml::add_element($doc, $author, "poco:updated", $namdate);
557 if (trim($profile["dob"]) > '0001-01-01') {
558 xml::add_element($doc, $author, "poco:birthday", "0000-".date("m-d", strtotime($profile["dob"])));
561 xml::add_element($doc, $author, "poco:note", $profile["about"]);
562 xml::add_element($doc, $author, "poco:preferredUsername", $profile["nickname"]);
564 $savetz = date_default_timezone_get();
565 date_default_timezone_set($profile["timezone"]);
566 xml::add_element($doc, $author, "poco:utcOffset", date("P"));
567 date_default_timezone_set($savetz);
569 if (trim($profile["homepage"]) != "") {
570 $urls = $doc->createElement("poco:urls");
571 xml::add_element($doc, $urls, "poco:type", "homepage");
572 xml::add_element($doc, $urls, "poco:value", $profile["homepage"]);
573 xml::add_element($doc, $urls, "poco:primary", "true");
574 $author->appendChild($urls);
577 if (trim($profile["pub_keywords"]) != "") {
578 $keywords = explode(",", $profile["pub_keywords"]);
580 foreach ($keywords AS $keyword) {
581 xml::add_element($doc, $author, "poco:tags", trim($keyword));
586 if (trim($profile["xmpp"]) != "") {
587 $ims = $doc->createElement("poco:ims");
588 xml::add_element($doc, $ims, "poco:type", "xmpp");
589 xml::add_element($doc, $ims, "poco:value", $profile["xmpp"]);
590 xml::add_element($doc, $ims, "poco:primary", "true");
591 $author->appendChild($ims);
594 if (trim($profile["locality"].$profile["region"].$profile["country-name"]) != "") {
595 $element = $doc->createElement("poco:address");
597 xml::add_element($doc, $element, "poco:formatted", formatted_location($profile));
599 if (trim($profile["locality"]) != "") {
600 xml::add_element($doc, $element, "poco:locality", $profile["locality"]);
603 if (trim($profile["region"]) != "") {
604 xml::add_element($doc, $element, "poco:region", $profile["region"]);
607 if (trim($profile["country-name"]) != "") {
608 xml::add_element($doc, $element, "poco:country", $profile["country-name"]);
611 $author->appendChild($element);
619 * @brief Adds the author elements in the "entry" elements of the DFRN protocol
621 * @param object $doc XML document
622 * @param string $element Element name for the author
623 * @param string $contact_url Link of the contact
624 * @param array $items Item elements
626 * @return object XML author object
627 * @todo Add type-hints
629 private static function add_entry_author($doc, $element, $contact_url, $item) {
631 $contact = get_contact_details_by_url($contact_url, $item["uid"]);
633 $author = $doc->createElement($element);
634 xml::add_element($doc, $author, "name", $contact["name"]);
635 xml::add_element($doc, $author, "uri", $contact["url"]);
636 xml::add_element($doc, $author, "dfrn:handle", $contact["addr"]);
639 /// - Check real image type and image size
640 /// - Check which of these boths elements we should use
643 "type" => "image/jpeg",
645 "media:height" => 80,
646 "href" => $contact["photo"]);
647 xml::add_element($doc, $author, "link", "", $attributes);
651 "type" => "image/jpeg",
653 "media:height" => 80,
654 "href" => $contact["photo"]);
655 xml::add_element($doc, $author, "link", "", $attributes);
661 * @brief Adds the activity elements
663 * @param object $doc XML document
664 * @param string $element Element name for the activity
665 * @param string $activity activity value
667 * @return object XML activity object
668 * @todo Add type-hints
670 private static function create_activity($doc, $element, $activity) {
673 $entry = $doc->createElement($element);
675 $r = parse_xml_string($activity, false);
680 xml::add_element($doc, $entry, "activity:object-type", $r->type);
683 xml::add_element($doc, $entry, "id", $r->id);
686 xml::add_element($doc, $entry, "title", $r->title);
690 if (substr($r->link, 0, 1) == '<') {
691 if (strstr($r->link, '&') && (! strstr($r->link, '&'))) {
692 $r->link = str_replace('&', '&', $r->link);
695 $r->link = preg_replace('/\<link(.*?)\"\>/', '<link$1"/>', $r->link);
697 // XML does need a single element as root element so we add a dummy element here
698 $data = parse_xml_string("<dummy>" . $r->link . "</dummy>", false);
699 if (is_object($data)) {
700 foreach ($data->link AS $link) {
701 $attributes = array();
702 foreach ($link->attributes() AS $parameter => $value) {
703 $attributes[$parameter] = $value;
705 xml::add_element($doc, $entry, "link", "", $attributes);
709 $attributes = array("rel" => "alternate", "type" => "text/html", "href" => $r->link);
710 xml::add_element($doc, $entry, "link", "", $attributes);
714 xml::add_element($doc, $entry, "content", bbcode($r->content), array("type" => "html"));
724 * @brief Adds the elements for attachments
726 * @param object $doc XML document
727 * @param object $root XML root
728 * @param array $item Item element
730 * @return object XML attachment object
731 * @todo Add type-hints
733 private static function get_attachment($doc, $root, $item) {
734 $arr = explode('[/attach],',$item['attach']);
736 foreach ($arr as $r) {
738 $cnt = preg_match('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\" title=\"(.*?)\"|',$r,$matches);
740 $attributes = array("rel" => "enclosure",
741 "href" => $matches[1],
742 "type" => $matches[3]);
744 if (intval($matches[2])) {
745 $attributes["length"] = intval($matches[2]);
748 if (trim($matches[4]) != "") {
749 $attributes["title"] = trim($matches[4]);
752 xml::add_element($doc, $root, "link", "", $attributes);
759 * @brief Adds the "entry" elements for the DFRN protocol
761 * @param object $doc XML document
762 * @param string $type "text" or "html"
763 * @param array $item Item element
764 * @param array $owner Owner record
765 * @param bool $comment Trigger the sending of the "comment" element
766 * @param int $cid Contact ID of the recipient
768 * @return object XML entry object
769 * @todo Add type-hints
771 private static function entry($doc, $type, $item, $owner, $comment = false, $cid = 0) {
773 $mentioned = array();
775 if (!$item['parent']) {
779 if ($item['deleted']) {
780 $attributes = array("ref" => $item['uri'], "when" => datetime_convert('UTC','UTC',$item['edited'] . '+00:00',ATOM_TIME));
781 return xml::create_element($doc, "at:deleted-entry", "", $attributes);
784 $entry = $doc->createElement("entry");
786 if ($item['allow_cid'] || $item['allow_gid'] || $item['deny_cid'] || $item['deny_gid']) {
787 $body = fix_private_photos($item['body'],$owner['uid'],$item,$cid);
789 $body = $item['body'];
792 // Remove the abstract element. It is only locally important.
793 $body = remove_abstract($body);
795 if ($type == 'html') {
798 if ($item['title'] != "") {
799 $htmlbody = "[b]".$item['title']."[/b]\n\n".$htmlbody;
802 $htmlbody = bbcode($htmlbody, false, false, 7);
805 $author = self::add_entry_author($doc, "author", $item["author-link"], $item);
806 $entry->appendChild($author);
808 $dfrnowner = self::add_entry_author($doc, "dfrn:owner", $item["owner-link"], $item);
809 $entry->appendChild($dfrnowner);
811 if (($item['parent'] != $item['id']) || ($item['parent-uri'] !== $item['uri']) || (($item['thr-parent'] !== '') && ($item['thr-parent'] !== $item['uri']))) {
812 $parent = q("SELECT `guid` FROM `item` WHERE `id` = %d", intval($item["parent"]));
813 $parent_item = (($item['thr-parent']) ? $item['thr-parent'] : $item['parent-uri']);
814 $attributes = array("ref" => $parent_item, "type" => "text/html",
815 "href" => app::get_baseurl().'/display/'.$parent[0]['guid'],
816 "dfrn:diaspora_guid" => $parent[0]['guid']);
817 xml::add_element($doc, $entry, "thr:in-reply-to", "", $attributes);
820 xml::add_element($doc, $entry, "id", $item["uri"]);
821 xml::add_element($doc, $entry, "title", $item["title"]);
823 xml::add_element($doc, $entry, "published", datetime_convert("UTC","UTC",$item["created"]."+00:00",ATOM_TIME));
824 xml::add_element($doc, $entry, "updated", datetime_convert("UTC","UTC",$item["edited"]."+00:00",ATOM_TIME));
826 // "dfrn:env" is used to read the content
827 xml::add_element($doc, $entry, "dfrn:env", base64url_encode($body, true));
829 // The "content" field is not read by the receiver. We could remove it when the type is "text"
830 // We keep it at the moment, maybe there is some old version that doesn't read "dfrn:env"
831 xml::add_element($doc, $entry, "content", (($type == 'html') ? $htmlbody : $body), array("type" => $type));
833 // We save this value in "plink". Maybe we should read it from there as well?
834 xml::add_element($doc, $entry, "link", "", array("rel" => "alternate", "type" => "text/html",
835 "href" => app::get_baseurl()."/display/".$item["guid"]));
837 // "comment-allow" is some old fashioned stuff for old Friendica versions.
838 // It is included in the rewritten code for completeness
840 xml::add_element($doc, $entry, "dfrn:comment-allow", intval($item['last-child']));
843 if ($item['location']) {
844 xml::add_element($doc, $entry, "dfrn:location", $item['location']);
847 if ($item['coord']) {
848 xml::add_element($doc, $entry, "georss:point", $item['coord']);
851 if (($item['private']) || strlen($item['allow_cid']) || strlen($item['allow_gid']) || strlen($item['deny_cid']) || strlen($item['deny_gid'])) {
852 xml::add_element($doc, $entry, "dfrn:private", (($item['private']) ? $item['private'] : 1));
855 if ($item['extid']) {
856 xml::add_element($doc, $entry, "dfrn:extid", $item['extid']);
859 if ($item['bookmark']) {
860 xml::add_element($doc, $entry, "dfrn:bookmark", "true");
864 xml::add_element($doc, $entry, "statusnet:notice_info", "", array("local_id" => $item['id'], "source" => $item['app']));
867 xml::add_element($doc, $entry, "dfrn:diaspora_guid", $item["guid"]);
869 // The signed text contains the content in Markdown, the sender handle and the signatur for the content
870 // It is needed for relayed comments to Diaspora.
871 if ($item['signed_text']) {
872 $sign = base64_encode(json_encode(array('signed_text' => $item['signed_text'],'signature' => $item['signature'],'signer' => $item['signer'])));
873 xml::add_element($doc, $entry, "dfrn:diaspora_signature", $sign);
876 xml::add_element($doc, $entry, "activity:verb", construct_verb($item));
878 if ($item['object-type'] != "") {
879 xml::add_element($doc, $entry, "activity:object-type", $item['object-type']);
880 } elseif ($item['id'] == $item['parent']) {
881 xml::add_element($doc, $entry, "activity:object-type", ACTIVITY_OBJ_NOTE);
883 xml::add_element($doc, $entry, "activity:object-type", ACTIVITY_OBJ_COMMENT);
886 $actobj = self::create_activity($doc, "activity:object", $item['object']);
888 $entry->appendChild($actobj);
891 $actarg = self::create_activity($doc, "activity:target", $item['target']);
893 $entry->appendChild($actarg);
896 $tags = item_getfeedtags($item);
899 foreach ($tags as $t) {
900 if (($type != 'html') OR ($t[0] != "@")) {
901 xml::add_element($doc, $entry, "category", "", array("scheme" => "X-DFRN:".$t[0].":".$t[1], "term" => $t[2]));
907 foreach ($tags as $t) {
909 $mentioned[$t[1]] = $t[1];
914 foreach ($mentioned AS $mention) {
915 $r = q("SELECT `forum`, `prv` FROM `contact` WHERE `uid` = %d AND `nurl` = '%s'",
916 intval($owner["uid"]),
917 dbesc(normalise_link($mention)));
919 if (dbm::is_result($r) AND ($r[0]["forum"] OR $r[0]["prv"])) {
920 xml::add_element($doc, $entry, "link", "", array("rel" => "mentioned",
921 "ostatus:object-type" => ACTIVITY_OBJ_GROUP,
922 "href" => $mention));
924 xml::add_element($doc, $entry, "link", "", array("rel" => "mentioned",
925 "ostatus:object-type" => ACTIVITY_OBJ_PERSON,
926 "href" => $mention));
930 self::get_attachment($doc, $entry, $item);
936 * @brief encrypts data via AES
938 * @param string $data The data that is to be encrypted
939 * @param string $key The AES key
941 * @return string encrypted data
943 private static function aes_encrypt($data, $key) {
944 return openssl_encrypt($data, 'aes-128-ecb', $key, OPENSSL_RAW_DATA);
948 * @brief decrypts data via AES
950 * @param string $encrypted The encrypted data
951 * @param string $key The AES key
953 * @return string decrypted data
955 public static function aes_decrypt($encrypted, $key) {
956 return openssl_decrypt($encrypted, 'aes-128-ecb', $key, OPENSSL_RAW_DATA);
960 * @brief Delivers the atom content to the contacts
962 * @param array $owner Owner record
963 * @param array $contactr Contact record of the receiver
964 * @param string $atom Content that will be transmitted
965 * @param bool $dissolve (to be documented)
967 * @return int Deliver status. -1 means an error.
968 * @todo Add array type-hint for $owner, $contact
970 public static function deliver($owner,$contact,$atom, $dissolve = false) {
974 $idtosend = $orig_id = (($contact['dfrn-id']) ? $contact['dfrn-id'] : $contact['issued-id']);
976 if ($contact['duplex'] && $contact['dfrn-id']) {
977 $idtosend = '0:' . $orig_id;
979 if ($contact['duplex'] && $contact['issued-id']) {
980 $idtosend = '1:' . $orig_id;
983 $rino = get_config('system', 'rino_encrypt');
984 $rino = intval($rino);
986 logger("Local rino version: ". $rino, LOGGER_DEBUG);
988 $ssl_val = intval(get_config('system','ssl_policy'));
992 case SSL_POLICY_FULL:
993 $ssl_policy = 'full';
995 case SSL_POLICY_SELFSIGN:
996 $ssl_policy = 'self';
998 case SSL_POLICY_NONE:
1000 $ssl_policy = 'none';
1004 $url = $contact['notify'] . '&dfrn_id=' . $idtosend . '&dfrn_version=' . DFRN_PROTOCOL_VERSION . (($rino) ? '&rino='.$rino : '');
1006 logger('dfrn_deliver: ' . $url);
1008 $ret = z_fetch_url($url);
1010 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
1011 return -2; // timed out
1014 $xml = $ret['body'];
1016 $curl_stat = $a->get_curl_code();
1018 return -3; // timed out
1021 logger('dfrn_deliver: ' . $xml, LOGGER_DATA);
1027 if (strpos($xml,'<?xml') === false) {
1028 logger('dfrn_deliver: no valid XML returned');
1029 logger('dfrn_deliver: returned XML: ' . $xml, LOGGER_DATA);
1033 $res = parse_xml_string($xml);
1035 if ((intval($res->status) != 0) || (! strlen($res->challenge)) || (! strlen($res->dfrn_id))) {
1036 return (($res->status) ? $res->status : 3);
1039 $postvars = array();
1040 $sent_dfrn_id = hex2bin((string) $res->dfrn_id);
1041 $challenge = hex2bin((string) $res->challenge);
1042 $perm = (($res->perm) ? $res->perm : null);
1043 $dfrn_version = (float) (($res->dfrn_version) ? $res->dfrn_version : 2.0);
1044 $rino_remote_version = intval($res->rino);
1045 $page = (($owner['page-flags'] == PAGE_COMMUNITY) ? 1 : 0);
1047 logger("Remote rino version: ".$rino_remote_version." for ".$contact["url"], LOGGER_DEBUG);
1049 if ($owner['page-flags'] == PAGE_PRVGROUP) {
1053 $final_dfrn_id = '';
1056 if ((($perm == 'rw') && (! intval($contact['writable'])))
1057 || (($perm == 'r') && (intval($contact['writable'])))) {
1058 q("update contact set writable = %d where id = %d",
1059 intval(($perm == 'rw') ? 1 : 0),
1060 intval($contact['id'])
1062 $contact['writable'] = (string) 1 - intval($contact['writable']);
1066 if (($contact['duplex'] && strlen($contact['pubkey']))
1067 || ($owner['page-flags'] == PAGE_COMMUNITY && strlen($contact['pubkey']))
1068 || ($contact['rel'] == CONTACT_IS_SHARING && strlen($contact['pubkey']))) {
1069 openssl_public_decrypt($sent_dfrn_id,$final_dfrn_id,$contact['pubkey']);
1070 openssl_public_decrypt($challenge,$postvars['challenge'],$contact['pubkey']);
1072 openssl_private_decrypt($sent_dfrn_id,$final_dfrn_id,$contact['prvkey']);
1073 openssl_private_decrypt($challenge,$postvars['challenge'],$contact['prvkey']);
1076 $final_dfrn_id = substr($final_dfrn_id, 0, strpos($final_dfrn_id, '.'));
1078 if (strpos($final_dfrn_id,':') == 1) {
1079 $final_dfrn_id = substr($final_dfrn_id,2);
1082 if ($final_dfrn_id != $orig_id) {
1083 logger('dfrn_deliver: wrong dfrn_id.');
1084 // did not decode properly - cannot trust this site
1088 $postvars['dfrn_id'] = $idtosend;
1089 $postvars['dfrn_version'] = DFRN_PROTOCOL_VERSION;
1091 $postvars['dissolve'] = '1';
1095 if ((($contact['rel']) && ($contact['rel'] != CONTACT_IS_SHARING) && (! $contact['blocked'])) || ($owner['page-flags'] == PAGE_COMMUNITY)) {
1096 $postvars['data'] = $atom;
1097 $postvars['perm'] = 'rw';
1099 $postvars['data'] = str_replace('<dfrn:comment-allow>1','<dfrn:comment-allow>0',$atom);
1100 $postvars['perm'] = 'r';
1103 $postvars['ssl_policy'] = $ssl_policy;
1106 $postvars['page'] = $page;
1110 if ($rino > 0 && $rino_remote_version > 0 && (! $dissolve)) {
1111 logger('rino version: '. $rino_remote_version);
1113 switch ($rino_remote_version) {
1115 // Deprecated rino version!
1116 $key = openssl_random_pseudo_bytes(16);
1117 $data = self::aes_encrypt($postvars['data'], $key);
1120 // RINO 2 based on php-encryption
1122 $key = Crypto::createNewRandomKey();
1123 } catch (CryptoTestFailed $ex) {
1124 logger('Cannot safely create a key');
1126 } catch (CannotPerformOperation $ex) {
1127 logger('Cannot safely create a key');
1131 $data = Crypto::encrypt($postvars['data'], $key);
1132 } catch (CryptoTestFailed $ex) {
1133 logger('Cannot safely perform encryption');
1135 } catch (CannotPerformOperation $ex) {
1136 logger('Cannot safely perform encryption');
1141 logger("rino: invalid requested verision '$rino_remote_version'");
1145 $postvars['rino'] = $rino_remote_version;
1146 $postvars['data'] = bin2hex($data);
1148 //logger('rino: sent key = ' . $key, LOGGER_DEBUG);
1151 if ($dfrn_version >= 2.1) {
1152 if (($contact['duplex'] && strlen($contact['pubkey']))
1153 || ($owner['page-flags'] == PAGE_COMMUNITY && strlen($contact['pubkey']))
1154 || ($contact['rel'] == CONTACT_IS_SHARING && strlen($contact['pubkey']))) {
1155 openssl_public_encrypt($key,$postvars['key'],$contact['pubkey']);
1157 openssl_private_encrypt($key,$postvars['key'],$contact['prvkey']);
1161 if (($contact['duplex'] && strlen($contact['prvkey'])) || ($owner['page-flags'] == PAGE_COMMUNITY)) {
1162 openssl_private_encrypt($key,$postvars['key'],$contact['prvkey']);
1164 openssl_public_encrypt($key,$postvars['key'],$contact['pubkey']);
1169 logger('md5 rawkey ' . md5($postvars['key']));
1171 $postvars['key'] = bin2hex($postvars['key']);
1175 logger('dfrn_deliver: ' . "SENDING: " . print_r($postvars,true), LOGGER_DATA);
1177 $xml = post_url($contact['notify'], $postvars);
1179 logger('dfrn_deliver: ' . "RECEIVED: " . $xml, LOGGER_DATA);
1181 $curl_stat = $a->get_curl_code();
1182 if ((!$curl_stat) || (!strlen($xml))) {
1183 return -9; // timed out
1186 if (($curl_stat == 503) && (stristr($a->get_curl_headers(),'retry-after'))) {
1190 if (strpos($xml,'<?xml') === false) {
1191 logger('dfrn_deliver: phase 2: no valid XML returned');
1192 logger('dfrn_deliver: phase 2: returned XML: ' . $xml, LOGGER_DATA);
1196 if ($contact['term-date'] > NULL_DATE) {
1197 logger("dfrn_deliver: $url back from the dead - removing mark for death");
1198 require_once('include/Contact.php');
1199 unmark_for_death($contact);
1202 $res = parse_xml_string($xml);
1204 return $res->status;
1208 * @brief Add new birthday event for this person
1210 * @param array $contact Contact record
1211 * @param string $birthday Birthday of the contact
1212 * @todo Add array type-hint for $contact
1214 private static function birthday_event($contact, $birthday) {
1216 // Check for duplicates
1217 $r = q("SELECT `id` FROM `event` WHERE `uid` = %d AND `cid` = %d AND `start` = '%s' AND `type` = '%s' LIMIT 1",
1218 intval($contact["uid"]),
1219 intval($contact["id"]),
1220 dbesc(datetime_convert("UTC","UTC", $birthday)),
1223 if (dbm::is_result($r)) {
1227 logger("updating birthday: ".$birthday." for contact ".$contact["id"]);
1229 $bdtext = sprintf(t("%s\'s birthday"), $contact["name"]);
1230 $bdtext2 = sprintf(t("Happy Birthday %s"), " [url=".$contact["url"]."]".$contact["name"]."[/url]") ;
1232 $r = q("INSERT INTO `event` (`uid`,`cid`,`created`,`edited`,`start`,`finish`,`summary`,`desc`,`type`)
1233 VALUES ( %d, %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s') ",
1234 intval($contact["uid"]),
1235 intval($contact["id"]),
1236 dbesc(datetime_convert()),
1237 dbesc(datetime_convert()),
1238 dbesc(datetime_convert("UTC","UTC", $birthday)),
1239 dbesc(datetime_convert("UTC","UTC", $birthday." + 1 day ")),
1247 * @brief Fetch the author data from head or entry items
1249 * @param object $xpath XPath object
1250 * @param object $context In which context should the data be searched
1251 * @param array $importer Record of the importer user mixed with contact of the content
1252 * @param string $element Element name from which the data is fetched
1253 * @param bool $onlyfetch Should the data only be fetched or should it update the contact record as well
1255 * @return Returns an array with relevant data of the author
1256 * @todo Find good type-hints for all parameter
1258 private static function fetchauthor($xpath, $context, $importer, $element, $onlyfetch, $xml = "") {
1261 $author["name"] = $xpath->evaluate($element."/atom:name/text()", $context)->item(0)->nodeValue;
1262 $author["link"] = $xpath->evaluate($element."/atom:uri/text()", $context)->item(0)->nodeValue;
1264 $r = q("SELECT `id`, `uid`, `url`, `network`, `avatar-date`, `name-date`, `uri-date`, `addr`,
1265 `name`, `nick`, `about`, `location`, `keywords`, `xmpp`, `bdyear`, `bd`, `hidden`, `contact-type`
1266 FROM `contact` WHERE `uid` = %d AND `nurl` = '%s' AND `network` != '%s'",
1267 intval($importer["uid"]), dbesc(normalise_link($author["link"])), dbesc(NETWORK_STATUSNET));
1269 if (dbm::is_result($r)) {
1271 $author["contact-id"] = $r[0]["id"];
1272 $author["network"] = $r[0]["network"];
1275 logger("Contact ".$author["link"]." wasn't found for user ".$importer["uid"]." XML: ".$xml, LOGGER_DEBUG);
1278 $author["contact-id"] = $importer["id"];
1279 $author["network"] = $importer["network"];
1283 // Until now we aren't serving different sizes - but maybe later
1284 $avatarlist = array();
1285 /// @todo check if "avatar" or "photo" would be the best field in the specification
1286 $avatars = $xpath->query($element."/atom:link[@rel='avatar']", $context);
1287 foreach ($avatars AS $avatar) {
1290 foreach ($avatar->attributes AS $attributes) {
1291 /// @TODO Rewrite these similar if () to one switch
1292 if ($attributes->name == "href") {
1293 $href = $attributes->textContent;
1295 if ($attributes->name == "width") {
1296 $width = $attributes->textContent;
1298 if ($attributes->name == "updated") {
1299 $contact["avatar-date"] = $attributes->textContent;
1302 if (($width > 0) AND ($href != "")) {
1303 $avatarlist[$width] = $href;
1306 if (count($avatarlist) > 0) {
1307 krsort($avatarlist);
1308 $author["avatar"] = current($avatarlist);
1311 if (dbm::is_result($r) AND !$onlyfetch) {
1312 logger("Check if contact details for contact " . $r[0]["id"] . " (" . $r[0]["nick"] . ") have to be updated.", LOGGER_DEBUG);
1314 $poco = array("url" => $contact["url"]);
1316 // When was the last change to name or uri?
1317 $name_element = $xpath->query($element . "/atom:name", $context)->item(0);
1318 foreach ($name_element->attributes AS $attributes) {
1319 if ($attributes->name == "updated") {
1320 $poco["name-date"] = $attributes->textContent;
1324 $link_element = $xpath->query($element . "/atom:link", $context)->item(0);
1325 foreach ($link_element->attributes AS $attributes) {
1326 if ($attributes->name == "updated") {
1327 $poco["uri-date"] = $attributes->textContent;
1331 // Update contact data
1332 $value = $xpath->evaluate($element . "/dfrn:handle/text()", $context)->item(0)->nodeValue;
1334 $poco["addr"] = $value;
1337 $value = $xpath->evaluate($element . "/poco:displayName/text()", $context)->item(0)->nodeValue;
1339 $poco["name"] = $value;
1342 $value = $xpath->evaluate($element . "/poco:preferredUsername/text()", $context)->item(0)->nodeValue;
1344 $poco["nick"] = $value;
1347 $value = $xpath->evaluate($element . "/poco:note/text()", $context)->item(0)->nodeValue;
1349 $poco["about"] = $value;
1352 $value = $xpath->evaluate($element . "/poco:address/poco:formatted/text()", $context)->item(0)->nodeValue;
1354 $poco["location"] = $value;
1357 /// @todo Only search for elements with "poco:type" = "xmpp"
1358 $value = $xpath->evaluate($element . "/poco:ims/poco:value/text()", $context)->item(0)->nodeValue;
1360 $poco["xmpp"] = $value;
1363 /// @todo Add support for the following fields that we don't support by now in the contact table:
1364 /// - poco:utcOffset
1370 // If the "hide" element is present then the profile isn't searchable.
1371 $hide = intval($xpath->evaluate($element . "/dfrn:hide/text()", $context)->item(0)->nodeValue == "true");
1373 logger("Hidden status for contact " . $contact["url"] . ": " . $hide, LOGGER_DEBUG);
1375 // If the contact isn't searchable then set the contact to "hidden".
1376 // Problem: This can be manually overridden by the user.
1378 $contact["hidden"] = true;
1381 // Save the keywords into the contact table
1383 $tagelements = $xpath->evaluate($element . "/poco:tags/text()", $context);
1384 foreach ($tagelements AS $tag) {
1385 $tags[$tag->nodeValue] = $tag->nodeValue;
1389 $poco["keywords"] = implode(", ", $tags);
1392 // "dfrn:birthday" contains the birthday converted to UTC
1393 $old_bdyear = $contact["bdyear"];
1395 $birthday = $xpath->evaluate($element . "/dfrn:birthday/text()", $context)->item(0)->nodeValue;
1397 if (strtotime($birthday) > time()) {
1398 $bd_timestamp = strtotime($birthday);
1400 $poco["bdyear"] = date("Y", $bd_timestamp);
1403 // "poco:birthday" is the birthday in the format "yyyy-mm-dd"
1404 $value = $xpath->evaluate($element . "/poco:birthday/text()", $context)->item(0)->nodeValue;
1406 if (!in_array($value, array("", "0000-00-00", "0001-01-01"))) {
1407 $bdyear = date("Y");
1408 $value = str_replace("0000", $bdyear, $value);
1410 if (strtotime($value) < time()) {
1411 $value = str_replace($bdyear, $bdyear + 1, $value);
1412 $bdyear = $bdyear + 1;
1415 $poco["bd"] = $value;
1418 $contact = array_merge($contact, $poco);
1420 if ($old_bdyear != $contact["bdyear"]) {
1421 self::birthday_event($contact, $birthday);
1424 // Get all field names
1426 foreach ($r[0] AS $field => $data) {
1427 $fields[$field] = $data;
1430 unset($fields["id"]);
1431 unset($fields["uid"]);
1432 unset($fields["url"]);
1433 unset($fields["avatar-date"]);
1434 unset($fields["name-date"]);
1435 unset($fields["uri-date"]);
1437 // Update check for this field has to be done differently
1438 $datefields = array("name-date", "uri-date");
1439 foreach ($datefields AS $field) {
1440 if (strtotime($contact[$field]) > strtotime($r[0][$field])) {
1441 logger("Difference for contact " . $contact["id"] . " in field '" . $field . "'. New value: '" . $contact[$field] . "', old value '" . $r[0][$field] . "'", LOGGER_DEBUG);
1446 foreach ($fields AS $field => $data) {
1447 if ($contact[$field] != $r[0][$field]) {
1448 logger("Difference for contact " . $contact["id"] . " in field '" . $field . "'. New value: '" . $contact[$field] . "', old value '" . $r[0][$field] . "'", LOGGER_DEBUG);
1454 logger("Update contact data for contact " . $contact["id"] . " (" . $contact["nick"] . ")", LOGGER_DEBUG);
1456 q("UPDATE `contact` SET `name` = '%s', `nick` = '%s', `about` = '%s', `location` = '%s',
1457 `addr` = '%s', `keywords` = '%s', `bdyear` = '%s', `bd` = '%s', `hidden` = %d,
1458 `xmpp` = '%s', `name-date` = '%s', `uri-date` = '%s'
1459 WHERE `id` = %d AND `network` = '%s'",
1460 dbesc($contact["name"]), dbesc($contact["nick"]), dbesc($contact["about"]), dbesc($contact["location"]),
1461 dbesc($contact["addr"]), dbesc($contact["keywords"]), dbesc($contact["bdyear"]),
1462 dbesc($contact["bd"]), intval($contact["hidden"]), dbesc($contact["xmpp"]),
1463 dbesc(dbm::date($contact["name-date"])), dbesc(dbm::date($contact["uri-date"])),
1464 intval($contact["id"]), dbesc($contact["network"]));
1467 update_contact_avatar($author["avatar"], $importer["uid"], $contact["id"],
1468 (strtotime($contact["avatar-date"]) > strtotime($r[0]["avatar-date"])));
1471 * The generation is a sign for the reliability of the provided data.
1472 * It is used in the socgraph.php to prevent that old contact data
1473 * that was relayed over several servers can overwrite contact
1474 * data that we received directly.
1477 $poco["generation"] = 2;
1478 $poco["photo"] = $author["avatar"];
1479 $poco["hide"] = $hide;
1480 $poco["contact-type"] = $contact["contact-type"];
1481 $gcid = update_gcontact($poco);
1483 link_gcontact($gcid, $importer["uid"], $contact["id"]);
1490 * @brief Transforms activity objects into an XML string
1492 * @param object $xpath XPath object
1493 * @param object $activity Activity object
1494 * @param text $element element name
1496 * @return string XML string
1497 * @todo Find good type-hints for all parameter
1499 private static function transform_activity($xpath, $activity, $element) {
1500 if (!is_object($activity)) {
1504 $obj_doc = new DOMDocument("1.0", "utf-8");
1505 $obj_doc->formatOutput = true;
1507 $obj_element = $obj_doc->createElementNS(NAMESPACE_ATOM1, $element);
1509 $activity_type = $xpath->query("activity:object-type/text()", $activity)->item(0)->nodeValue;
1510 xml::add_element($obj_doc, $obj_element, "type", $activity_type);
1512 $id = $xpath->query("atom:id", $activity)->item(0);
1513 if (is_object($id)) {
1514 $obj_element->appendChild($obj_doc->importNode($id, true));
1517 $title = $xpath->query("atom:title", $activity)->item(0);
1518 if (is_object($title)) {
1519 $obj_element->appendChild($obj_doc->importNode($title, true));
1522 $links = $xpath->query("atom:link", $activity);
1523 if (is_object($links)) {
1524 foreach ($links AS $link) {
1525 $obj_element->appendChild($obj_doc->importNode($link, true));
1529 $content = $xpath->query("atom:content", $activity)->item(0);
1530 if (is_object($content)) {
1531 $obj_element->appendChild($obj_doc->importNode($content, true));
1534 $obj_doc->appendChild($obj_element);
1536 $objxml = $obj_doc->saveXML($obj_element);
1538 /// @todo This isn't totally clean. We should find a way to transform the namespaces
1539 $objxml = str_replace("<".$element.' xmlns="http://www.w3.org/2005/Atom">', "<".$element.">", $objxml);
1544 * @brief Processes the mail elements
1546 * @param object $xpath XPath object
1547 * @param object $mail mail elements
1548 * @param array $importer Record of the importer user mixed with contact of the content
1549 * @todo Find good type-hints for all parameter
1551 private static function process_mail($xpath, $mail, $importer) {
1553 logger("Processing mails");
1555 /// @TODO Rewrite this to one statement
1557 $msg["uid"] = $importer["importer_uid"];
1558 $msg["from-name"] = $xpath->query("dfrn:sender/dfrn:name/text()", $mail)->item(0)->nodeValue;
1559 $msg["from-url"] = $xpath->query("dfrn:sender/dfrn:uri/text()", $mail)->item(0)->nodeValue;
1560 $msg["from-photo"] = $xpath->query("dfrn:sender/dfrn:avatar/text()", $mail)->item(0)->nodeValue;
1561 $msg["contact-id"] = $importer["id"];
1562 $msg["uri"] = $xpath->query("dfrn:id/text()", $mail)->item(0)->nodeValue;
1563 $msg["parent-uri"] = $xpath->query("dfrn:in-reply-to/text()", $mail)->item(0)->nodeValue;
1564 $msg["created"] = $xpath->query("dfrn:sentdate/text()", $mail)->item(0)->nodeValue;
1565 $msg["title"] = $xpath->query("dfrn:subject/text()", $mail)->item(0)->nodeValue;
1566 $msg["body"] = $xpath->query("dfrn:content/text()", $mail)->item(0)->nodeValue;
1568 $msg["replied"] = 0;
1570 dbm::esc_array($msg, true);
1572 $r = dbq("INSERT INTO `mail` (`".implode("`, `", array_keys($msg))."`) VALUES (".implode(", ", array_values($msg)).")");
1574 // send notifications.
1575 /// @TODO Arange this mess
1576 $notif_params = array(
1577 "type" => NOTIFY_MAIL,
1578 "notify_flags" => $importer["notify-flags"],
1579 "language" => $importer["language"],
1580 "to_name" => $importer["username"],
1581 "to_email" => $importer["email"],
1582 "uid" => $importer["importer_uid"],
1584 "source_name" => $msg["from-name"],
1585 "source_link" => $importer["url"],
1586 "source_photo" => $importer["thumb"],
1587 "verb" => ACTIVITY_POST,
1591 notification($notif_params);
1593 logger("Mail is processed, notification was sent.");
1597 * @brief Processes the suggestion elements
1599 * @param object $xpath XPath object
1600 * @param object $suggestion suggestion elements
1601 * @param array $importer Record of the importer user mixed with contact of the content
1602 * @todo Find good type-hints for all parameter
1604 private static function process_suggestion($xpath, $suggestion, $importer) {
1607 logger("Processing suggestions");
1609 /// @TODO Rewrite this to one statement
1611 $suggest["uid"] = $importer["importer_uid"];
1612 $suggest["cid"] = $importer["id"];
1613 $suggest["url"] = $xpath->query("dfrn:url/text()", $suggestion)->item(0)->nodeValue;
1614 $suggest["name"] = $xpath->query("dfrn:name/text()", $suggestion)->item(0)->nodeValue;
1615 $suggest["photo"] = $xpath->query("dfrn:photo/text()", $suggestion)->item(0)->nodeValue;
1616 $suggest["request"] = $xpath->query("dfrn:request/text()", $suggestion)->item(0)->nodeValue;
1617 $suggest["body"] = $xpath->query("dfrn:note/text()", $suggestion)->item(0)->nodeValue;
1619 // Does our member already have a friend matching this description?
1621 $r = q("SELECT `id` FROM `contact` WHERE `name` = '%s' AND `nurl` = '%s' AND `uid` = %d LIMIT 1",
1622 dbesc($suggest["name"]),
1623 dbesc(normalise_link($suggest["url"])),
1624 intval($suggest["uid"])
1628 * The valid result means the friend we're about to send a friend
1629 * suggestion already has them in their contact, which means no further
1630 * action is required.
1632 * @see https://github.com/friendica/friendica/pull/3254#discussion_r107315246
1634 if (dbm::is_result($r)) {
1638 // Do we already have an fcontact record for this person?
1641 $r = q("SELECT `id` FROM `fcontact` WHERE `url` = '%s' AND `name` = '%s' AND `request` = '%s' LIMIT 1",
1642 dbesc($suggest["url"]),
1643 dbesc($suggest["name"]),
1644 dbesc($suggest["request"])
1646 if (dbm::is_result($r)) {
1649 // OK, we do. Do we already have an introduction for this person ?
1650 $r = q("SELECT `id` FROM `intro` WHERE `uid` = %d AND `fid` = %d LIMIT 1",
1651 intval($suggest["uid"]),
1656 * The valid result means the friend we're about to send a friend
1657 * suggestion already has them in their contact, which means no further
1658 * action is required.
1660 * @see https://github.com/friendica/friendica/pull/3254#discussion_r107315246
1662 if (dbm::is_result($r)) {
1667 $r = q("INSERT INTO `fcontact` (`name`,`url`,`photo`,`request`) VALUES ('%s', '%s', '%s', '%s')",
1668 dbesc($suggest["name"]),
1669 dbesc($suggest["url"]),
1670 dbesc($suggest["photo"]),
1671 dbesc($suggest["request"])
1674 $r = q("SELECT `id` FROM `fcontact` WHERE `url` = '%s' AND `name` = '%s' AND `request` = '%s' LIMIT 1",
1675 dbesc($suggest["url"]),
1676 dbesc($suggest["name"]),
1677 dbesc($suggest["request"])
1681 * If no record in fcontact is found, below INSERT statement will not
1682 * link an introduction to it.
1684 if (!dbm::is_result($r)) {
1685 // database record did not get created. Quietly give up.
1691 $hash = random_string();
1693 $r = q("INSERT INTO `intro` (`uid`, `fid`, `contact-id`, `note`, `hash`, `datetime`, `blocked`)
1694 VALUES(%d, %d, %d, '%s', '%s', '%s', %d)",
1695 intval($suggest["uid"]),
1697 intval($suggest["cid"]),
1698 dbesc($suggest["body"]),
1700 dbesc(datetime_convert()),
1705 "type" => NOTIFY_SUGGEST,
1706 "notify_flags" => $importer["notify-flags"],
1707 "language" => $importer["language"],
1708 "to_name" => $importer["username"],
1709 "to_email" => $importer["email"],
1710 "uid" => $importer["importer_uid"],
1712 "link" => App::get_baseurl()."/notifications/intros",
1713 "source_name" => $importer["name"],
1714 "source_link" => $importer["url"],
1715 "source_photo" => $importer["photo"],
1716 "verb" => ACTIVITY_REQ_FRIEND,
1725 * @brief Processes the relocation elements
1727 * @param object $xpath XPath object
1728 * @param object $relocation relocation elements
1729 * @param array $importer Record of the importer user mixed with contact of the content
1730 * @todo Find good type-hints for all parameter
1732 private static function process_relocation($xpath, $relocation, $importer) {
1734 logger("Processing relocations");
1736 /// @TODO Rewrite this to one statement
1737 $relocate = array();
1738 $relocate["uid"] = $importer["importer_uid"];
1739 $relocate["cid"] = $importer["id"];
1740 $relocate["url"] = $xpath->query("dfrn:url/text()", $relocation)->item(0)->nodeValue;
1741 $relocate["addr"] = $xpath->query("dfrn:addr/text()", $relocation)->item(0)->nodeValue;
1742 $relocate["name"] = $xpath->query("dfrn:name/text()", $relocation)->item(0)->nodeValue;
1743 $relocate["avatar"] = $xpath->query("dfrn:avatar/text()", $relocation)->item(0)->nodeValue;
1744 $relocate["photo"] = $xpath->query("dfrn:photo/text()", $relocation)->item(0)->nodeValue;
1745 $relocate["thumb"] = $xpath->query("dfrn:thumb/text()", $relocation)->item(0)->nodeValue;
1746 $relocate["micro"] = $xpath->query("dfrn:micro/text()", $relocation)->item(0)->nodeValue;
1747 $relocate["request"] = $xpath->query("dfrn:request/text()", $relocation)->item(0)->nodeValue;
1748 $relocate["confirm"] = $xpath->query("dfrn:confirm/text()", $relocation)->item(0)->nodeValue;
1749 $relocate["notify"] = $xpath->query("dfrn:notify/text()", $relocation)->item(0)->nodeValue;
1750 $relocate["poll"] = $xpath->query("dfrn:poll/text()", $relocation)->item(0)->nodeValue;
1751 $relocate["sitepubkey"] = $xpath->query("dfrn:sitepubkey/text()", $relocation)->item(0)->nodeValue;
1753 if (($relocate["avatar"] == "") AND ($relocate["photo"] != "")) {
1754 $relocate["avatar"] = $relocate["photo"];
1757 if ($relocate["addr"] == "") {
1758 $relocate["addr"] = preg_replace("=(https?://)(.*)/profile/(.*)=ism", "$3@$2", $relocate["url"]);
1762 $r = q("SELECT `photo`, `url` FROM `contact` WHERE `id` = %d AND `uid` = %d;",
1763 intval($importer["id"]),
1764 intval($importer["importer_uid"]));
1766 if (!dbm::is_result($r)) {
1767 logger("Query failed to execute, no result returned in " . __FUNCTION__);
1773 // Update the gcontact entry
1774 $relocate["server_url"] = preg_replace("=(https?://)(.*)/profile/(.*)=ism", "$1$2", $relocate["url"]);
1776 $x = q("UPDATE `gcontact` SET
1785 WHERE `nurl` = '%s';",
1786 dbesc($relocate["name"]),
1787 dbesc($relocate["avatar"]),
1788 dbesc($relocate["url"]),
1789 dbesc(normalise_link($relocate["url"])),
1790 dbesc($relocate["addr"]),
1791 dbesc($relocate["addr"]),
1792 dbesc($relocate["notify"]),
1793 dbesc($relocate["server_url"]),
1794 dbesc(normalise_link($old["url"])));
1796 // Update the contact table. We try to find every entry.
1797 $x = q("UPDATE `contact` SET
1807 `site-pubkey` = '%s'
1808 WHERE (`id` = %d AND `uid` = %d) OR (`nurl` = '%s');",
1809 dbesc($relocate["name"]),
1810 dbesc($relocate["avatar"]),
1811 dbesc($relocate["url"]),
1812 dbesc(normalise_link($relocate["url"])),
1813 dbesc($relocate["addr"]),
1814 dbesc($relocate["request"]),
1815 dbesc($relocate["confirm"]),
1816 dbesc($relocate["notify"]),
1817 dbesc($relocate["poll"]),
1818 dbesc($relocate["sitepubkey"]),
1819 intval($importer["id"]),
1820 intval($importer["importer_uid"]),
1821 dbesc(normalise_link($old["url"])));
1823 update_contact_avatar($relocate["avatar"], $importer["importer_uid"], $importer["id"], true);
1830 /// @todo This is an extreme performance killer
1832 'owner-link' => array($old["url"], $relocate["url"]),
1833 'author-link' => array($old["url"], $relocate["url"]),
1834 //'owner-avatar' => array($old["photo"], $relocate["photo"]),
1835 //'author-avatar' => array($old["photo"], $relocate["photo"]),
1837 foreach ($fields as $n=>$f) {
1838 $r = q("SELECT `id` FROM `item` WHERE `%s` = '%s' AND `uid` = %d LIMIT 1",
1840 intval($importer["importer_uid"]));
1842 if (dbm::is_result($r)) {
1843 $x = q("UPDATE `item` SET `%s` = '%s' WHERE `%s` = '%s' AND `uid` = %d",
1846 intval($importer["importer_uid"]));
1855 /// merge with current record, current contents have priority
1856 /// update record, set url-updated
1857 /// update profile photos
1858 /// schedule a scan?
1863 * @brief Updates an item
1865 * @param array $current the current item record
1866 * @param array $item the new item record
1867 * @param array $importer Record of the importer user mixed with contact of the content
1868 * @param int $entrytype Is it a toplevel entry, a comment or a relayed comment?
1869 * @todo set proper type-hints (array?)
1871 private static function update_content($current, $item, $importer, $entrytype) {
1874 if (edited_timestamp_is_newer($current, $item)) {
1876 // do not accept (ignore) an earlier edit than one we currently have.
1877 if (datetime_convert("UTC","UTC",$item["edited"]) < $current["edited"]) {
1881 $r = q("UPDATE `item` SET `title` = '%s', `body` = '%s', `tag` = '%s', `edited` = '%s', `changed` = '%s' WHERE `uri` = '%s' AND `uid` = %d",
1882 dbesc($item["title"]),
1883 dbesc($item["body"]),
1884 dbesc($item["tag"]),
1885 dbesc(datetime_convert("UTC","UTC",$item["edited"])),
1886 dbesc(datetime_convert()),
1887 dbesc($item["uri"]),
1888 intval($importer["importer_uid"])
1890 create_tags_from_itemuri($item["uri"], $importer["importer_uid"]);
1891 update_thread_uri($item["uri"], $importer["importer_uid"]);
1895 if ($entrytype == DFRN_REPLY_RC) {
1896 proc_run(PRIORITY_HIGH, "include/notifier.php","comment-import", $current["id"]);
1900 // update last-child if it changes
1901 if ($item["last-child"] AND ($item["last-child"] != $current["last-child"])) {
1902 $r = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d",
1903 dbesc(datetime_convert()),
1904 dbesc($item["parent-uri"]),
1905 intval($importer["importer_uid"])
1907 $r = q("UPDATE `item` SET `last-child` = %d , `changed` = '%s' WHERE `uri` = '%s' AND `uid` = %d",
1908 intval($item["last-child"]),
1909 dbesc(datetime_convert()),
1910 dbesc($item["uri"]),
1911 intval($importer["importer_uid"])
1918 * @brief Detects the entry type of the item
1920 * @param array $importer Record of the importer user mixed with contact of the content
1921 * @param array $item the new item record
1923 * @return int Is it a toplevel entry, a comment or a relayed comment?
1924 * @todo set proper type-hints (array?)
1926 private static function get_entry_type($importer, $item) {
1927 if ($item["parent-uri"] != $item["uri"]) {
1930 if ($importer["page-flags"] == PAGE_COMMUNITY || $importer["page-flags"] == PAGE_PRVGROUP) {
1933 logger("possible community action");
1935 $sql_extra = " AND `contact`.`self` AND `item`.`wall` ";
1938 // was the top-level post for this action written by somebody on this site?
1939 // Specifically, the recipient?
1941 $is_a_remote_action = false;
1943 $r = q("SELECT `item`.`parent-uri` FROM `item`
1944 WHERE `item`.`uri` = '%s'
1946 dbesc($item["parent-uri"])
1948 if (dbm::is_result($r)) {
1949 $r = q("SELECT `item`.`forum_mode`, `item`.`wall` FROM `item`
1950 INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
1951 WHERE `item`.`uri` = '%s' AND (`item`.`parent-uri` = '%s' OR `item`.`thr-parent` = '%s')
1952 AND `item`.`uid` = %d
1955 dbesc($r[0]["parent-uri"]),
1956 dbesc($r[0]["parent-uri"]),
1957 dbesc($r[0]["parent-uri"]),
1958 intval($importer["importer_uid"])
1960 if (dbm::is_result($r)) {
1961 $is_a_remote_action = true;
1966 * Does this have the characteristics of a community or private group action?
1967 * If it's an action to a wall post on a community/prvgroup page it's a
1968 * valid community action. Also forum_mode makes it valid for sure.
1969 * If neither, it's not.
1972 /// @TODO Maybe merge these if() blocks into one?
1973 if ($is_a_remote_action && $community && (!$r[0]["forum_mode"]) && (!$r[0]["wall"])) {
1974 $is_a_remote_action = false;
1975 logger("not a community action");
1978 if ($is_a_remote_action) {
1979 return DFRN_REPLY_RC;
1984 return DFRN_TOP_LEVEL;
1990 * @brief Send a "poke"
1992 * @param array $item the new item record
1993 * @param array $importer Record of the importer user mixed with contact of the content
1994 * @param int $posted_id The record number of item record that was just posted
1995 * @todo set proper type-hints (array?)
1997 private static function do_poke($item, $importer, $posted_id) {
1998 $verb = urldecode(substr($item["verb"],strpos($item["verb"], "#")+1));
2002 $xo = parse_xml_string($item["object"],false);
2004 if (($xo->type == ACTIVITY_OBJ_PERSON) && ($xo->id)) {
2006 // somebody was poked/prodded. Was it me?
2007 foreach ($xo->link as $l) {
2008 $atts = $l->attributes();
2009 switch ($atts["rel"]) {
2011 $Blink = $atts["href"];
2018 if ($Blink && link_compare($Blink, App::get_baseurl() . "/profile/" . $importer["nickname"])) {
2020 // send a notification
2022 "type" => NOTIFY_POKE,
2023 "notify_flags" => $importer["notify-flags"],
2024 "language" => $importer["language"],
2025 "to_name" => $importer["username"],
2026 "to_email" => $importer["email"],
2027 "uid" => $importer["importer_uid"],
2029 "link" => App::get_baseurl()."/display/".urlencode(get_item_guid($posted_id)),
2030 "source_name" => stripslashes($item["author-name"]),
2031 "source_link" => $item["author-link"],
2032 "source_photo" => ((link_compare($item["author-link"],$importer["url"]))
2033 ? $importer["thumb"] : $item["author-avatar"]),
2034 "verb" => $item["verb"],
2035 "otype" => "person",
2036 "activity" => $verb,
2037 "parent" => $item["parent"]
2044 * @brief Processes several actions, depending on the verb
2046 * @param int $entrytype Is it a toplevel entry, a comment or a relayed comment?
2047 * @param array $importer Record of the importer user mixed with contact of the content
2048 * @param array $item the new item record
2049 * @param bool $is_like Is the verb a "like"?
2051 * @return bool Should the processing of the entries be continued?
2052 * @todo set proper type-hints (array?)
2054 private static function process_verbs($entrytype, $importer, &$item, &$is_like) {
2056 logger("Process verb ".$item["verb"]." and object-type ".$item["object-type"]." for entrytype ".$entrytype, LOGGER_DEBUG);
2058 if (($entrytype == DFRN_TOP_LEVEL)) {
2059 // The filling of the the "contact" variable is done for legcy reasons
2060 // The functions below are partly used by ostatus.php as well - where we have this variable
2061 $r = q("SELECT * FROM `contact` WHERE `id` = %d", intval($importer["id"]));
2063 $nickname = $contact["nick"];
2065 // Big question: Do we need these functions? They were part of the "consume_feed" function.
2066 // This function once was responsible for DFRN and OStatus.
2067 if (activity_match($item["verb"], ACTIVITY_FOLLOW)) {
2068 logger("New follower");
2069 new_follower($importer, $contact, $item, $nickname);
2072 if (activity_match($item["verb"], ACTIVITY_UNFOLLOW)) {
2073 logger("Lost follower");
2074 lose_follower($importer, $contact, $item);
2077 if (activity_match($item["verb"], ACTIVITY_REQ_FRIEND)) {
2078 logger("New friend request");
2079 new_follower($importer, $contact, $item, $nickname, true);
2082 if (activity_match($item["verb"], ACTIVITY_UNFRIEND)) {
2083 logger("Lost sharer");
2084 lose_sharer($importer, $contact, $item);
2088 if (($item["verb"] == ACTIVITY_LIKE)
2089 || ($item["verb"] == ACTIVITY_DISLIKE)
2090 || ($item["verb"] == ACTIVITY_ATTEND)
2091 || ($item["verb"] == ACTIVITY_ATTENDNO)
2092 || ($item["verb"] == ACTIVITY_ATTENDMAYBE)) {
2094 $item["type"] = "activity";
2095 $item["gravity"] = GRAVITY_LIKE;
2096 // only one like or dislike per person
2097 // splitted into two queries for performance issues
2098 $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",
2099 intval($item["uid"]),
2100 dbesc($item["author-link"]),
2101 dbesc($item["verb"]),
2102 dbesc($item["parent-uri"])
2104 if (dbm::is_result($r)) {
2108 $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",
2109 intval($item["uid"]),
2110 dbesc($item["author-link"]),
2111 dbesc($item["verb"]),
2112 dbesc($item["parent-uri"])
2114 if (dbm::is_result($r)) {
2121 if (($item["verb"] == ACTIVITY_TAG) && ($item["object-type"] == ACTIVITY_OBJ_TAGTERM)) {
2123 $xo = parse_xml_string($item["object"],false);
2124 $xt = parse_xml_string($item["target"],false);
2126 if ($xt->type == ACTIVITY_OBJ_NOTE) {
2127 $r = q("SELECT `id`, `tag` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2129 intval($importer["importer_uid"])
2132 if (!dbm::is_result($r)) {
2133 logger("Query failed to execute, no result returned in " . __FUNCTION__);
2137 // extract tag, if not duplicate, add to parent item
2139 if (!(stristr($r[0]["tag"],trim($xo->content)))) {
2140 q("UPDATE `item` SET `tag` = '%s' WHERE `id` = %d",
2141 dbesc($r[0]["tag"] . (strlen($r[0]["tag"]) ? ',' : '') . '#[url=' . $xo->id . ']'. $xo->content . '[/url]'),
2144 create_tags_from_item($r[0]["id"]);
2154 * @brief Processes the link elements
2156 * @param object $links link elements
2157 * @param array $item the item record
2158 * @todo set proper type-hints
2160 private static function parse_links($links, &$item) {
2166 foreach ($links AS $link) {
2167 foreach ($link->attributes AS $attributes) {
2168 /// @TODO Rewrite these repeated (same) if () statements to a switch()
2169 if ($attributes->name == "href") {
2170 $href = $attributes->textContent;
2172 if ($attributes->name == "rel") {
2173 $rel = $attributes->textContent;
2175 if ($attributes->name == "type") {
2176 $type = $attributes->textContent;
2178 if ($attributes->name == "length") {
2179 $length = $attributes->textContent;
2181 if ($attributes->name == "title") {
2182 $title = $attributes->textContent;
2185 if (($rel != "") AND ($href != "")) {
2188 $item["plink"] = $href;
2192 if (strlen($item["attach"])) {
2193 $item["attach"] .= ",";
2196 $item["attach"] .= '[attach]href="' . $href . '" length="' . $length . '" type="' . $type . '" title="' . $title . '"[/attach]';
2204 * @brief Processes the entry elements which contain the items and comments
2206 * @param array $header Array of the header elements that always stay the same
2207 * @param object $xpath XPath object
2208 * @param object $entry entry elements
2209 * @param array $importer Record of the importer user mixed with contact of the content
2210 * @todo Add type-hints
2212 private static function process_entry($header, $xpath, $entry, $importer) {
2214 logger("Processing entries");
2219 $item["uri"] = $xpath->query("atom:id/text()", $entry)->item(0)->nodeValue;
2221 $item["edited"] = $xpath->query("atom:updated/text()", $entry)->item(0)->nodeValue;
2223 $current = q("SELECT `id`, `uid`, `last-child`, `edited`, `body` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2224 dbesc($item["uri"]),
2225 intval($importer["importer_uid"])
2228 // Is there an existing item?
2229 if (dbm::is_result($current) AND edited_timestamp_is_newer($current[0], $item) AND
2230 (datetime_convert("UTC","UTC",$item["edited"]) < $current[0]["edited"])) {
2231 logger("Item ".$item["uri"]." already existed.", LOGGER_DEBUG);
2236 $owner = self::fetchauthor($xpath, $entry, $importer, "dfrn:owner", true);
2238 $item["owner-name"] = $owner["name"];
2239 $item["owner-link"] = $owner["link"];
2240 $item["owner-avatar"] = $owner["avatar"];
2243 $author = self::fetchauthor($xpath, $entry, $importer, "atom:author", true);
2245 $item["author-name"] = $author["name"];
2246 $item["author-link"] = $author["link"];
2247 $item["author-avatar"] = $author["avatar"];
2249 $item["title"] = $xpath->query("atom:title/text()", $entry)->item(0)->nodeValue;
2251 $item["created"] = $xpath->query("atom:published/text()", $entry)->item(0)->nodeValue;
2253 $item["body"] = $xpath->query("dfrn:env/text()", $entry)->item(0)->nodeValue;
2254 $item["body"] = str_replace(array(' ',"\t","\r","\n"), array('','','',''),$item["body"]);
2255 // make sure nobody is trying to sneak some html tags by us
2256 $item["body"] = notags(base64url_decode($item["body"]));
2258 $item["body"] = limit_body_size($item["body"]);
2260 /// @todo Do we really need this check for HTML elements? (It was copied from the old function)
2261 if ((strpos($item['body'],'<') !== false) && (strpos($item['body'],'>') !== false)) {
2263 $item['body'] = reltoabs($item['body'],$base_url);
2265 $item['body'] = html2bb_video($item['body']);
2267 $item['body'] = oembed_html2bbcode($item['body']);
2269 $config = HTMLPurifier_Config::createDefault();
2270 $config->set('Cache.DefinitionImpl', null);
2272 // we shouldn't need a whitelist, because the bbcode converter
2273 // will strip out any unsupported tags.
2275 $purifier = new HTMLPurifier($config);
2276 $item['body'] = $purifier->purify($item['body']);
2278 $item['body'] = @html2bbcode($item['body']);
2281 /// @todo We should check for a repeated post and if we know the repeated author.
2283 // We don't need the content element since "dfrn:env" is always present
2284 //$item["body"] = $xpath->query("atom:content/text()", $entry)->item(0)->nodeValue;
2286 $item["last-child"] = $xpath->query("dfrn:comment-allow/text()", $entry)->item(0)->nodeValue;
2287 $item["location"] = $xpath->query("dfrn:location/text()", $entry)->item(0)->nodeValue;
2289 $georsspoint = $xpath->query("georss:point", $entry);
2291 $item["coord"] = $georsspoint->item(0)->nodeValue;
2294 $item["private"] = $xpath->query("dfrn:private/text()", $entry)->item(0)->nodeValue;
2296 $item["extid"] = $xpath->query("dfrn:extid/text()", $entry)->item(0)->nodeValue;
2298 if ($xpath->query("dfrn:bookmark/text()", $entry)->item(0)->nodeValue == "true") {
2299 $item["bookmark"] = true;
2302 $notice_info = $xpath->query("statusnet:notice_info", $entry);
2303 if ($notice_info AND ($notice_info->length > 0)) {
2304 foreach ($notice_info->item(0)->attributes AS $attributes) {
2305 if ($attributes->name == "source") {
2306 $item["app"] = strip_tags($attributes->textContent);
2311 $item["guid"] = $xpath->query("dfrn:diaspora_guid/text()", $entry)->item(0)->nodeValue;
2313 // We store the data from "dfrn:diaspora_signature" in a different table, this is done in "item_store"
2314 $dsprsig = unxmlify($xpath->query("dfrn:diaspora_signature/text()", $entry)->item(0)->nodeValue);
2315 if ($dsprsig != "") {
2316 $item["dsprsig"] = $dsprsig;
2319 $item["verb"] = $xpath->query("activity:verb/text()", $entry)->item(0)->nodeValue;
2321 if ($xpath->query("activity:object-type/text()", $entry)->item(0)->nodeValue != "") {
2322 $item["object-type"] = $xpath->query("activity:object-type/text()", $entry)->item(0)->nodeValue;
2325 $object = $xpath->query("activity:object", $entry)->item(0);
2326 $item["object"] = self::transform_activity($xpath, $object, "object");
2328 if (trim($item["object"]) != "") {
2329 $r = parse_xml_string($item["object"], false);
2330 if (isset($r->type)) {
2331 $item["object-type"] = $r->type;
2335 $target = $xpath->query("activity:target", $entry)->item(0);
2336 $item["target"] = self::transform_activity($xpath, $target, "target");
2338 $categories = $xpath->query("atom:category", $entry);
2340 foreach ($categories AS $category) {
2343 foreach ($category->attributes AS $attributes) {
2344 if ($attributes->name == "term") {
2345 $term = $attributes->textContent;
2348 if ($attributes->name == "scheme") {
2349 $scheme = $attributes->textContent;
2353 if (($term != "") AND ($scheme != "")) {
2354 $parts = explode(":", $scheme);
2355 if ((count($parts) >= 4) AND (array_shift($parts) == "X-DFRN")) {
2356 $termhash = array_shift($parts);
2357 $termurl = implode(":", $parts);
2359 if (strlen($item["tag"])) {
2360 $item["tag"] .= ",";
2363 $item["tag"] .= $termhash . "[url=" . $termurl . "]" . $term . "[/url]";
2371 $links = $xpath->query("atom:link", $entry);
2373 self::parse_links($links, $item);
2376 // Is it a reply or a top level posting?
2377 $item["parent-uri"] = $item["uri"];
2379 $inreplyto = $xpath->query("thr:in-reply-to", $entry);
2380 if (is_object($inreplyto->item(0))) {
2381 foreach ($inreplyto->item(0)->attributes AS $attributes) {
2382 if ($attributes->name == "ref") {
2383 $item["parent-uri"] = $attributes->textContent;
2388 // Get the type of the item (Top level post, reply or remote reply)
2389 $entrytype = self::get_entry_type($importer, $item);
2391 // Now assign the rest of the values that depend on the type of the message
2392 if (in_array($entrytype, array(DFRN_REPLY, DFRN_REPLY_RC))) {
2393 if (!isset($item["object-type"])) {
2394 $item["object-type"] = ACTIVITY_OBJ_COMMENT;
2397 if ($item["contact-id"] != $owner["contact-id"]) {
2398 $item["contact-id"] = $owner["contact-id"];
2401 if (($item["network"] != $owner["network"]) AND ($owner["network"] != "")) {
2402 $item["network"] = $owner["network"];
2405 if ($item["contact-id"] != $author["contact-id"]) {
2406 $item["contact-id"] = $author["contact-id"];
2409 if (($item["network"] != $author["network"]) AND ($author["network"] != "")) {
2410 $item["network"] = $author["network"];
2413 /// @TODO maybe remove this old-lost code then?
2414 // This code was taken from the old DFRN code
2415 // When activated, forums don't work.
2416 // And: Why should we disallow commenting by followers?
2417 // the behaviour is now similar to the Diaspora part.
2418 //if ($importer["rel"] == CONTACT_IS_FOLLOWER) {
2419 // logger("Contact ".$importer["id"]." is only follower. Quitting", LOGGER_DEBUG);
2424 if ($entrytype == DFRN_REPLY_RC) {
2425 $item["type"] = "remote-comment";
2427 } elseif ($entrytype == DFRN_TOP_LEVEL) {
2428 if (!isset($item["object-type"])) {
2429 $item["object-type"] = ACTIVITY_OBJ_NOTE;
2433 if ($item["object-type"] == ACTIVITY_OBJ_EVENT) {
2434 logger("Item ".$item["uri"]." seems to contain an event.", LOGGER_DEBUG);
2435 $ev = bbtoevent($item["body"]);
2436 if ((x($ev, "desc") || x($ev, "summary")) && x($ev, "start")) {
2437 logger("Event in item ".$item["uri"]." was found.", LOGGER_DEBUG);
2438 /// @TODO Mixure of "/' ahead ...
2439 $ev["cid"] = $importer["id"];
2440 $ev["uid"] = $importer["uid"];
2441 $ev["uri"] = $item["uri"];
2442 $ev["edited"] = $item["edited"];
2443 $ev['private'] = $item['private'];
2444 $ev["guid"] = $item["guid"];
2446 $r = q("SELECT `id` FROM `event` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2447 dbesc($item["uri"]),
2448 intval($importer["uid"])
2450 if (dbm::is_result($r)) {
2451 $ev["id"] = $r[0]["id"];
2454 $event_id = event_store($ev);
2455 logger("Event ".$event_id." was stored", LOGGER_DEBUG);
2461 if (!self::process_verbs($entrytype, $importer, $item, $is_like)) {
2462 logger("Exiting because 'process_verbs' told us so", LOGGER_DEBUG);
2466 // Update content if 'updated' changes
2467 if (dbm::is_result($current)) {
2468 if (self::update_content($r[0], $item, $importer, $entrytype)) {
2469 logger("Item ".$item["uri"]." was updated.", LOGGER_DEBUG);
2471 logger("Item ".$item["uri"]." already existed.", LOGGER_DEBUG);
2476 if (in_array($entrytype, array(DFRN_REPLY, DFRN_REPLY_RC))) {
2477 $posted_id = item_store($item);
2482 logger("Reply from contact ".$item["contact-id"]." was stored with id ".$posted_id, LOGGER_DEBUG);
2484 $item["id"] = $posted_id;
2486 $r = q("SELECT `parent`, `parent-uri` FROM `item` WHERE `id` = %d AND `uid` = %d LIMIT 1",
2488 intval($importer["importer_uid"])
2490 if (dbm::is_result($r)) {
2491 $parent = $r[0]["parent"];
2492 $parent_uri = $r[0]["parent-uri"];
2496 $r1 = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `uid` = %d AND `parent` = %d",
2497 dbesc(datetime_convert()),
2498 intval($importer["importer_uid"]),
2499 intval($r[0]["parent"])
2502 $r2 = q("UPDATE `item` SET `last-child` = 1, `changed` = '%s' WHERE `uid` = %d AND `id` = %d",
2503 dbesc(datetime_convert()),
2504 intval($importer["importer_uid"]),
2509 if ($posted_id AND $parent AND ($entrytype == DFRN_REPLY_RC)) {
2510 logger("Notifying followers about comment ".$posted_id, LOGGER_DEBUG);
2511 proc_run(PRIORITY_HIGH, "include/notifier.php", "comment-import", $posted_id);
2516 } else { // $entrytype == DFRN_TOP_LEVEL
2517 if (!link_compare($item["owner-link"],$importer["url"])) {
2519 * The item owner info is not our contact. It's OK and is to be expected if this is a tgroup delivery,
2520 * but otherwise there's a possible data mixup on the sender's system.
2521 * the tgroup delivery code called from item_store will correct it if it's a forum,
2522 * but we're going to unconditionally correct it here so that the post will always be owned by our contact.
2524 logger('Correcting item owner.', LOGGER_DEBUG);
2525 $item["owner-name"] = $importer["senderName"];
2526 $item["owner-link"] = $importer["url"];
2527 $item["owner-avatar"] = $importer["thumb"];
2530 if (($importer["rel"] == CONTACT_IS_FOLLOWER) && (!tgroup_check($importer["importer_uid"], $item))) {
2531 logger("Contact ".$importer["id"]." is only follower and tgroup check was negative.", LOGGER_DEBUG);
2535 // This is my contact on another system, but it's really me.
2536 // Turn this into a wall post.
2537 $notify = item_is_remote_self($importer, $item);
2539 $posted_id = item_store($item, false, $notify);
2541 logger("Item was stored with id ".$posted_id, LOGGER_DEBUG);
2543 if (stristr($item["verb"],ACTIVITY_POKE))
2544 self::do_poke($item, $importer, $posted_id);
2549 * @brief Deletes items
2551 * @param object $xpath XPath object
2552 * @param object $deletion deletion elements
2553 * @param array $importer Record of the importer user mixed with contact of the content
2554 * @todo set proper type-hints
2556 private static function process_deletion($xpath, $deletion, $importer) {
2558 logger("Processing deletions");
2560 foreach ($deletion->attributes AS $attributes) {
2561 if ($attributes->name == "ref") {
2562 $uri = $attributes->textContent;
2564 if ($attributes->name == "when") {
2565 $when = $attributes->textContent;
2569 $when = datetime_convert("UTC", "UTC", $when, "Y-m-d H:i:s");
2571 $when = datetime_convert("UTC", "UTC", "now", "Y-m-d H:i:s");
2574 if (!$uri OR !$importer["id"]) {
2578 /// @todo Only select the used fields
2579 $r = q("SELECT `item`.*, `contact`.`self` FROM `item` INNER JOIN `contact` on `item`.`contact-id` = `contact`.`id`
2580 WHERE `uri` = '%s' AND `item`.`uid` = %d AND `contact-id` = %d AND NOT `item`.`file` LIKE '%%[%%' LIMIT 1",
2582 intval($importer["uid"]),
2583 intval($importer["id"])
2585 if (!dbm::is_result($r)) {
2586 logger("Item with uri " . $uri . " from contact " . $importer["id"] . " for user " . $importer["uid"] . " wasn't found.", LOGGER_DEBUG);
2592 $entrytype = self::get_entry_type($importer, $item);
2594 if (!$item["deleted"]) {
2595 logger('deleting item '.$item["id"].' uri='.$uri, LOGGER_DEBUG);
2600 if ($item["object-type"] == ACTIVITY_OBJ_EVENT) {
2601 logger("Deleting event ".$item["event-id"], LOGGER_DEBUG);
2602 event_delete($item["event-id"]);
2605 if (($item["verb"] == ACTIVITY_TAG) && ($item["object-type"] == ACTIVITY_OBJ_TAGTERM)) {
2607 $xo = parse_xml_string($item["object"],false);
2608 $xt = parse_xml_string($item["target"],false);
2610 if ($xt->type == ACTIVITY_OBJ_NOTE) {
2611 $i = q("SELECT `id`, `contact-id`, `tag` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2613 intval($importer["importer_uid"])
2615 if (dbm::is_result($i)) {
2617 // For tags, the owner cannot remove the tag on the author's copy of the post.
2619 $owner_remove = (($item["contact-id"] == $i[0]["contact-id"]) ? true: false);
2620 $author_remove = (($item["origin"] && $item["self"]) ? true : false);
2621 $author_copy = (($item["origin"]) ? true : false);
2623 if ($owner_remove && $author_copy) {
2626 if ($author_remove || $owner_remove) {
2627 $tags = explode(',',$i[0]["tag"]);
2630 foreach ($tags as $tag) {
2631 if (trim($tag) !== trim($xo->body)) {
2632 $newtags[] = trim($tag);
2636 q("UPDATE `item` SET `tag` = '%s' WHERE `id` = %d",
2637 dbesc(implode(',', $newtags)),
2640 create_tags_from_item($i[0]["id"]);
2646 if ($entrytype == DFRN_TOP_LEVEL) {
2647 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s',
2648 `body` = '', `title` = ''
2649 WHERE `parent-uri` = '%s' AND `uid` = %d",
2651 dbesc(datetime_convert()),
2653 intval($importer["uid"])
2655 create_tags_from_itemuri($uri, $importer["uid"]);
2656 create_files_from_itemuri($uri, $importer["uid"]);
2657 update_thread_uri($uri, $importer["uid"]);
2659 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s',
2660 `body` = '', `title` = ''
2661 WHERE `uri` = '%s' AND `uid` = %d",
2663 dbesc(datetime_convert()),
2665 intval($importer["uid"])
2667 create_tags_from_itemuri($uri, $importer["uid"]);
2668 create_files_from_itemuri($uri, $importer["uid"]);
2669 update_thread_uri($uri, $importer["importer_uid"]);
2670 if ($item["last-child"]) {
2671 // ensure that last-child is set in case the comment that had it just got wiped.
2672 q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d ",
2673 dbesc(datetime_convert()),
2674 dbesc($item["parent-uri"]),
2675 intval($item["uid"])
2677 // who is the last child now?
2678 $r = q("SELECT `id` FROM `item` WHERE `parent-uri` = '%s' AND `type` != 'activity' AND `deleted` = 0 AND `moderated` = 0 AND `uid` = %d
2679 ORDER BY `created` DESC LIMIT 1",
2680 dbesc($item["parent-uri"]),
2681 intval($importer["uid"])
2683 if (dbm::is_result($r)) {
2684 q("UPDATE `item` SET `last-child` = 1 WHERE `id` = %d",
2689 // if this is a relayed delete, propagate it to other recipients
2691 if ($entrytype == DFRN_REPLY_RC) {
2692 logger("Notifying followers about deletion of post " . $item["id"], LOGGER_DEBUG);
2693 proc_run(PRIORITY_HIGH, "include/notifier.php","drop", $item["id"]);
2700 * @brief Imports a DFRN message
2702 * @param text $xml The DFRN message
2703 * @param array $importer Record of the importer user mixed with contact of the content
2704 * @param bool $sort_by_date Is used when feeds are polled
2705 * @todo set proper type-hints
2707 public static function import($xml,$importer, $sort_by_date = false) {
2713 if ($importer["readonly"]) {
2714 // We aren't receiving stuff from this person. But we will quietly ignore them
2715 // rather than a blatant "go away" message.
2716 logger('ignoring contact '.$importer["id"]);
2720 $doc = new DOMDocument();
2721 @$doc->loadXML($xml);
2723 $xpath = new DomXPath($doc);
2724 $xpath->registerNamespace("atom", NAMESPACE_ATOM1);
2725 $xpath->registerNamespace("thr", NAMESPACE_THREAD);
2726 $xpath->registerNamespace("at", NAMESPACE_TOMB);
2727 $xpath->registerNamespace("media", NAMESPACE_MEDIA);
2728 $xpath->registerNamespace("dfrn", NAMESPACE_DFRN);
2729 $xpath->registerNamespace("activity", NAMESPACE_ACTIVITY);
2730 $xpath->registerNamespace("georss", NAMESPACE_GEORSS);
2731 $xpath->registerNamespace("poco", NAMESPACE_POCO);
2732 $xpath->registerNamespace("ostatus", NAMESPACE_OSTATUS);
2733 $xpath->registerNamespace("statusnet", NAMESPACE_STATUSNET);
2736 $header["uid"] = $importer["uid"];
2737 $header["network"] = NETWORK_DFRN;
2738 $header["type"] = "remote";
2739 $header["wall"] = 0;
2740 $header["origin"] = 0;
2741 $header["contact-id"] = $importer["id"];
2743 // Update the contact table if the data has changed
2745 // The "atom:author" is only present in feeds
2746 if ($xpath->query("/atom:feed/atom:author")->length > 0) {
2747 self::fetchauthor($xpath, $doc->firstChild, $importer, "atom:author", false, $xml);
2750 // Only the "dfrn:owner" in the head section contains all data
2751 if ($xpath->query("/atom:feed/dfrn:owner")->length > 0) {
2752 self::fetchauthor($xpath, $doc->firstChild, $importer, "dfrn:owner", false, $xml);
2755 logger("Import DFRN message for user " . $importer["uid"] . " from contact " . $importer["id"], LOGGER_DEBUG);
2757 // The account type is new since 3.5.1
2758 if ($xpath->query("/atom:feed/dfrn:account_type")->length > 0) {
2759 $accounttype = intval($xpath->evaluate("/atom:feed/dfrn:account_type/text()", $context)->item(0)->nodeValue);
2761 if ($accounttype != $importer["contact-type"]) {
2762 /// @TODO this way is the norm or putting ); at the end of the line?
2763 q("UPDATE `contact` SET `contact-type` = %d WHERE `id` = %d",
2764 intval($accounttype),
2765 intval($importer["id"])
2770 // is it a public forum? Private forums aren't supported with this method
2771 // This is deprecated since 3.5.1
2772 $forum = intval($xpath->evaluate("/atom:feed/dfrn:community/text()", $context)->item(0)->nodeValue);
2774 if ($forum != $importer["forum"]) {
2775 q("UPDATE `contact` SET `forum` = %d WHERE `forum` != %d AND `id` = %d",
2776 intval($forum), intval($forum),
2777 intval($importer["id"])
2781 $mails = $xpath->query("/atom:feed/dfrn:mail");
2782 foreach ($mails AS $mail) {
2783 self::process_mail($xpath, $mail, $importer);
2786 $suggestions = $xpath->query("/atom:feed/dfrn:suggest");
2787 foreach ($suggestions AS $suggestion) {
2788 self::process_suggestion($xpath, $suggestion, $importer);
2791 $relocations = $xpath->query("/atom:feed/dfrn:relocate");
2792 foreach ($relocations AS $relocation) {
2793 self::process_relocation($xpath, $relocation, $importer);
2796 $deletions = $xpath->query("/atom:feed/at:deleted-entry");
2797 foreach ($deletions AS $deletion) {
2798 self::process_deletion($xpath, $deletion, $importer);
2801 if (!$sort_by_date) {
2802 $entries = $xpath->query("/atom:feed/atom:entry");
2803 foreach ($entries AS $entry) {
2804 self::process_entry($header, $xpath, $entry, $importer);
2807 $newentries = array();
2808 $entries = $xpath->query("/atom:feed/atom:entry");
2809 foreach ($entries AS $entry) {
2810 $created = $xpath->query("atom:published/text()", $entry)->item(0)->nodeValue;
2811 $newentries[strtotime($created)] = $entry;
2814 // Now sort after the publishing date
2817 foreach ($newentries AS $entry) {
2818 self::process_entry($header, $xpath, $entry, $importer);
2821 logger("Import done for user " . $importer["uid"] . " from contact " . $importer["id"], LOGGER_DEBUG);