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",
219 if (!dbm::is_result($r)) {
220 /// @TODO Some logging?
224 // Will check further below if this actually returned results.
225 // We will provide an empty feed if that is the case.
229 $doc = new DOMDocument('1.0', 'utf-8');
230 $doc->formatOutput = true;
232 $alternatelink = $owner['url'];
234 if (isset($category)) {
235 $alternatelink .= "/category/".$category;
239 $author = "dfrn:owner";
244 $root = self::add_header($doc, $owner, $author, $alternatelink, true);
246 // This hook can't work anymore
247 // call_hooks('atom_feed', $atom);
249 if (!count($items) OR $onlyheader) {
250 $atom = trim($doc->saveXML());
252 call_hooks('atom_feed_end', $atom);
257 foreach ($items as $item) {
259 // prevent private email from leaking.
260 if ($item['network'] == NETWORK_MAIL) {
264 // public feeds get html, our own nodes use bbcode
268 // catch any email that's in a public conversation and make sure it doesn't leak
269 if ($item['private']) {
276 $entry = self::entry($doc, $type, $item, $owner, true);
277 $root->appendChild($entry);
281 $atom = trim($doc->saveXML());
283 call_hooks('atom_feed_end', $atom);
289 * @brief Create XML text for DFRN mails
291 * @param array $item message elements
292 * @param array $owner Owner record
294 * @return string DFRN mail
295 * @todo Add type-hints
297 public static function mail($item, $owner) {
298 $doc = new DOMDocument('1.0', 'utf-8');
299 $doc->formatOutput = true;
301 $root = self::add_header($doc, $owner, "dfrn:owner", "", false);
303 $mail = $doc->createElement("dfrn:mail");
304 $sender = $doc->createElement("dfrn:sender");
306 xml::add_element($doc, $sender, "dfrn:name", $owner['name']);
307 xml::add_element($doc, $sender, "dfrn:uri", $owner['url']);
308 xml::add_element($doc, $sender, "dfrn:avatar", $owner['thumb']);
310 $mail->appendChild($sender);
312 xml::add_element($doc, $mail, "dfrn:id", $item['uri']);
313 xml::add_element($doc, $mail, "dfrn:in-reply-to", $item['parent-uri']);
314 xml::add_element($doc, $mail, "dfrn:sentdate", datetime_convert('UTC', 'UTC', $item['created'] . '+00:00' , ATOM_TIME));
315 xml::add_element($doc, $mail, "dfrn:subject", $item['title']);
316 xml::add_element($doc, $mail, "dfrn:content", $item['body']);
318 $root->appendChild($mail);
320 return(trim($doc->saveXML()));
324 * @brief Create XML text for DFRN friend suggestions
326 * @param array $item suggestion elements
327 * @param array $owner Owner record
329 * @return string DFRN suggestions
330 * @todo Add type-hints
332 public static function fsuggest($item, $owner) {
333 $doc = new DOMDocument('1.0', 'utf-8');
334 $doc->formatOutput = true;
336 $root = self::add_header($doc, $owner, "dfrn:owner", "", false);
338 $suggest = $doc->createElement("dfrn:suggest");
340 xml::add_element($doc, $suggest, "dfrn:url", $item['url']);
341 xml::add_element($doc, $suggest, "dfrn:name", $item['name']);
342 xml::add_element($doc, $suggest, "dfrn:photo", $item['photo']);
343 xml::add_element($doc, $suggest, "dfrn:request", $item['request']);
344 xml::add_element($doc, $suggest, "dfrn:note", $item['note']);
346 $root->appendChild($suggest);
348 return(trim($doc->saveXML()));
352 * @brief Create XML text for DFRN relocations
354 * @param array $owner Owner record
355 * @param int $uid User ID
357 * @return string DFRN relocations
358 * @todo Add type-hints
360 public static function relocate($owner, $uid) {
362 /* get site pubkey. this could be a new installation with no site keys*/
363 $pubkey = get_config('system','site_pubkey');
365 $res = new_keypair(1024);
366 set_config('system','site_prvkey', $res['prvkey']);
367 set_config('system','site_pubkey', $res['pubkey']);
370 $rp = q("SELECT `resource-id` , `scale`, type FROM `photo`
371 WHERE `profile` = 1 AND `uid` = %d ORDER BY scale;", $uid);
373 $ext = Photo::supportedTypes();
375 foreach ($rp as $p) {
376 $photos[$p['scale']] = app::get_baseurl().'/photo/'.$p['resource-id'].'-'.$p['scale'].'.'.$ext[$p['type']];
381 $doc = new DOMDocument('1.0', 'utf-8');
382 $doc->formatOutput = true;
384 $root = self::add_header($doc, $owner, "dfrn:owner", "", false);
386 $relocate = $doc->createElement("dfrn:relocate");
388 xml::add_element($doc, $relocate, "dfrn:url", $owner['url']);
389 xml::add_element($doc, $relocate, "dfrn:name", $owner['name']);
390 xml::add_element($doc, $relocate, "dfrn:addr", $owner['addr']);
391 xml::add_element($doc, $relocate, "dfrn:avatar", $owner['avatar']);
392 xml::add_element($doc, $relocate, "dfrn:photo", $photos[4]);
393 xml::add_element($doc, $relocate, "dfrn:thumb", $photos[5]);
394 xml::add_element($doc, $relocate, "dfrn:micro", $photos[6]);
395 xml::add_element($doc, $relocate, "dfrn:request", $owner['request']);
396 xml::add_element($doc, $relocate, "dfrn:confirm", $owner['confirm']);
397 xml::add_element($doc, $relocate, "dfrn:notify", $owner['notify']);
398 xml::add_element($doc, $relocate, "dfrn:poll", $owner['poll']);
399 xml::add_element($doc, $relocate, "dfrn:sitepubkey", get_config('system','site_pubkey'));
401 $root->appendChild($relocate);
403 return(trim($doc->saveXML()));
407 * @brief Adds the header elements for the DFRN protocol
409 * @param object $doc XML document
410 * @param array $owner Owner record
411 * @param string $authorelement Element name for the author
412 * @param string $alternatelink link to profile or category
413 * @param bool $public Is it a header for public posts?
415 * @return object XML root object
416 * @todo Add type-hints
418 private static function add_header($doc, $owner, $authorelement, $alternatelink = "", $public = false) {
420 if ($alternatelink == "") {
421 $alternatelink = $owner['url'];
424 $root = $doc->createElementNS(NAMESPACE_ATOM1, 'feed');
425 $doc->appendChild($root);
427 $root->setAttribute("xmlns:thr", NAMESPACE_THREAD);
428 $root->setAttribute("xmlns:at", NAMESPACE_TOMB);
429 $root->setAttribute("xmlns:media", NAMESPACE_MEDIA);
430 $root->setAttribute("xmlns:dfrn", NAMESPACE_DFRN);
431 $root->setAttribute("xmlns:activity", NAMESPACE_ACTIVITY);
432 $root->setAttribute("xmlns:georss", NAMESPACE_GEORSS);
433 $root->setAttribute("xmlns:poco", NAMESPACE_POCO);
434 $root->setAttribute("xmlns:ostatus", NAMESPACE_OSTATUS);
435 $root->setAttribute("xmlns:statusnet", NAMESPACE_STATUSNET);
437 xml::add_element($doc, $root, "id", app::get_baseurl()."/profile/".$owner["nick"]);
438 xml::add_element($doc, $root, "title", $owner["name"]);
440 $attributes = array("uri" => "https://friendi.ca", "version" => FRIENDICA_VERSION."-".DB_UPDATE_VERSION);
441 xml::add_element($doc, $root, "generator", FRIENDICA_PLATFORM, $attributes);
443 $attributes = array("rel" => "license", "href" => "http://creativecommons.org/licenses/by/3.0/");
444 xml::add_element($doc, $root, "link", "", $attributes);
446 $attributes = array("rel" => "alternate", "type" => "text/html", "href" => $alternatelink);
447 xml::add_element($doc, $root, "link", "", $attributes);
451 // DFRN itself doesn't uses this. But maybe someone else wants to subscribe to the public feed.
452 ostatus::hublinks($doc, $root);
454 $attributes = array("rel" => "salmon", "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-replies", "href" => app::get_baseurl()."/salmon/".$owner["nick"]);
458 xml::add_element($doc, $root, "link", "", $attributes);
460 $attributes = array("rel" => "http://salmon-protocol.org/ns/salmon-mention", "href" => app::get_baseurl()."/salmon/".$owner["nick"]);
461 xml::add_element($doc, $root, "link", "", $attributes);
464 // For backward compatibility we keep this element
465 if ($owner['page-flags'] == PAGE_COMMUNITY) {
466 xml::add_element($doc, $root, "dfrn:community", 1);
469 // The former element is replaced by this one
470 xml::add_element($doc, $root, "dfrn:account_type", $owner["account-type"]);
472 /// @todo We need a way to transmit the different page flags like "PAGE_PRVGROUP"
474 xml::add_element($doc, $root, "updated", datetime_convert("UTC", "UTC", "now", ATOM_TIME));
476 $author = self::add_author($doc, $owner, $authorelement, $public);
477 $root->appendChild($author);
483 * @brief Adds the author element in the header for the DFRN protocol
485 * @param object $doc XML document
486 * @param array $owner Owner record
487 * @param string $authorelement Element name for the author
489 * @return object XML author object
490 * @todo Add type-hints
492 private static function add_author($doc, $owner, $authorelement, $public) {
494 // Is the profile hidden or shouldn't be published in the net? Then add the "hide" element
495 $r = q("SELECT `id` FROM `profile` INNER JOIN `user` ON `user`.`uid` = `profile`.`uid`
496 WHERE (`hidewall` OR NOT `net-publish`) AND `user`.`uid` = %d",
497 intval($owner['uid']));
498 if (dbm::is_result($r)) {
504 $author = $doc->createElement($authorelement);
506 $namdate = datetime_convert('UTC', 'UTC', $owner['name-date'].'+00:00', ATOM_TIME);
507 $uridate = datetime_convert('UTC', 'UTC', $owner['uri-date'].'+00:00', ATOM_TIME);
508 $picdate = datetime_convert('UTC', 'UTC', $owner['avatar-date'].'+00:00', ATOM_TIME);
510 $attributes = array();
512 if (!$public OR !$hidewall) {
513 $attributes = array("dfrn:updated" => $namdate);
516 xml::add_element($doc, $author, "name", $owner["name"], $attributes);
517 xml::add_element($doc, $author, "uri", app::get_baseurl().'/profile/'.$owner["nickname"], $attributes);
518 xml::add_element($doc, $author, "dfrn:handle", $owner["addr"], $attributes);
520 $attributes = array("rel" => "photo", "type" => "image/jpeg",
521 "media:width" => 175, "media:height" => 175, "href" => $owner['photo']);
523 if (!$public OR !$hidewall) {
524 $attributes["dfrn:updated"] = $picdate;
527 xml::add_element($doc, $author, "link", "", $attributes);
529 $attributes["rel"] = "avatar";
530 xml::add_element($doc, $author, "link", "", $attributes);
533 xml::add_element($doc, $author, "dfrn:hide", "true");
536 // The following fields will only be generated if the data isn't meant for a public feed
541 $birthday = feed_birthday($owner['uid'], $owner['timezone']);
544 xml::add_element($doc, $author, "dfrn:birthday", $birthday);
546 // Only show contact details when we are allowed to
547 $r = q("SELECT `profile`.`about`, `profile`.`name`, `profile`.`homepage`, `user`.`nickname`,
548 `user`.`timezone`, `profile`.`locality`, `profile`.`region`, `profile`.`country-name`,
549 `profile`.`pub_keywords`, `profile`.`xmpp`, `profile`.`dob`
551 INNER JOIN `user` ON `user`.`uid` = `profile`.`uid`
552 WHERE `profile`.`is-default` AND NOT `user`.`hidewall` AND `user`.`uid` = %d",
553 intval($owner['uid']));
554 if (dbm::is_result($r)) {
557 xml::add_element($doc, $author, "poco:displayName", $profile["name"]);
558 xml::add_element($doc, $author, "poco:updated", $namdate);
560 if (trim($profile["dob"]) != "0000-00-00")
561 xml::add_element($doc, $author, "poco:birthday", "0000-".date("m-d", strtotime($profile["dob"])));
563 xml::add_element($doc, $author, "poco:note", $profile["about"]);
564 xml::add_element($doc, $author, "poco:preferredUsername", $profile["nickname"]);
566 $savetz = date_default_timezone_get();
567 date_default_timezone_set($profile["timezone"]);
568 xml::add_element($doc, $author, "poco:utcOffset", date("P"));
569 date_default_timezone_set($savetz);
571 if (trim($profile["homepage"]) != "") {
572 $urls = $doc->createElement("poco:urls");
573 xml::add_element($doc, $urls, "poco:type", "homepage");
574 xml::add_element($doc, $urls, "poco:value", $profile["homepage"]);
575 xml::add_element($doc, $urls, "poco:primary", "true");
576 $author->appendChild($urls);
579 if (trim($profile["pub_keywords"]) != "") {
580 $keywords = explode(",", $profile["pub_keywords"]);
582 foreach ($keywords AS $keyword) {
583 xml::add_element($doc, $author, "poco:tags", trim($keyword));
588 if (trim($profile["xmpp"]) != "") {
589 $ims = $doc->createElement("poco:ims");
590 xml::add_element($doc, $ims, "poco:type", "xmpp");
591 xml::add_element($doc, $ims, "poco:value", $profile["xmpp"]);
592 xml::add_element($doc, $ims, "poco:primary", "true");
593 $author->appendChild($ims);
596 if (trim($profile["locality"].$profile["region"].$profile["country-name"]) != "") {
597 $element = $doc->createElement("poco:address");
599 xml::add_element($doc, $element, "poco:formatted", formatted_location($profile));
601 if (trim($profile["locality"]) != "") {
602 xml::add_element($doc, $element, "poco:locality", $profile["locality"]);
605 if (trim($profile["region"]) != "") {
606 xml::add_element($doc, $element, "poco:region", $profile["region"]);
609 if (trim($profile["country-name"]) != "") {
610 xml::add_element($doc, $element, "poco:country", $profile["country-name"]);
613 $author->appendChild($element);
621 * @brief Adds the author elements in the "entry" elements of the DFRN protocol
623 * @param object $doc XML document
624 * @param string $element Element name for the author
625 * @param string $contact_url Link of the contact
626 * @param array $items Item elements
628 * @return object XML author object
629 * @todo Add type-hints
631 private static function add_entry_author($doc, $element, $contact_url, $item) {
633 $contact = get_contact_details_by_url($contact_url, $item["uid"]);
635 $author = $doc->createElement($element);
636 xml::add_element($doc, $author, "name", $contact["name"]);
637 xml::add_element($doc, $author, "uri", $contact["url"]);
638 xml::add_element($doc, $author, "dfrn:handle", $contact["addr"]);
641 /// - Check real image type and image size
642 /// - Check which of these boths elements we should use
645 "type" => "image/jpeg",
647 "media:height" => 80,
648 "href" => $contact["photo"]);
649 xml::add_element($doc, $author, "link", "", $attributes);
653 "type" => "image/jpeg",
655 "media:height" => 80,
656 "href" => $contact["photo"]);
657 xml::add_element($doc, $author, "link", "", $attributes);
663 * @brief Adds the activity elements
665 * @param object $doc XML document
666 * @param string $element Element name for the activity
667 * @param string $activity activity value
669 * @return object XML activity object
670 * @todo Add type-hints
672 private static function create_activity($doc, $element, $activity) {
675 $entry = $doc->createElement($element);
677 $r = parse_xml_string($activity, false);
682 xml::add_element($doc, $entry, "activity:object-type", $r->type);
685 xml::add_element($doc, $entry, "id", $r->id);
688 xml::add_element($doc, $entry, "title", $r->title);
692 if (substr($r->link, 0, 1) == '<') {
693 if (strstr($r->link, '&') && (! strstr($r->link, '&'))) {
694 $r->link = str_replace('&', '&', $r->link);
697 $r->link = preg_replace('/\<link(.*?)\"\>/', '<link$1"/>', $r->link);
699 // XML does need a single element as root element so we add a dummy element here
700 $data = parse_xml_string("<dummy>" . $r->link . "</dummy>", false);
701 if (is_object($data)) {
702 foreach ($data->link AS $link) {
703 $attributes = array();
704 foreach ($link->attributes() AS $parameter => $value) {
705 $attributes[$parameter] = $value;
707 xml::add_element($doc, $entry, "link", "", $attributes);
711 $attributes = array("rel" => "alternate", "type" => "text/html", "href" => $r->link);
712 xml::add_element($doc, $entry, "link", "", $attributes);
716 xml::add_element($doc, $entry, "content", bbcode($r->content), array("type" => "html"));
726 * @brief Adds the elements for attachments
728 * @param object $doc XML document
729 * @param object $root XML root
730 * @param array $item Item element
732 * @return object XML attachment object
733 * @todo Add type-hints
735 private static function get_attachment($doc, $root, $item) {
736 $arr = explode('[/attach],',$item['attach']);
738 foreach ($arr as $r) {
740 $cnt = preg_match('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\" title=\"(.*?)\"|',$r,$matches);
742 $attributes = array("rel" => "enclosure",
743 "href" => $matches[1],
744 "type" => $matches[3]);
746 if (intval($matches[2])) {
747 $attributes["length"] = intval($matches[2]);
750 if (trim($matches[4]) != "") {
751 $attributes["title"] = trim($matches[4]);
754 xml::add_element($doc, $root, "link", "", $attributes);
761 * @brief Adds the "entry" elements for the DFRN protocol
763 * @param object $doc XML document
764 * @param string $type "text" or "html"
765 * @param array $item Item element
766 * @param array $owner Owner record
767 * @param bool $comment Trigger the sending of the "comment" element
768 * @param int $cid Contact ID of the recipient
770 * @return object XML entry object
771 * @todo Add type-hints
773 private static function entry($doc, $type, $item, $owner, $comment = false, $cid = 0) {
775 $mentioned = array();
777 if (!$item['parent']) {
781 if ($item['deleted']) {
782 $attributes = array("ref" => $item['uri'], "when" => datetime_convert('UTC','UTC',$item['edited'] . '+00:00',ATOM_TIME));
783 return xml::create_element($doc, "at:deleted-entry", "", $attributes);
786 $entry = $doc->createElement("entry");
788 if ($item['allow_cid'] || $item['allow_gid'] || $item['deny_cid'] || $item['deny_gid']) {
789 $body = fix_private_photos($item['body'],$owner['uid'],$item,$cid);
791 $body = $item['body'];
794 // Remove the abstract element. It is only locally important.
795 $body = remove_abstract($body);
797 if ($type == 'html') {
800 if ($item['title'] != "") {
801 $htmlbody = "[b]".$item['title']."[/b]\n\n".$htmlbody;
804 $htmlbody = bbcode($htmlbody, false, false, 7);
807 $author = self::add_entry_author($doc, "author", $item["author-link"], $item);
808 $entry->appendChild($author);
810 $dfrnowner = self::add_entry_author($doc, "dfrn:owner", $item["owner-link"], $item);
811 $entry->appendChild($dfrnowner);
813 if (($item['parent'] != $item['id']) || ($item['parent-uri'] !== $item['uri']) || (($item['thr-parent'] !== '') && ($item['thr-parent'] !== $item['uri']))) {
814 $parent = q("SELECT `guid` FROM `item` WHERE `id` = %d", intval($item["parent"]));
815 $parent_item = (($item['thr-parent']) ? $item['thr-parent'] : $item['parent-uri']);
816 $attributes = array("ref" => $parent_item, "type" => "text/html",
817 "href" => app::get_baseurl().'/display/'.$parent[0]['guid'],
818 "dfrn:diaspora_guid" => $parent[0]['guid']);
819 xml::add_element($doc, $entry, "thr:in-reply-to", "", $attributes);
822 xml::add_element($doc, $entry, "id", $item["uri"]);
823 xml::add_element($doc, $entry, "title", $item["title"]);
825 xml::add_element($doc, $entry, "published", datetime_convert("UTC","UTC",$item["created"]."+00:00",ATOM_TIME));
826 xml::add_element($doc, $entry, "updated", datetime_convert("UTC","UTC",$item["edited"]."+00:00",ATOM_TIME));
828 // "dfrn:env" is used to read the content
829 xml::add_element($doc, $entry, "dfrn:env", base64url_encode($body, true));
831 // The "content" field is not read by the receiver. We could remove it when the type is "text"
832 // We keep it at the moment, maybe there is some old version that doesn't read "dfrn:env"
833 xml::add_element($doc, $entry, "content", (($type == 'html') ? $htmlbody : $body), array("type" => $type));
835 // We save this value in "plink". Maybe we should read it from there as well?
836 xml::add_element($doc, $entry, "link", "", array("rel" => "alternate", "type" => "text/html",
837 "href" => app::get_baseurl()."/display/".$item["guid"]));
839 // "comment-allow" is some old fashioned stuff for old Friendica versions.
840 // It is included in the rewritten code for completeness
842 xml::add_element($doc, $entry, "dfrn:comment-allow", intval($item['last-child']));
845 if ($item['location']) {
846 xml::add_element($doc, $entry, "dfrn:location", $item['location']);
849 if ($item['coord']) {
850 xml::add_element($doc, $entry, "georss:point", $item['coord']);
853 if (($item['private']) || strlen($item['allow_cid']) || strlen($item['allow_gid']) || strlen($item['deny_cid']) || strlen($item['deny_gid'])) {
854 xml::add_element($doc, $entry, "dfrn:private", (($item['private']) ? $item['private'] : 1));
857 if ($item['extid']) {
858 xml::add_element($doc, $entry, "dfrn:extid", $item['extid']);
861 if ($item['bookmark']) {
862 xml::add_element($doc, $entry, "dfrn:bookmark", "true");
866 xml::add_element($doc, $entry, "statusnet:notice_info", "", array("local_id" => $item['id'], "source" => $item['app']));
869 xml::add_element($doc, $entry, "dfrn:diaspora_guid", $item["guid"]);
871 // The signed text contains the content in Markdown, the sender handle and the signatur for the content
872 // It is needed for relayed comments to Diaspora.
873 if($item['signed_text']) {
874 $sign = base64_encode(json_encode(array('signed_text' => $item['signed_text'],'signature' => $item['signature'],'signer' => $item['signer'])));
875 xml::add_element($doc, $entry, "dfrn:diaspora_signature", $sign);
878 xml::add_element($doc, $entry, "activity:verb", construct_verb($item));
880 if ($item['object-type'] != "") {
881 xml::add_element($doc, $entry, "activity:object-type", $item['object-type']);
882 } elseif ($item['id'] == $item['parent']) {
883 xml::add_element($doc, $entry, "activity:object-type", ACTIVITY_OBJ_NOTE);
885 xml::add_element($doc, $entry, "activity:object-type", ACTIVITY_OBJ_COMMENT);
888 $actobj = self::create_activity($doc, "activity:object", $item['object']);
890 $entry->appendChild($actobj);
893 $actarg = self::create_activity($doc, "activity:target", $item['target']);
895 $entry->appendChild($actarg);
898 $tags = item_getfeedtags($item);
901 foreach ($tags as $t) {
902 if (($type != 'html') OR ($t[0] != "@")) {
903 xml::add_element($doc, $entry, "category", "", array("scheme" => "X-DFRN:".$t[0].":".$t[1], "term" => $t[2]));
909 foreach ($tags as $t) {
911 $mentioned[$t[1]] = $t[1];
916 foreach ($mentioned AS $mention) {
917 $r = q("SELECT `forum`, `prv` FROM `contact` WHERE `uid` = %d AND `nurl` = '%s'",
918 intval($owner["uid"]),
919 dbesc(normalise_link($mention)));
921 if (!dbm::is_result($r)) {
922 /// @TODO Maybe some logging?
926 if ($r[0]["forum"] OR $r[0]["prv"]) {
927 xml::add_element($doc, $entry, "link", "", array("rel" => "mentioned",
928 "ostatus:object-type" => ACTIVITY_OBJ_GROUP,
929 "href" => $mention));
931 xml::add_element($doc, $entry, "link", "", array("rel" => "mentioned",
932 "ostatus:object-type" => ACTIVITY_OBJ_PERSON,
933 "href" => $mention));
937 self::get_attachment($doc, $entry, $item);
943 * @brief Delivers the atom content to the contacts
945 * @param array $owner Owner record
946 * @param array $contactr Contact record of the receiver
947 * @param string $atom Content that will be transmitted
948 * @param bool $dissolve (to be documented)
950 * @return int Deliver status. -1 means an error.
951 * @todo Add array type-hint for $owner, $contact
953 public static function deliver($owner,$contact,$atom, $dissolve = false) {
957 $idtosend = $orig_id = (($contact['dfrn-id']) ? $contact['dfrn-id'] : $contact['issued-id']);
959 if ($contact['duplex'] && $contact['dfrn-id']) {
960 $idtosend = '0:' . $orig_id;
962 if ($contact['duplex'] && $contact['issued-id']) {
963 $idtosend = '1:' . $orig_id;
966 $rino = get_config('system','rino_encrypt');
967 $rino = intval($rino);
969 // use RINO1 if mcrypt isn't installed and RINO2 was selected
970 if ($rino==2 and !function_exists('mcrypt_create_iv')) {
974 logger("Local rino version: ". $rino, LOGGER_DEBUG);
976 $ssl_val = intval(get_config('system','ssl_policy'));
980 case SSL_POLICY_FULL:
981 $ssl_policy = 'full';
983 case SSL_POLICY_SELFSIGN:
984 $ssl_policy = 'self';
986 case SSL_POLICY_NONE:
988 $ssl_policy = 'none';
992 $url = $contact['notify'] . '&dfrn_id=' . $idtosend . '&dfrn_version=' . DFRN_PROTOCOL_VERSION . (($rino) ? '&rino='.$rino : '');
994 logger('dfrn_deliver: ' . $url);
996 $ret = z_fetch_url($url);
998 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
999 return -2; // timed out
1002 $xml = $ret['body'];
1004 $curl_stat = $a->get_curl_code();
1006 return -3; // timed out
1009 logger('dfrn_deliver: ' . $xml, LOGGER_DATA);
1015 if (strpos($xml,'<?xml') === false) {
1016 logger('dfrn_deliver: no valid XML returned');
1017 logger('dfrn_deliver: returned XML: ' . $xml, LOGGER_DATA);
1021 $res = parse_xml_string($xml);
1023 if ((intval($res->status) != 0) || (! strlen($res->challenge)) || (! strlen($res->dfrn_id))) {
1024 return (($res->status) ? $res->status : 3);
1027 $postvars = array();
1028 $sent_dfrn_id = hex2bin((string) $res->dfrn_id);
1029 $challenge = hex2bin((string) $res->challenge);
1030 $perm = (($res->perm) ? $res->perm : null);
1031 $dfrn_version = (float) (($res->dfrn_version) ? $res->dfrn_version : 2.0);
1032 $rino_remote_version = intval($res->rino);
1033 $page = (($owner['page-flags'] == PAGE_COMMUNITY) ? 1 : 0);
1035 logger("Remote rino version: ".$rino_remote_version." for ".$contact["url"], LOGGER_DEBUG);
1037 if ($owner['page-flags'] == PAGE_PRVGROUP) {
1041 $final_dfrn_id = '';
1044 if ((($perm == 'rw') && (! intval($contact['writable'])))
1045 || (($perm == 'r') && (intval($contact['writable'])))) {
1046 q("update contact set writable = %d where id = %d",
1047 intval(($perm == 'rw') ? 1 : 0),
1048 intval($contact['id'])
1050 $contact['writable'] = (string) 1 - intval($contact['writable']);
1054 if (($contact['duplex'] && strlen($contact['pubkey']))
1055 || ($owner['page-flags'] == PAGE_COMMUNITY && strlen($contact['pubkey']))
1056 || ($contact['rel'] == CONTACT_IS_SHARING && strlen($contact['pubkey']))) {
1057 openssl_public_decrypt($sent_dfrn_id,$final_dfrn_id,$contact['pubkey']);
1058 openssl_public_decrypt($challenge,$postvars['challenge'],$contact['pubkey']);
1060 openssl_private_decrypt($sent_dfrn_id,$final_dfrn_id,$contact['prvkey']);
1061 openssl_private_decrypt($challenge,$postvars['challenge'],$contact['prvkey']);
1064 $final_dfrn_id = substr($final_dfrn_id, 0, strpos($final_dfrn_id, '.'));
1066 if (strpos($final_dfrn_id,':') == 1) {
1067 $final_dfrn_id = substr($final_dfrn_id,2);
1070 if ($final_dfrn_id != $orig_id) {
1071 logger('dfrn_deliver: wrong dfrn_id.');
1072 // did not decode properly - cannot trust this site
1076 $postvars['dfrn_id'] = $idtosend;
1077 $postvars['dfrn_version'] = DFRN_PROTOCOL_VERSION;
1079 $postvars['dissolve'] = '1';
1083 if ((($contact['rel']) && ($contact['rel'] != CONTACT_IS_SHARING) && (! $contact['blocked'])) || ($owner['page-flags'] == PAGE_COMMUNITY)) {
1084 $postvars['data'] = $atom;
1085 $postvars['perm'] = 'rw';
1087 $postvars['data'] = str_replace('<dfrn:comment-allow>1','<dfrn:comment-allow>0',$atom);
1088 $postvars['perm'] = 'r';
1091 $postvars['ssl_policy'] = $ssl_policy;
1094 $postvars['page'] = $page;
1098 if ($rino>0 && $rino_remote_version>0 && (! $dissolve)) {
1099 logger('rino version: '. $rino_remote_version);
1101 switch($rino_remote_version) {
1103 // Deprecated rino version!
1104 $key = substr(random_string(),0,16);
1105 $data = aes_encrypt($postvars['data'],$key);
1108 // RINO 2 based on php-encryption
1110 $key = Crypto::createNewRandomKey();
1111 } catch (CryptoTestFailed $ex) {
1112 logger('Cannot safely create a key');
1114 } catch (CannotPerformOperation $ex) {
1115 logger('Cannot safely create a key');
1119 $data = Crypto::encrypt($postvars['data'], $key);
1120 } catch (CryptoTestFailed $ex) {
1121 logger('Cannot safely perform encryption');
1123 } catch (CannotPerformOperation $ex) {
1124 logger('Cannot safely perform encryption');
1129 logger("rino: invalid requested verision '$rino_remote_version'");
1133 $postvars['rino'] = $rino_remote_version;
1134 $postvars['data'] = bin2hex($data);
1136 //logger('rino: sent key = ' . $key, LOGGER_DEBUG);
1139 if ($dfrn_version >= 2.1) {
1140 if (($contact['duplex'] && strlen($contact['pubkey'])) {
1141 || ($owner['page-flags'] == PAGE_COMMUNITY && strlen($contact['pubkey']))
1142 || ($contact['rel'] == CONTACT_IS_SHARING && strlen($contact['pubkey'])))
1144 openssl_public_encrypt($key,$postvars['key'],$contact['pubkey']);
1146 openssl_private_encrypt($key,$postvars['key'],$contact['prvkey']);
1150 if (($contact['duplex'] && strlen($contact['prvkey'])) || ($owner['page-flags'] == PAGE_COMMUNITY)) {
1151 openssl_private_encrypt($key,$postvars['key'],$contact['prvkey']);
1153 openssl_public_encrypt($key,$postvars['key'],$contact['pubkey']);
1158 logger('md5 rawkey ' . md5($postvars['key']));
1160 $postvars['key'] = bin2hex($postvars['key']);
1164 logger('dfrn_deliver: ' . "SENDING: " . print_r($postvars,true), LOGGER_DATA);
1166 $xml = post_url($contact['notify'], $postvars);
1168 logger('dfrn_deliver: ' . "RECEIVED: " . $xml, LOGGER_DATA);
1170 $curl_stat = $a->get_curl_code();
1171 if ((!$curl_stat) || (!strlen($xml))) {
1172 return -9; // timed out
1175 if (($curl_stat == 503) && (stristr($a->get_curl_headers(),'retry-after'))) {
1179 if (strpos($xml,'<?xml') === false) {
1180 logger('dfrn_deliver: phase 2: no valid XML returned');
1181 logger('dfrn_deliver: phase 2: returned XML: ' . $xml, LOGGER_DATA);
1185 if ($contact['term-date'] > NULL_DATE) {
1186 logger("dfrn_deliver: $url back from the dead - removing mark for death");
1187 require_once('include/Contact.php');
1188 unmark_for_death($contact);
1191 $res = parse_xml_string($xml);
1193 return $res->status;
1197 * @brief Add new birthday event for this person
1199 * @param array $contact Contact record
1200 * @param string $birthday Birthday of the contact
1201 * @todo Add array type-hint for $contact
1203 private static function birthday_event($contact, $birthday) {
1205 // Check for duplicates
1206 $r = q("SELECT `id` FROM `event` WHERE `uid` = %d AND `cid` = %d AND `start` = '%s' AND `type` = '%s' LIMIT 1",
1207 intval($contact["uid"]),
1208 intval($contact["id"]),
1209 dbesc(datetime_convert("UTC","UTC", $birthday)),
1212 if (dbm::is_result($r)) {
1216 logger("updating birthday: ".$birthday." for contact ".$contact["id"]);
1218 $bdtext = sprintf(t("%s\'s birthday"), $contact["name"]);
1219 $bdtext2 = sprintf(t("Happy Birthday %s"), " [url=".$contact["url"]."]".$contact["name"]."[/url]") ;
1221 $r = q("INSERT INTO `event` (`uid`,`cid`,`created`,`edited`,`start`,`finish`,`summary`,`desc`,`type`)
1222 VALUES ( %d, %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s') ",
1223 intval($contact["uid"]),
1224 intval($contact["id"]),
1225 dbesc(datetime_convert()),
1226 dbesc(datetime_convert()),
1227 dbesc(datetime_convert("UTC","UTC", $birthday)),
1228 dbesc(datetime_convert("UTC","UTC", $birthday." + 1 day ")),
1236 * @brief Fetch the author data from head or entry items
1238 * @param object $xpath XPath object
1239 * @param object $context In which context should the data be searched
1240 * @param array $importer Record of the importer user mixed with contact of the content
1241 * @param string $element Element name from which the data is fetched
1242 * @param bool $onlyfetch Should the data only be fetched or should it update the contact record as well
1244 * @return Returns an array with relevant data of the author
1245 * @todo Find good type-hints for all parameter
1247 private static function fetchauthor($xpath, $context, $importer, $element, $onlyfetch, $xml = "") {
1250 $author["name"] = $xpath->evaluate($element."/atom:name/text()", $context)->item(0)->nodeValue;
1251 $author["link"] = $xpath->evaluate($element."/atom:uri/text()", $context)->item(0)->nodeValue;
1253 $r = q("SELECT `id`, `uid`, `url`, `network`, `avatar-date`, `name-date`, `uri-date`, `addr`,
1254 `name`, `nick`, `about`, `location`, `keywords`, `xmpp`, `bdyear`, `bd`, `hidden`, `contact-type`
1255 FROM `contact` WHERE `uid` = %d AND `nurl` = '%s' AND `network` != '%s'",
1256 intval($importer["uid"]), dbesc(normalise_link($author["link"])), dbesc(NETWORK_STATUSNET));
1258 if (dbm::is_result($r)) {
1260 $author["contact-id"] = $r[0]["id"];
1261 $author["network"] = $r[0]["network"];
1264 logger("Contact ".$author["link"]." wasn't found for user ".$importer["uid"]." XML: ".$xml, LOGGER_DEBUG);
1267 $author["contact-id"] = $importer["id"];
1268 $author["network"] = $importer["network"];
1272 // Until now we aren't serving different sizes - but maybe later
1273 $avatarlist = array();
1274 /// @todo check if "avatar" or "photo" would be the best field in the specification
1275 $avatars = $xpath->query($element."/atom:link[@rel='avatar']", $context);
1276 foreach ($avatars AS $avatar) {
1279 foreach ($avatar->attributes AS $attributes) {
1280 /// @TODO Rewrite these similar if() to one switch
1281 if ($attributes->name == "href") {
1282 $href = $attributes->textContent;
1284 if ($attributes->name == "width") {
1285 $width = $attributes->textContent;
1287 if ($attributes->name == "updated") {
1288 $contact["avatar-date"] = $attributes->textContent;
1291 if (($width > 0) AND ($href != "")) {
1292 $avatarlist[$width] = $href;
1295 if (count($avatarlist) > 0) {
1296 krsort($avatarlist);
1297 $author["avatar"] = current($avatarlist);
1300 if (dbm::is_result($r) AND !$onlyfetch) {
1301 logger("Check if contact details for contact ".$r[0]["id"]." (".$r[0]["nick"].") have to be updated.", LOGGER_DEBUG);
1303 $poco = array("url" => $contact["url"]);
1305 // When was the last change to name or uri?
1306 $name_element = $xpath->query($element."/atom:name", $context)->item(0);
1307 foreach ($name_element->attributes AS $attributes) {
1308 if ($attributes->name == "updated") {
1309 $poco["name-date"] = $attributes->textContent;
1313 $link_element = $xpath->query($element."/atom:link", $context)->item(0);
1314 foreach ($link_element->attributes AS $attributes) {
1315 if ($attributes->name == "updated") {
1316 $poco["uri-date"] = $attributes->textContent;
1320 // Update contact data
1321 $value = $xpath->evaluate($element."/dfrn:handle/text()", $context)->item(0)->nodeValue;
1323 $poco["addr"] = $value;
1326 $value = $xpath->evaluate($element."/poco:displayName/text()", $context)->item(0)->nodeValue;
1328 $poco["name"] = $value;
1331 $value = $xpath->evaluate($element."/poco:preferredUsername/text()", $context)->item(0)->nodeValue;
1333 $poco["nick"] = $value;
1336 $value = $xpath->evaluate($element."/poco:note/text()", $context)->item(0)->nodeValue;
1338 $poco["about"] = $value;
1341 $value = $xpath->evaluate($element."/poco:address/poco:formatted/text()", $context)->item(0)->nodeValue;
1343 $poco["location"] = $value;
1346 /// @todo Only search for elements with "poco:type" = "xmpp"
1347 $value = $xpath->evaluate($element."/poco:ims/poco:value/text()", $context)->item(0)->nodeValue;
1349 $poco["xmpp"] = $value;
1352 /// @todo Add support for the following fields that we don't support by now in the contact table:
1353 /// - poco:utcOffset
1359 // If the "hide" element is present then the profile isn't searchable.
1360 $hide = intval($xpath->evaluate($element."/dfrn:hide/text()", $context)->item(0)->nodeValue == "true");
1362 logger("Hidden status for contact ".$contact["url"].": ".$hide, LOGGER_DEBUG);
1364 // If the contact isn't searchable then set the contact to "hidden".
1365 // Problem: This can be manually overridden by the user.
1367 $contact["hidden"] = true;
1370 // Save the keywords into the contact table
1372 $tagelements = $xpath->evaluate($element."/poco:tags/text()", $context);
1373 foreach ($tagelements AS $tag) {
1374 $tags[$tag->nodeValue] = $tag->nodeValue;
1378 $poco["keywords"] = implode(", ", $tags);
1381 // "dfrn:birthday" contains the birthday converted to UTC
1382 $old_bdyear = $contact["bdyear"];
1384 $birthday = $xpath->evaluate($element."/dfrn:birthday/text()", $context)->item(0)->nodeValue;
1386 if (strtotime($birthday) > time()) {
1387 $bd_timestamp = strtotime($birthday);
1389 $poco["bdyear"] = date("Y", $bd_timestamp);
1392 // "poco:birthday" is the birthday in the format "yyyy-mm-dd"
1393 $value = $xpath->evaluate($element."/poco:birthday/text()", $context)->item(0)->nodeValue;
1395 if (!in_array($value, array("", "0000-00-00"))) {
1396 $bdyear = date("Y");
1397 $value = str_replace("0000", $bdyear, $value);
1399 if (strtotime($value) < time()) {
1400 $value = str_replace($bdyear, $bdyear + 1, $value);
1401 $bdyear = $bdyear + 1;
1404 $poco["bd"] = $value;
1407 $contact = array_merge($contact, $poco);
1409 if ($old_bdyear != $contact["bdyear"]) {
1410 self::birthday_event($contact, $birthday);
1413 // Get all field names
1415 foreach ($r[0] AS $field => $data) {
1416 $fields[$field] = $data;
1419 unset($fields["id"]);
1420 unset($fields["uid"]);
1421 unset($fields["url"]);
1422 unset($fields["avatar-date"]);
1423 unset($fields["name-date"]);
1424 unset($fields["uri-date"]);
1426 // Update check for this field has to be done differently
1427 $datefields = array("name-date", "uri-date");
1428 foreach ($datefields AS $field) {
1429 if (strtotime($contact[$field]) > strtotime($r[0][$field])) {
1430 logger("Difference for contact ".$contact["id"]." in field '".$field."'. New value: '".$contact[$field]."', old value '".$r[0][$field]."'", LOGGER_DEBUG);
1435 foreach ($fields AS $field => $data) {
1436 if ($contact[$field] != $r[0][$field]) {
1437 logger("Difference for contact ".$contact["id"]." in field '".$field."'. New value: '".$contact[$field]."', old value '".$r[0][$field]."'", LOGGER_DEBUG);
1443 logger("Update contact data for contact ".$contact["id"]." (".$contact["nick"].")", LOGGER_DEBUG);
1445 q("UPDATE `contact` SET `name` = '%s', `nick` = '%s', `about` = '%s', `location` = '%s',
1446 `addr` = '%s', `keywords` = '%s', `bdyear` = '%s', `bd` = '%s', `hidden` = %d,
1447 `xmpp` = '%s', `name-date` = '%s', `uri-date` = '%s'
1448 WHERE `id` = %d AND `network` = '%s'",
1449 dbesc($contact["name"]), dbesc($contact["nick"]), dbesc($contact["about"]), dbesc($contact["location"]),
1450 dbesc($contact["addr"]), dbesc($contact["keywords"]), dbesc($contact["bdyear"]),
1451 dbesc($contact["bd"]), intval($contact["hidden"]), dbesc($contact["xmpp"]),
1452 dbesc($contact["name-date"]), dbesc($contact["uri-date"]),
1453 intval($contact["id"]), dbesc($contact["network"]));
1456 update_contact_avatar($author["avatar"], $importer["uid"], $contact["id"],
1457 (strtotime($contact["avatar-date"]) > strtotime($r[0]["avatar-date"])));
1459 // The generation is a sign for the reliability of the provided data.
1460 // It is used in the socgraph.php to prevent that old contact data
1461 // that was relayed over several servers can overwrite contact
1462 // data that we received directly.
1464 $poco["generation"] = 2;
1465 $poco["photo"] = $author["avatar"];
1466 $poco["hide"] = $hide;
1467 $poco["contact-type"] = $contact["contact-type"];
1468 update_gcontact($poco);
1475 * @brief Transforms activity objects into an XML string
1477 * @param object $xpath XPath object
1478 * @param object $activity Activity object
1479 * @param text $element element name
1481 * @return string XML string
1482 * @todo Find good type-hints for all parameter
1484 private static function transform_activity($xpath, $activity, $element) {
1485 if (!is_object($activity)) {
1489 $obj_doc = new DOMDocument("1.0", "utf-8");
1490 $obj_doc->formatOutput = true;
1492 $obj_element = $obj_doc->createElementNS(NAMESPACE_ATOM1, $element);
1494 $activity_type = $xpath->query("activity:object-type/text()", $activity)->item(0)->nodeValue;
1495 xml::add_element($obj_doc, $obj_element, "type", $activity_type);
1497 $id = $xpath->query("atom:id", $activity)->item(0);
1498 if (is_object($id)) {
1499 $obj_element->appendChild($obj_doc->importNode($id, true));
1502 $title = $xpath->query("atom:title", $activity)->item(0);
1503 if (is_object($title)) {
1504 $obj_element->appendChild($obj_doc->importNode($title, true));
1507 $links = $xpath->query("atom:link", $activity);
1508 if (is_object($links)) {
1509 foreach ($links AS $link) {
1510 $obj_element->appendChild($obj_doc->importNode($link, true));
1514 $content = $xpath->query("atom:content", $activity)->item(0);
1515 if (is_object($content)) {
1516 $obj_element->appendChild($obj_doc->importNode($content, true));
1519 $obj_doc->appendChild($obj_element);
1521 $objxml = $obj_doc->saveXML($obj_element);
1523 /// @todo This isn't totally clean. We should find a way to transform the namespaces
1524 $objxml = str_replace("<".$element.' xmlns="http://www.w3.org/2005/Atom">', "<".$element.">", $objxml);
1529 * @brief Processes the mail elements
1531 * @param object $xpath XPath object
1532 * @param object $mail mail elements
1533 * @param array $importer Record of the importer user mixed with contact of the content
1534 * @todo Find good type-hints for all parameter
1536 private static function process_mail($xpath, $mail, $importer) {
1538 logger("Processing mails");
1540 /// @TODO Rewrite this to one statement
1542 $msg["uid"] = $importer["importer_uid"];
1543 $msg["from-name"] = $xpath->query("dfrn:sender/dfrn:name/text()", $mail)->item(0)->nodeValue;
1544 $msg["from-url"] = $xpath->query("dfrn:sender/dfrn:uri/text()", $mail)->item(0)->nodeValue;
1545 $msg["from-photo"] = $xpath->query("dfrn:sender/dfrn:avatar/text()", $mail)->item(0)->nodeValue;
1546 $msg["contact-id"] = $importer["id"];
1547 $msg["uri"] = $xpath->query("dfrn:id/text()", $mail)->item(0)->nodeValue;
1548 $msg["parent-uri"] = $xpath->query("dfrn:in-reply-to/text()", $mail)->item(0)->nodeValue;
1549 $msg["created"] = $xpath->query("dfrn:sentdate/text()", $mail)->item(0)->nodeValue;
1550 $msg["title"] = $xpath->query("dfrn:subject/text()", $mail)->item(0)->nodeValue;
1551 $msg["body"] = $xpath->query("dfrn:content/text()", $mail)->item(0)->nodeValue;
1553 $msg["replied"] = 0;
1555 dbm::esc_array($msg, true);
1557 $r = dbq("INSERT INTO `mail` (`".implode("`, `", array_keys($msg))."`) VALUES (".implode(", ", array_values($msg)).")");
1559 // send notifications.
1560 /// @TODO Arange this mess
1561 $notif_params = array(
1562 "type" => NOTIFY_MAIL,
1563 "notify_flags" => $importer["notify-flags"],
1564 "language" => $importer["language"],
1565 "to_name" => $importer["username"],
1566 "to_email" => $importer["email"],
1567 "uid" => $importer["importer_uid"],
1569 "source_name" => $msg["from-name"],
1570 "source_link" => $importer["url"],
1571 "source_photo" => $importer["thumb"],
1572 "verb" => ACTIVITY_POST,
1576 notification($notif_params);
1578 logger("Mail is processed, notification was sent.");
1582 * @brief Processes the suggestion elements
1584 * @param object $xpath XPath object
1585 * @param object $suggestion suggestion elements
1586 * @param array $importer Record of the importer user mixed with contact of the content
1587 * @todo Find good type-hints for all parameter
1589 private static function process_suggestion($xpath, $suggestion, $importer) {
1592 logger("Processing suggestions");
1594 /// @TODO Rewrite this to one statement
1596 $suggest["uid"] = $importer["importer_uid"];
1597 $suggest["cid"] = $importer["id"];
1598 $suggest["url"] = $xpath->query("dfrn:url/text()", $suggestion)->item(0)->nodeValue;
1599 $suggest["name"] = $xpath->query("dfrn:name/text()", $suggestion)->item(0)->nodeValue;
1600 $suggest["photo"] = $xpath->query("dfrn:photo/text()", $suggestion)->item(0)->nodeValue;
1601 $suggest["request"] = $xpath->query("dfrn:request/text()", $suggestion)->item(0)->nodeValue;
1602 $suggest["body"] = $xpath->query("dfrn:note/text()", $suggestion)->item(0)->nodeValue;
1604 // Does our member already have a friend matching this description?
1606 $r = q("SELECT `id` FROM `contact` WHERE `name` = '%s' AND `nurl` = '%s' AND `uid` = %d LIMIT 1",
1607 dbesc($suggest["name"]),
1608 dbesc(normalise_link($suggest["url"])),
1609 intval($suggest["uid"])
1613 * The valid result means the friend we're about to send a friend
1614 * suggestion already has them in their contact, which means no further
1615 * action is required.
1617 * @see https://github.com/friendica/friendica/pull/3254#discussion_r107315246
1619 if (dbm::is_result($r)) {
1623 // Do we already have an fcontact record for this person?
1626 $r = q("SELECT `id` FROM `fcontact` WHERE `url` = '%s' AND `name` = '%s' AND `request` = '%s' LIMIT 1",
1627 dbesc($suggest["url"]),
1628 dbesc($suggest["name"]),
1629 dbesc($suggest["request"])
1631 if (dbm::is_result($r)) {
1634 // OK, we do. Do we already have an introduction for this person ?
1635 $r = q("SELECT `id` FROM `intro` WHERE `uid` = %d AND `fid` = %d LIMIT 1",
1636 intval($suggest["uid"]),
1640 /// @TODO Really abort on valid result??? Maybe missed ! here?
1641 if (dbm::is_result($r)) {
1646 $r = q("INSERT INTO `fcontact` (`name`,`url`,`photo`,`request`) VALUES ('%s', '%s', '%s', '%s')",
1647 dbesc($suggest["name"]),
1648 dbesc($suggest["url"]),
1649 dbesc($suggest["photo"]),
1650 dbesc($suggest["request"])
1653 $r = q("SELECT `id` FROM `fcontact` WHERE `url` = '%s' AND `name` = '%s' AND `request` = '%s' LIMIT 1",
1654 dbesc($suggest["url"]),
1655 dbesc($suggest["name"]),
1656 dbesc($suggest["request"])
1659 // This way a useless else-block is being spared, resulting in easier code.
1660 if (!dbm::is_result($r)) {
1661 // database record did not get created. Quietly give up.
1667 $hash = random_string();
1669 $r = q("INSERT INTO `intro` (`uid`, `fid`, `contact-id`, `note`, `hash`, `datetime`, `blocked`)
1670 VALUES(%d, %d, %d, '%s', '%s', '%s', %d)",
1671 intval($suggest["uid"]),
1673 intval($suggest["cid"]),
1674 dbesc($suggest["body"]),
1676 dbesc(datetime_convert()),
1681 "type" => NOTIFY_SUGGEST,
1682 "notify_flags" => $importer["notify-flags"],
1683 "language" => $importer["language"],
1684 "to_name" => $importer["username"],
1685 "to_email" => $importer["email"],
1686 "uid" => $importer["importer_uid"],
1688 "link" => App::get_baseurl()."/notifications/intros",
1689 "source_name" => $importer["name"],
1690 "source_link" => $importer["url"],
1691 "source_photo" => $importer["photo"],
1692 "verb" => ACTIVITY_REQ_FRIEND,
1701 * @brief Processes the relocation elements
1703 * @param object $xpath XPath object
1704 * @param object $relocation relocation elements
1705 * @param array $importer Record of the importer user mixed with contact of the content
1706 * @todo Find good type-hints for all parameter
1708 private static function process_relocation($xpath, $relocation, $importer) {
1710 logger("Processing relocations");
1712 /// @TODO Rewrite this to one statement
1713 $relocate = array();
1714 $relocate["uid"] = $importer["importer_uid"];
1715 $relocate["cid"] = $importer["id"];
1716 $relocate["url"] = $xpath->query("dfrn:url/text()", $relocation)->item(0)->nodeValue;
1717 $relocate["addr"] = $xpath->query("dfrn:addr/text()", $relocation)->item(0)->nodeValue;
1718 $relocate["name"] = $xpath->query("dfrn:name/text()", $relocation)->item(0)->nodeValue;
1719 $relocate["avatar"] = $xpath->query("dfrn:avatar/text()", $relocation)->item(0)->nodeValue;
1720 $relocate["photo"] = $xpath->query("dfrn:photo/text()", $relocation)->item(0)->nodeValue;
1721 $relocate["thumb"] = $xpath->query("dfrn:thumb/text()", $relocation)->item(0)->nodeValue;
1722 $relocate["micro"] = $xpath->query("dfrn:micro/text()", $relocation)->item(0)->nodeValue;
1723 $relocate["request"] = $xpath->query("dfrn:request/text()", $relocation)->item(0)->nodeValue;
1724 $relocate["confirm"] = $xpath->query("dfrn:confirm/text()", $relocation)->item(0)->nodeValue;
1725 $relocate["notify"] = $xpath->query("dfrn:notify/text()", $relocation)->item(0)->nodeValue;
1726 $relocate["poll"] = $xpath->query("dfrn:poll/text()", $relocation)->item(0)->nodeValue;
1727 $relocate["sitepubkey"] = $xpath->query("dfrn:sitepubkey/text()", $relocation)->item(0)->nodeValue;
1729 if (($relocate["avatar"] == "") AND ($relocate["photo"] != "")) {
1730 $relocate["avatar"] = $relocate["photo"];
1733 if ($relocate["addr"] == "") {
1734 $relocate["addr"] = preg_replace("=(https?://)(.*)/profile/(.*)=ism", "$3@$2", $relocate["url"]);
1738 $r = q("SELECT `photo`, `url` FROM `contact` WHERE `id` = %d AND `uid` = %d;",
1739 intval($importer["id"]),
1740 intval($importer["importer_uid"]));
1742 if (!dbm::is_result($r)) {
1744 * @TODO maybe one day:
1745 logger("Query failed to execute, no result returned in " . __FUNCTION__);
1753 // Update the gcontact entry
1754 $relocate["server_url"] = preg_replace("=(https?://)(.*)/profile/(.*)=ism", "$1$2", $relocate["url"]);
1756 $x = q("UPDATE `gcontact` SET
1765 WHERE `nurl` = '%s';",
1766 dbesc($relocate["name"]),
1767 dbesc($relocate["avatar"]),
1768 dbesc($relocate["url"]),
1769 dbesc(normalise_link($relocate["url"])),
1770 dbesc($relocate["addr"]),
1771 dbesc($relocate["addr"]),
1772 dbesc($relocate["notify"]),
1773 dbesc($relocate["server_url"]),
1774 dbesc(normalise_link($old["url"])));
1776 // Update the contact table. We try to find every entry.
1777 $x = q("UPDATE `contact` SET
1787 `site-pubkey` = '%s'
1788 WHERE (`id` = %d AND `uid` = %d) OR (`nurl` = '%s');",
1789 dbesc($relocate["name"]),
1790 dbesc($relocate["avatar"]),
1791 dbesc($relocate["url"]),
1792 dbesc(normalise_link($relocate["url"])),
1793 dbesc($relocate["addr"]),
1794 dbesc($relocate["request"]),
1795 dbesc($relocate["confirm"]),
1796 dbesc($relocate["notify"]),
1797 dbesc($relocate["poll"]),
1798 dbesc($relocate["sitepubkey"]),
1799 intval($importer["id"]),
1800 intval($importer["importer_uid"]),
1801 dbesc(normalise_link($old["url"])));
1803 update_contact_avatar($relocate["avatar"], $importer["importer_uid"], $importer["id"], true);
1810 /// @todo This is an extreme performance killer
1812 'owner-link' => array($old["url"], $relocate["url"]),
1813 'author-link' => array($old["url"], $relocate["url"]),
1814 //'owner-avatar' => array($old["photo"], $relocate["photo"]),
1815 //'author-avatar' => array($old["photo"], $relocate["photo"]),
1817 foreach ($fields as $n=>$f) {
1818 $r = q("SELECT `id` FROM `item` WHERE `%s` = '%s' AND `uid` = %d LIMIT 1",
1820 intval($importer["importer_uid"]));
1822 if (dbm::is_result($r)) {
1823 $x = q("UPDATE `item` SET `%s` = '%s' WHERE `%s` = '%s' AND `uid` = %d",
1826 intval($importer["importer_uid"]));
1833 /// merge with current record, current contents have priority
1834 /// update record, set url-updated
1835 /// update profile photos
1836 /// schedule a scan?
1841 * @brief Updates an item
1843 * @param array $current the current item record
1844 * @param array $item the new item record
1845 * @param array $importer Record of the importer user mixed with contact of the content
1846 * @param int $entrytype Is it a toplevel entry, a comment or a relayed comment?
1848 private static function update_content($current, $item, $importer, $entrytype) {
1851 if (edited_timestamp_is_newer($current, $item)) {
1853 // do not accept (ignore) an earlier edit than one we currently have.
1854 if(datetime_convert("UTC","UTC",$item["edited"]) < $current["edited"])
1857 $r = q("UPDATE `item` SET `title` = '%s', `body` = '%s', `tag` = '%s', `edited` = '%s', `changed` = '%s' WHERE `uri` = '%s' AND `uid` = %d",
1858 dbesc($item["title"]),
1859 dbesc($item["body"]),
1860 dbesc($item["tag"]),
1861 dbesc(datetime_convert("UTC","UTC",$item["edited"])),
1862 dbesc(datetime_convert()),
1863 dbesc($item["uri"]),
1864 intval($importer["importer_uid"])
1866 create_tags_from_itemuri($item["uri"], $importer["importer_uid"]);
1867 update_thread_uri($item["uri"], $importer["importer_uid"]);
1871 if ($entrytype == DFRN_REPLY_RC) {
1872 proc_run(PRIORITY_HIGH, "include/notifier.php","comment-import", $current["id"]);
1876 // update last-child if it changes
1877 if ($item["last-child"] AND ($item["last-child"] != $current["last-child"])) {
1878 $r = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d",
1879 dbesc(datetime_convert()),
1880 dbesc($item["parent-uri"]),
1881 intval($importer["importer_uid"])
1883 $r = q("UPDATE `item` SET `last-child` = %d , `changed` = '%s' WHERE `uri` = '%s' AND `uid` = %d",
1884 intval($item["last-child"]),
1885 dbesc(datetime_convert()),
1886 dbesc($item["uri"]),
1887 intval($importer["importer_uid"])
1894 * @brief Detects the entry type of the item
1896 * @param array $importer Record of the importer user mixed with contact of the content
1897 * @param array $item the new item record
1899 * @return int Is it a toplevel entry, a comment or a relayed comment?
1901 private static function get_entry_type($importer, $item) {
1902 if ($item["parent-uri"] != $item["uri"]) {
1905 if($importer["page-flags"] == PAGE_COMMUNITY || $importer["page-flags"] == PAGE_PRVGROUP) {
1908 logger("possible community action");
1910 $sql_extra = " AND `contact`.`self` AND `item`.`wall` ";
1913 // was the top-level post for this action written by somebody on this site?
1914 // Specifically, the recipient?
1916 $is_a_remote_action = false;
1918 $r = q("SELECT `item`.`parent-uri` FROM `item`
1919 WHERE `item`.`uri` = '%s'
1921 dbesc($item["parent-uri"])
1923 if (dbm::is_result($r)) {
1924 $r = q("SELECT `item`.`forum_mode`, `item`.`wall` FROM `item`
1925 INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
1926 WHERE `item`.`uri` = '%s' AND (`item`.`parent-uri` = '%s' OR `item`.`thr-parent` = '%s')
1927 AND `item`.`uid` = %d
1930 dbesc($r[0]["parent-uri"]),
1931 dbesc($r[0]["parent-uri"]),
1932 dbesc($r[0]["parent-uri"]),
1933 intval($importer["importer_uid"])
1935 if (dbm::is_result($r)) {
1936 $is_a_remote_action = true;
1940 // Does this have the characteristics of a community or private group action?
1941 // If it's an action to a wall post on a community/prvgroup page it's a
1942 // valid community action. Also forum_mode makes it valid for sure.
1943 // If neither, it's not.
1945 if ($is_a_remote_action && $community) {
1946 if ((!$r[0]["forum_mode"]) && (!$r[0]["wall"])) {
1947 $is_a_remote_action = false;
1948 logger("not a community action");
1952 if ($is_a_remote_action) {
1953 return DFRN_REPLY_RC;
1959 return DFRN_TOP_LEVEL;
1965 * @brief Send a "poke"
1967 * @param array $item the new item record
1968 * @param array $importer Record of the importer user mixed with contact of the content
1969 * @param int $posted_id The record number of item record that was just posted
1971 private static function do_poke($item, $importer, $posted_id) {
1972 $verb = urldecode(substr($item["verb"],strpos($item["verb"], "#")+1));
1976 $xo = parse_xml_string($item["object"],false);
1978 if (($xo->type == ACTIVITY_OBJ_PERSON) && ($xo->id)) {
1980 // somebody was poked/prodded. Was it me?
1981 foreach ($xo->link as $l) {
1982 $atts = $l->attributes();
1983 switch($atts["rel"]) {
1985 $Blink = $atts["href"];
1992 if($Blink && link_compare($Blink,App::get_baseurl()."/profile/".$importer["nickname"])) {
1994 // send a notification
1996 "type" => NOTIFY_POKE,
1997 "notify_flags" => $importer["notify-flags"],
1998 "language" => $importer["language"],
1999 "to_name" => $importer["username"],
2000 "to_email" => $importer["email"],
2001 "uid" => $importer["importer_uid"],
2003 "link" => App::get_baseurl()."/display/".urlencode(get_item_guid($posted_id)),
2004 "source_name" => stripslashes($item["author-name"]),
2005 "source_link" => $item["author-link"],
2006 "source_photo" => ((link_compare($item["author-link"],$importer["url"]))
2007 ? $importer["thumb"] : $item["author-avatar"]),
2008 "verb" => $item["verb"],
2009 "otype" => "person",
2010 "activity" => $verb,
2011 "parent" => $item["parent"]
2018 * @brief Processes several actions, depending on the verb
2020 * @param int $entrytype Is it a toplevel entry, a comment or a relayed comment?
2021 * @param array $importer Record of the importer user mixed with contact of the content
2022 * @param array $item the new item record
2023 * @param bool $is_like Is the verb a "like"?
2025 * @return bool Should the processing of the entries be continued?
2027 private static function process_verbs($entrytype, $importer, &$item, &$is_like) {
2029 logger("Process verb ".$item["verb"]." and object-type ".$item["object-type"]." for entrytype ".$entrytype, LOGGER_DEBUG);
2031 if (($entrytype == DFRN_TOP_LEVEL)) {
2032 // The filling of the the "contact" variable is done for legcy reasons
2033 // The functions below are partly used by ostatus.php as well - where we have this variable
2034 $r = q("SELECT * FROM `contact` WHERE `id` = %d", intval($importer["id"]));
2036 $nickname = $contact["nick"];
2038 // Big question: Do we need these functions? They were part of the "consume_feed" function.
2039 // This function once was responsible for DFRN and OStatus.
2040 if (activity_match($item["verb"], ACTIVITY_FOLLOW)) {
2041 logger("New follower");
2042 new_follower($importer, $contact, $item, $nickname);
2045 if (activity_match($item["verb"], ACTIVITY_UNFOLLOW)) {
2046 logger("Lost follower");
2047 lose_follower($importer, $contact, $item);
2050 if (activity_match($item["verb"], ACTIVITY_REQ_FRIEND)) {
2051 logger("New friend request");
2052 new_follower($importer, $contact, $item, $nickname, true);
2055 if (activity_match($item["verb"], ACTIVITY_UNFRIEND)) {
2056 logger("Lost sharer");
2057 lose_sharer($importer, $contact, $item);
2061 if (($item["verb"] == ACTIVITY_LIKE)
2062 || ($item["verb"] == ACTIVITY_DISLIKE)
2063 || ($item["verb"] == ACTIVITY_ATTEND)
2064 || ($item["verb"] == ACTIVITY_ATTENDNO)
2065 || ($item["verb"] == ACTIVITY_ATTENDMAYBE)) {
2067 $item["type"] = "activity";
2068 $item["gravity"] = GRAVITY_LIKE;
2069 // only one like or dislike per person
2070 // splitted into two queries for performance issues
2071 $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",
2072 intval($item["uid"]),
2073 dbesc($item["author-link"]),
2074 dbesc($item["verb"]),
2075 dbesc($item["parent-uri"])
2077 if (dbm::is_result($r)) {
2081 $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",
2082 intval($item["uid"]),
2083 dbesc($item["author-link"]),
2084 dbesc($item["verb"]),
2085 dbesc($item["parent-uri"])
2087 if (dbm::is_result($r)) {
2094 if (($item["verb"] == ACTIVITY_TAG) && ($item["object-type"] == ACTIVITY_OBJ_TAGTERM)) {
2096 $xo = parse_xml_string($item["object"],false);
2097 $xt = parse_xml_string($item["target"],false);
2099 if ($xt->type == ACTIVITY_OBJ_NOTE) {
2100 $r = q("SELECT `id`, `tag` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2102 intval($importer["importer_uid"])
2105 if (!dbm::is_result($r)) {
2107 * @TODO maybe one day:
2108 logger("Query failed to execute, no result returned in " . __FUNCTION__);
2114 // extract tag, if not duplicate, add to parent item
2116 if (!(stristr($r[0]["tag"],trim($xo->content)))) {
2117 q("UPDATE `item` SET `tag` = '%s' WHERE `id` = %d",
2118 dbesc($r[0]["tag"] . (strlen($r[0]["tag"]) ? ',' : '') . '#[url=' . $xo->id . ']'. $xo->content . '[/url]'),
2121 create_tags_from_item($r[0]["id"]);
2131 * @brief Processes the link elements
2133 * @param object $links link elements
2134 * @param array $item the item record
2135 * @todo Add type-hints
2137 private static function parse_links($links, &$item) {
2143 foreach ($links AS $link) {
2144 foreach ($link->attributes AS $attributes) {
2145 /// @TODO Rewrite these repeated (same) if() statements to a switch()
2146 if ($attributes->name == "href") {
2147 $href = $attributes->textContent;
2149 if ($attributes->name == "rel") {
2150 $rel = $attributes->textContent;
2152 if ($attributes->name == "type") {
2153 $type = $attributes->textContent;
2155 if ($attributes->name == "length") {
2156 $length = $attributes->textContent;
2158 if ($attributes->name == "title") {
2159 $title = $attributes->textContent;
2162 if (($rel != "") AND ($href != "")) {
2165 $item["plink"] = $href;
2169 if (strlen($item["attach"])) {
2170 $item["attach"] .= ",";
2173 $item["attach"] .= '[attach]href="' . $href . '" length="' . $length . '" type="' . $type . '" title="' . $title . '"[/attach]';
2181 * @brief Processes the entry elements which contain the items and comments
2183 * @param array $header Array of the header elements that always stay the same
2184 * @param object $xpath XPath object
2185 * @param object $entry entry elements
2186 * @param array $importer Record of the importer user mixed with contact of the content
2187 * @todo Add type-hints
2189 private static function process_entry($header, $xpath, $entry, $importer) {
2191 logger("Processing entries");
2196 $item["uri"] = $xpath->query("atom:id/text()", $entry)->item(0)->nodeValue;
2198 $item["edited"] = $xpath->query("atom:updated/text()", $entry)->item(0)->nodeValue;
2200 $current = q("SELECT `id`, `uid`, `last-child`, `edited`, `body` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2201 dbesc($item["uri"]),
2202 intval($importer["importer_uid"])
2205 // Is there an existing item?
2206 if (dbm::is_result($current) AND edited_timestamp_is_newer($current[0], $item) AND
2207 (datetime_convert("UTC","UTC",$item["edited"]) < $current[0]["edited"])) {
2208 logger("Item ".$item["uri"]." already existed.", LOGGER_DEBUG);
2213 $owner = self::fetchauthor($xpath, $entry, $importer, "dfrn:owner", true);
2215 $item["owner-name"] = $owner["name"];
2216 $item["owner-link"] = $owner["link"];
2217 $item["owner-avatar"] = $owner["avatar"];
2220 $author = self::fetchauthor($xpath, $entry, $importer, "atom:author", true);
2222 $item["author-name"] = $author["name"];
2223 $item["author-link"] = $author["link"];
2224 $item["author-avatar"] = $author["avatar"];
2226 $item["title"] = $xpath->query("atom:title/text()", $entry)->item(0)->nodeValue;
2228 $item["created"] = $xpath->query("atom:published/text()", $entry)->item(0)->nodeValue;
2230 $item["body"] = $xpath->query("dfrn:env/text()", $entry)->item(0)->nodeValue;
2231 $item["body"] = str_replace(array(' ',"\t","\r","\n"), array('','','',''),$item["body"]);
2232 // make sure nobody is trying to sneak some html tags by us
2233 $item["body"] = notags(base64url_decode($item["body"]));
2235 $item["body"] = limit_body_size($item["body"]);
2237 /// @todo Do we really need this check for HTML elements? (It was copied from the old function)
2238 if ((strpos($item['body'],'<') !== false) && (strpos($item['body'],'>') !== false)) {
2240 $item['body'] = reltoabs($item['body'],$base_url);
2242 $item['body'] = html2bb_video($item['body']);
2244 $item['body'] = oembed_html2bbcode($item['body']);
2246 $config = HTMLPurifier_Config::createDefault();
2247 $config->set('Cache.DefinitionImpl', null);
2249 // we shouldn't need a whitelist, because the bbcode converter
2250 // will strip out any unsupported tags.
2252 $purifier = new HTMLPurifier($config);
2253 $item['body'] = $purifier->purify($item['body']);
2255 $item['body'] = @html2bbcode($item['body']);
2258 /// @todo We should check for a repeated post and if we know the repeated author.
2260 // We don't need the content element since "dfrn:env" is always present
2261 //$item["body"] = $xpath->query("atom:content/text()", $entry)->item(0)->nodeValue;
2263 $item["last-child"] = $xpath->query("dfrn:comment-allow/text()", $entry)->item(0)->nodeValue;
2264 $item["location"] = $xpath->query("dfrn:location/text()", $entry)->item(0)->nodeValue;
2266 $georsspoint = $xpath->query("georss:point", $entry);
2268 $item["coord"] = $georsspoint->item(0)->nodeValue;
2271 $item["private"] = $xpath->query("dfrn:private/text()", $entry)->item(0)->nodeValue;
2273 $item["extid"] = $xpath->query("dfrn:extid/text()", $entry)->item(0)->nodeValue;
2275 if ($xpath->query("dfrn:bookmark/text()", $entry)->item(0)->nodeValue == "true") {
2276 $item["bookmark"] = true;
2279 $notice_info = $xpath->query("statusnet:notice_info", $entry);
2280 if ($notice_info AND ($notice_info->length > 0)) {
2281 foreach ($notice_info->item(0)->attributes AS $attributes) {
2282 if ($attributes->name == "source") {
2283 $item["app"] = strip_tags($attributes->textContent);
2288 $item["guid"] = $xpath->query("dfrn:diaspora_guid/text()", $entry)->item(0)->nodeValue;
2290 // We store the data from "dfrn:diaspora_signature" in a different table, this is done in "item_store"
2291 $dsprsig = unxmlify($xpath->query("dfrn:diaspora_signature/text()", $entry)->item(0)->nodeValue);
2292 if ($dsprsig != "") {
2293 $item["dsprsig"] = $dsprsig;
2296 $item["verb"] = $xpath->query("activity:verb/text()", $entry)->item(0)->nodeValue;
2298 if ($xpath->query("activity:object-type/text()", $entry)->item(0)->nodeValue != "") {
2299 $item["object-type"] = $xpath->query("activity:object-type/text()", $entry)->item(0)->nodeValue;
2302 $object = $xpath->query("activity:object", $entry)->item(0);
2303 $item["object"] = self::transform_activity($xpath, $object, "object");
2305 if (trim($item["object"]) != "") {
2306 $r = parse_xml_string($item["object"], false);
2307 if (isset($r->type)) {
2308 $item["object-type"] = $r->type;
2312 $target = $xpath->query("activity:target", $entry)->item(0);
2313 $item["target"] = self::transform_activity($xpath, $target, "target");
2315 $categories = $xpath->query("atom:category", $entry);
2317 foreach ($categories AS $category) {
2320 foreach ($category->attributes AS $attributes) {
2321 if ($attributes->name == "term") {
2322 $term = $attributes->textContent;
2325 if ($attributes->name == "scheme") {
2326 $scheme = $attributes->textContent;
2330 if (($term != "") AND ($scheme != "")) {
2331 $parts = explode(":", $scheme);
2332 if ((count($parts) >= 4) AND (array_shift($parts) == "X-DFRN")) {
2333 $termhash = array_shift($parts);
2334 $termurl = implode(":", $parts);
2336 if (strlen($item["tag"])) {
2337 $item["tag"] .= ",";
2340 $item["tag"] .= $termhash . "[url=" . $termurl . "]" . $term . "[/url]";
2348 $links = $xpath->query("atom:link", $entry);
2350 self::parse_links($links, $item);
2353 // Is it a reply or a top level posting?
2354 $item["parent-uri"] = $item["uri"];
2356 $inreplyto = $xpath->query("thr:in-reply-to", $entry);
2357 if (is_object($inreplyto->item(0))) {
2358 foreach ($inreplyto->item(0)->attributes AS $attributes) {
2359 if ($attributes->name == "ref") {
2360 $item["parent-uri"] = $attributes->textContent;
2365 // Get the type of the item (Top level post, reply or remote reply)
2366 $entrytype = self::get_entry_type($importer, $item);
2368 // Now assign the rest of the values that depend on the type of the message
2369 if (in_array($entrytype, array(DFRN_REPLY, DFRN_REPLY_RC))) {
2370 if (!isset($item["object-type"])) {
2371 $item["object-type"] = ACTIVITY_OBJ_COMMENT;
2374 if ($item["contact-id"] != $owner["contact-id"]) {
2375 $item["contact-id"] = $owner["contact-id"];
2378 if (($item["network"] != $owner["network"]) AND ($owner["network"] != "")) {
2379 $item["network"] = $owner["network"];
2382 if ($item["contact-id"] != $author["contact-id"]) {
2383 $item["contact-id"] = $author["contact-id"];
2386 if (($item["network"] != $author["network"]) AND ($author["network"] != "")) {
2387 $item["network"] = $author["network"];
2390 /// @TODO maybe remove this old-lost code then?
2391 // This code was taken from the old DFRN code
2392 // When activated, forums don't work.
2393 // And: Why should we disallow commenting by followers?
2394 // the behaviour is now similar to the Diaspora part.
2395 //if($importer["rel"] == CONTACT_IS_FOLLOWER) {
2396 // logger("Contact ".$importer["id"]." is only follower. Quitting", LOGGER_DEBUG);
2401 if ($entrytype == DFRN_REPLY_RC) {
2402 $item["type"] = "remote-comment";
2404 } elseif ($entrytype == DFRN_TOP_LEVEL) {
2405 if (!isset($item["object-type"])) {
2406 $item["object-type"] = ACTIVITY_OBJ_NOTE;
2410 if ($item["object-type"] == ACTIVITY_OBJ_EVENT) {
2411 logger("Item ".$item["uri"]." seems to contain an event.", LOGGER_DEBUG);
2412 $ev = bbtoevent($item["body"]);
2413 if ((x($ev, "desc") || x($ev, "summary")) && x($ev, "start")) {
2414 logger("Event in item ".$item["uri"]." was found.", LOGGER_DEBUG);
2415 /// @TODO Mixure of "/' ahead ...
2416 $ev["cid"] = $importer["id"];
2417 $ev["uid"] = $importer["uid"];
2418 $ev["uri"] = $item["uri"];
2419 $ev["edited"] = $item["edited"];
2420 $ev['private'] = $item['private'];
2421 $ev["guid"] = $item["guid"];
2423 $r = q("SELECT `id` FROM `event` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2424 dbesc($item["uri"]),
2425 intval($importer["uid"])
2427 if (dbm::is_result($r)) {
2428 $ev["id"] = $r[0]["id"];
2431 $event_id = event_store($ev);
2432 logger("Event ".$event_id." was stored", LOGGER_DEBUG);
2438 if (!self::process_verbs($entrytype, $importer, $item, $is_like)) {
2439 logger("Exiting because 'process_verbs' told us so", LOGGER_DEBUG);
2443 // Update content if 'updated' changes
2444 if (dbm::is_result($current)) {
2445 if (self::update_content($r[0], $item, $importer, $entrytype)) {
2446 logger("Item ".$item["uri"]." was updated.", LOGGER_DEBUG);
2448 logger("Item ".$item["uri"]." already existed.", LOGGER_DEBUG);
2453 if (in_array($entrytype, array(DFRN_REPLY, DFRN_REPLY_RC))) {
2454 $posted_id = item_store($item);
2459 logger("Reply from contact ".$item["contact-id"]." was stored with id ".$posted_id, LOGGER_DEBUG);
2461 $item["id"] = $posted_id;
2463 $r = q("SELECT `parent`, `parent-uri` FROM `item` WHERE `id` = %d AND `uid` = %d LIMIT 1",
2465 intval($importer["importer_uid"])
2467 if (dbm::is_result($r)) {
2468 $parent = $r[0]["parent"];
2469 $parent_uri = $r[0]["parent-uri"];
2473 $r1 = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `uid` = %d AND `parent` = %d",
2474 dbesc(datetime_convert()),
2475 intval($importer["importer_uid"]),
2476 intval($r[0]["parent"])
2479 $r2 = q("UPDATE `item` SET `last-child` = 1, `changed` = '%s' WHERE `uid` = %d AND `id` = %d",
2480 dbesc(datetime_convert()),
2481 intval($importer["importer_uid"]),
2486 if ($posted_id AND $parent AND ($entrytype == DFRN_REPLY_RC)) {
2487 logger("Notifying followers about comment ".$posted_id, LOGGER_DEBUG);
2488 proc_run(PRIORITY_HIGH, "include/notifier.php", "comment-import", $posted_id);
2493 } else { // $entrytype == DFRN_TOP_LEVEL
2494 if (!link_compare($item["owner-link"],$importer["url"])) {
2495 // The item owner info is not our contact. It's OK and is to be expected if this is a tgroup delivery,
2496 // but otherwise there's a possible data mixup on the sender's system.
2497 // the tgroup delivery code called from item_store will correct it if it's a forum,
2498 // but we're going to unconditionally correct it here so that the post will always be owned by our contact.
2499 logger('Correcting item owner.', LOGGER_DEBUG);
2500 $item["owner-name"] = $importer["senderName"];
2501 $item["owner-link"] = $importer["url"];
2502 $item["owner-avatar"] = $importer["thumb"];
2505 if (($importer["rel"] == CONTACT_IS_FOLLOWER) && (!tgroup_check($importer["importer_uid"], $item))) {
2506 logger("Contact ".$importer["id"]." is only follower and tgroup check was negative.", LOGGER_DEBUG);
2510 // This is my contact on another system, but it's really me.
2511 // Turn this into a wall post.
2512 $notify = item_is_remote_self($importer, $item);
2514 $posted_id = item_store($item, false, $notify);
2516 logger("Item was stored with id ".$posted_id, LOGGER_DEBUG);
2518 if(stristr($item["verb"],ACTIVITY_POKE))
2519 self::do_poke($item, $importer, $posted_id);
2524 * @brief Deletes items
2526 * @param object $xpath XPath object
2527 * @param object $deletion deletion elements
2528 * @param array $importer Record of the importer user mixed with contact of the content
2530 private static function process_deletion($xpath, $deletion, $importer) {
2532 logger("Processing deletions");
2534 foreach ($deletion->attributes AS $attributes) {
2535 if ($attributes->name == "ref") {
2536 $uri = $attributes->textContent;
2538 if ($attributes->name == "when") {
2539 $when = $attributes->textContent;
2543 $when = datetime_convert("UTC", "UTC", $when, "Y-m-d H:i:s");
2545 $when = datetime_convert("UTC", "UTC", "now", "Y-m-d H:i:s");
2548 if (!$uri OR !$importer["id"]) {
2552 /// @todo Only select the used fields
2553 $r = q("SELECT `item`.*, `contact`.`self` FROM `item` INNER JOIN `contact` on `item`.`contact-id` = `contact`.`id`
2554 WHERE `uri` = '%s' AND `item`.`uid` = %d AND `contact-id` = %d AND NOT `item`.`file` LIKE '%%[%%' LIMIT 1",
2556 intval($importer["uid"]),
2557 intval($importer["id"])
2559 if (!dbm::is_result($r)) {
2560 logger("Item with uri " . $uri . " from contact " . $importer["id"] . " for user " . $importer["uid"] . " wasn't found.", LOGGER_DEBUG);
2566 $entrytype = self::get_entry_type($importer, $item);
2568 if (!$item["deleted"]) {
2569 logger('deleting item '.$item["id"].' uri='.$uri, LOGGER_DEBUG);
2574 if ($item["object-type"] == ACTIVITY_OBJ_EVENT) {
2575 logger("Deleting event ".$item["event-id"], LOGGER_DEBUG);
2576 event_delete($item["event-id"]);
2579 if (($item["verb"] == ACTIVITY_TAG) && ($item["object-type"] == ACTIVITY_OBJ_TAGTERM)) {
2581 $xo = parse_xml_string($item["object"],false);
2582 $xt = parse_xml_string($item["target"],false);
2584 if ($xt->type == ACTIVITY_OBJ_NOTE) {
2585 $i = q("SELECT `id`, `contact-id`, `tag` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2587 intval($importer["importer_uid"])
2589 if (dbm::is_result($i)) {
2591 // For tags, the owner cannot remove the tag on the author's copy of the post.
2593 $owner_remove = (($item["contact-id"] == $i[0]["contact-id"]) ? true: false);
2594 $author_remove = (($item["origin"] && $item["self"]) ? true : false);
2595 $author_copy = (($item["origin"]) ? true : false);
2597 if ($owner_remove && $author_copy) {
2600 if ($author_remove || $owner_remove) {
2601 $tags = explode(',',$i[0]["tag"]);
2604 foreach ($tags as $tag) {
2605 if (trim($tag) !== trim($xo->body)) {
2606 $newtags[] = trim($tag);
2610 q("UPDATE `item` SET `tag` = '%s' WHERE `id` = %d",
2611 dbesc(implode(',',$newtags)),
2614 create_tags_from_item($i[0]["id"]);
2620 if($entrytype == DFRN_TOP_LEVEL) {
2621 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s',
2622 `body` = '', `title` = ''
2623 WHERE `parent-uri` = '%s' AND `uid` = %d",
2625 dbesc(datetime_convert()),
2627 intval($importer["uid"])
2629 create_tags_from_itemuri($uri, $importer["uid"]);
2630 create_files_from_itemuri($uri, $importer["uid"]);
2631 update_thread_uri($uri, $importer["uid"]);
2633 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s',
2634 `body` = '', `title` = ''
2635 WHERE `uri` = '%s' AND `uid` = %d",
2637 dbesc(datetime_convert()),
2639 intval($importer["uid"])
2641 create_tags_from_itemuri($uri, $importer["uid"]);
2642 create_files_from_itemuri($uri, $importer["uid"]);
2643 update_thread_uri($uri, $importer["importer_uid"]);
2644 if($item["last-child"]) {
2645 // ensure that last-child is set in case the comment that had it just got wiped.
2646 q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d ",
2647 dbesc(datetime_convert()),
2648 dbesc($item["parent-uri"]),
2649 intval($item["uid"])
2651 // who is the last child now?
2652 $r = q("SELECT `id` FROM `item` WHERE `parent-uri` = '%s' AND `type` != 'activity' AND `deleted` = 0 AND `moderated` = 0 AND `uid` = %d
2653 ORDER BY `created` DESC LIMIT 1",
2654 dbesc($item["parent-uri"]),
2655 intval($importer["uid"])
2657 if (dbm::is_result($r)) {
2658 q("UPDATE `item` SET `last-child` = 1 WHERE `id` = %d",
2663 // if this is a relayed delete, propagate it to other recipients
2665 if ($entrytype == DFRN_REPLY_RC) {
2666 logger("Notifying followers about deletion of post ".$item["id"], LOGGER_DEBUG);
2667 proc_run(PRIORITY_HIGH, "include/notifier.php","drop", $item["id"]);
2674 * @brief Imports a DFRN message
2676 * @param text $xml The DFRN message
2677 * @param array $importer Record of the importer user mixed with contact of the content
2678 * @param bool $sort_by_date Is used when feeds are polled
2680 public static function import($xml,$importer, $sort_by_date = false) {
2686 if ($importer["readonly"]) {
2687 // We aren't receiving stuff from this person. But we will quietly ignore them
2688 // rather than a blatant "go away" message.
2689 logger('ignoring contact '.$importer["id"]);
2693 $doc = new DOMDocument();
2694 @$doc->loadXML($xml);
2696 $xpath = new DomXPath($doc);
2697 $xpath->registerNamespace("atom", NAMESPACE_ATOM1);
2698 $xpath->registerNamespace("thr", NAMESPACE_THREAD);
2699 $xpath->registerNamespace("at", NAMESPACE_TOMB);
2700 $xpath->registerNamespace("media", NAMESPACE_MEDIA);
2701 $xpath->registerNamespace("dfrn", NAMESPACE_DFRN);
2702 $xpath->registerNamespace("activity", NAMESPACE_ACTIVITY);
2703 $xpath->registerNamespace("georss", NAMESPACE_GEORSS);
2704 $xpath->registerNamespace("poco", NAMESPACE_POCO);
2705 $xpath->registerNamespace("ostatus", NAMESPACE_OSTATUS);
2706 $xpath->registerNamespace("statusnet", NAMESPACE_STATUSNET);
2709 $header["uid"] = $importer["uid"];
2710 $header["network"] = NETWORK_DFRN;
2711 $header["type"] = "remote";
2712 $header["wall"] = 0;
2713 $header["origin"] = 0;
2714 $header["contact-id"] = $importer["id"];
2716 // Update the contact table if the data has changed
2718 // The "atom:author" is only present in feeds
2719 if ($xpath->query("/atom:feed/atom:author")->length > 0) {
2720 self::fetchauthor($xpath, $doc->firstChild, $importer, "atom:author", false, $xml);
2723 // Only the "dfrn:owner" in the head section contains all data
2724 if ($xpath->query("/atom:feed/dfrn:owner")->length > 0) {
2725 self::fetchauthor($xpath, $doc->firstChild, $importer, "dfrn:owner", false, $xml);
2728 logger("Import DFRN message for user " . $importer["uid"] . " from contact " . $importer["id"], LOGGER_DEBUG);
2730 // The account type is new since 3.5.1
2731 if ($xpath->query("/atom:feed/dfrn:account_type")->length > 0) {
2732 $accounttype = intval($xpath->evaluate("/atom:feed/dfrn:account_type/text()", $context)->item(0)->nodeValue);
2734 if ($accounttype != $importer["contact-type"]) {
2735 /// @TODO this way is the norm or putting ); at the end of the line?
2736 q("UPDATE `contact` SET `contact-type` = %d WHERE `id` = %d",
2737 intval($accounttype),
2738 intval($importer["id"])
2743 // is it a public forum? Private forums aren't supported with this method
2744 // This is deprecated since 3.5.1
2745 $forum = intval($xpath->evaluate("/atom:feed/dfrn:community/text()", $context)->item(0)->nodeValue);
2747 if ($forum != $importer["forum"]) {
2748 q("UPDATE `contact` SET `forum` = %d WHERE `forum` != %d AND `id` = %d",
2749 intval($forum), intval($forum),
2750 intval($importer["id"])
2754 $mails = $xpath->query("/atom:feed/dfrn:mail");
2755 foreach ($mails AS $mail) {
2756 self::process_mail($xpath, $mail, $importer);
2759 $suggestions = $xpath->query("/atom:feed/dfrn:suggest");
2760 foreach ($suggestions AS $suggestion) {
2761 self::process_suggestion($xpath, $suggestion, $importer);
2764 $relocations = $xpath->query("/atom:feed/dfrn:relocate");
2765 foreach ($relocations AS $relocation) {
2766 self::process_relocation($xpath, $relocation, $importer);
2769 $deletions = $xpath->query("/atom:feed/at:deleted-entry");
2770 foreach ($deletions AS $deletion) {
2771 self::process_deletion($xpath, $deletion, $importer);
2774 if (!$sort_by_date) {
2775 $entries = $xpath->query("/atom:feed/atom:entry");
2776 foreach ($entries AS $entry) {
2777 self::process_entry($header, $xpath, $entry, $importer);
2780 $newentries = array();
2781 $entries = $xpath->query("/atom:feed/atom:entry");
2782 foreach ($entries AS $entry) {
2783 $created = $xpath->query("atom:published/text()", $entry)->item(0)->nodeValue;
2784 $newentries[strtotime($created)] = $entry;
2787 // Now sort after the publishing date
2790 foreach ($newentries AS $entry) {
2791 self::process_entry($header, $xpath, $entry, $importer);
2794 logger("Import done for user ".$importer["uid"]." from contact ".$importer["id"], LOGGER_DEBUG);