2 namespace Friendica\Protocol;
4 * @file include/dfrn.php
5 * @brief The implementation of the dfrn protocol
7 * @see https://github.com/friendica/friendica/wiki/Protocol and
8 * https://github.com/friendica/friendica/blob/master/spec/dfrn2.pdf
12 use Friendica\Core\Config;
13 use Friendica\Core\System;
14 use Friendica\Core\Worker;
15 use Friendica\Database\Dbm;
19 require_once("include/Contact.php");
20 require_once("include/ostatus.php");
21 require_once("include/enotify.php");
22 require_once("include/threads.php");
23 require_once("include/socgraph.php");
24 require_once("include/items.php");
25 require_once("include/tags.php");
26 require_once("include/files.php");
27 require_once("include/event.php");
28 require_once("include/text.php");
29 require_once("include/oembed.php");
30 require_once("include/html2bbcode.php");
31 require_once("include/bbcode.php");
32 require_once("include/xml.php");
35 * @brief This class contain functions to create and send DFRN XML files
40 const DFRN_TOP_LEVEL = 0; // Top level posting
41 const DFRN_REPLY = 1; // Regular reply that is stored locally
42 const DFRN_REPLY_RC = 2; // Reply that will be relayed
45 * @brief Generates the atom entries for delivery.php
47 * This function is used whenever content is transmitted via DFRN.
49 * @param array $items Item elements
50 * @param array $owner Owner record
52 * @return string DFRN entries
53 * @todo Add type-hints
55 public static function entries($items,$owner) {
57 $doc = new DOMDocument('1.0', 'utf-8');
58 $doc->formatOutput = true;
60 $root = self::add_header($doc, $owner, "dfrn:owner", "", false);
62 if (! count($items)) {
63 return trim($doc->saveXML());
66 foreach ($items as $item) {
67 $entry = self::entry($doc, "text", $item, $owner, $item["entry:comment-allow"], $item["entry:cid"]);
68 $root->appendChild($entry);
71 return(trim($doc->saveXML()));
75 * @brief Generate an atom feed for the given user
77 * This function is called when another server is pulling data from the user feed.
79 * @param string $dfrn_id DFRN ID from the requesting party
80 * @param string $owner_nick Owner nick name
81 * @param string $last_update Date of the last update
82 * @param int $direction Can be -1, 0 or 1.
83 * @param boolean $onlyheader Output only the header without content? (Default is "no")
85 * @return string DFRN feed entries
87 public static function feed($dfrn_id, $owner_nick, $last_update, $direction = 0, $onlyheader = false) {
91 $sitefeed = ((strlen($owner_nick)) ? false : true); // not yet implemented, need to rewrite huge chunks of following logic
92 $public_feed = (($dfrn_id) ? false : true);
93 $starred = false; // not yet implemented, possible security issues
96 if ($public_feed && $a->argc > 2) {
97 for ($x = 2; $x < $a->argc; $x++) {
98 if ($a->argv[$x] == 'converse') {
101 if ($a->argv[$x] == 'starred') {
104 if ($a->argv[$x] == 'category' && $a->argc > ($x + 1) && strlen($a->argv[$x+1])) {
105 $category = $a->argv[$x+1];
112 // default permissions - anonymous user
114 $sql_extra = " AND `item`.`allow_cid` = '' AND `item`.`allow_gid` = '' AND `item`.`deny_cid` = '' AND `item`.`deny_gid` = '' ";
116 $r = q("SELECT `contact`.*, `user`.`nickname`, `user`.`timezone`, `user`.`page-flags`, `user`.`account-type`
117 FROM `contact` INNER JOIN `user` ON `user`.`uid` = `contact`.`uid`
118 WHERE `contact`.`self` AND `user`.`nickname` = '%s' LIMIT 1",
122 if (! Dbm::is_result($r)) {
127 $owner_id = $owner['uid'];
128 $owner_nick = $owner['nickname'];
130 $sql_post_table = "";
132 if (! $public_feed) {
137 $sql_extra = sprintf(" AND `issued-id` = '%s' ", dbesc($dfrn_id));
141 $sql_extra = sprintf(" AND `issued-id` = '%s' AND `duplex` = 1 ", dbesc($dfrn_id));
142 $my_id = '1:' . $dfrn_id;
145 $sql_extra = sprintf(" AND `dfrn-id` = '%s' AND `duplex` = 1 ", dbesc($dfrn_id));
146 $my_id = '0:' . $dfrn_id;
153 $r = q("SELECT * FROM `contact` WHERE NOT `blocked` AND `contact`.`uid` = %d $sql_extra LIMIT 1",
157 if (! Dbm::is_result($r)) {
162 require_once('include/security.php');
163 $groups = init_groups_visitor($contact['id']);
165 if (count($groups)) {
166 for ($x = 0; $x < count($groups); $x ++)
167 $groups[$x] = '<' . intval($groups[$x]) . '>' ;
168 $gs = implode('|', $groups);
170 $gs = '<<>>' ; // Impossible to match
173 $sql_extra = sprintf("
174 AND ( `allow_cid` = '' OR `allow_cid` REGEXP '<%d>' )
175 AND ( `deny_cid` = '' OR NOT `deny_cid` REGEXP '<%d>' )
176 AND ( `allow_gid` = '' OR `allow_gid` REGEXP '%s' )
177 AND ( `deny_gid` = '' OR NOT `deny_gid` REGEXP '%s')
179 intval($contact['id']),
180 intval($contact['id']),
192 if (! strlen($last_update)) {
193 $last_update = 'now -30 days';
196 if (isset($category)) {
197 $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` ",
198 dbesc(protect_sprintf($category)), intval(TERM_OBJ_POST), intval(TERM_CATEGORY), intval($owner_id));
199 //$sql_extra .= file_tag_file_query('item',$category,'category');
204 $sql_extra .= " AND `contact`.`self` = 1 ";
208 $check_date = datetime_convert('UTC','UTC',$last_update,'Y-m-d H:i:s');
210 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`,
211 `contact`.`name`, `contact`.`network`, `contact`.`photo`, `contact`.`url`,
212 `contact`.`name-date`, `contact`.`uri-date`, `contact`.`avatar-date`,
213 `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
214 `sign`.`signed_text`, `sign`.`signature`, `sign`.`signer`
215 FROM `item` USE INDEX (`uid_wall_changed`) $sql_post_table
216 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
217 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
218 LEFT JOIN `sign` ON `sign`.`iid` = `item`.`id`
219 WHERE `item`.`uid` = %d AND `item`.`visible` AND NOT `item`.`moderated` AND `item`.`parent` != 0
220 AND `item`.`wall` AND `item`.`changed` > '%s'
222 ORDER BY `item`.`parent` ".$sort.", `item`.`created` ASC LIMIT 0, 300",
229 * Will check further below if this actually returned results.
230 * We will provide an empty feed if that is the case.
235 $doc = new DOMDocument('1.0', 'utf-8');
236 $doc->formatOutput = true;
238 $alternatelink = $owner['url'];
240 if (isset($category)) {
241 $alternatelink .= "/category/".$category;
245 $author = "dfrn:owner";
250 $root = self::add_header($doc, $owner, $author, $alternatelink, true);
252 /// @TODO This hook can't work anymore
253 // call_hooks('atom_feed', $atom);
255 if (!Dbm::is_result($items) || $onlyheader) {
256 $atom = trim($doc->saveXML());
258 call_hooks('atom_feed_end', $atom);
263 foreach ($items as $item) {
265 // prevent private email from leaking.
266 if ($item['network'] == NETWORK_MAIL) {
270 // public feeds get html, our own nodes use bbcode
274 // catch any email that's in a public conversation and make sure it doesn't leak
275 if ($item['private']) {
282 $entry = self::entry($doc, $type, $item, $owner, true);
283 $root->appendChild($entry);
287 $atom = trim($doc->saveXML());
289 call_hooks('atom_feed_end', $atom);
295 * @brief Generate an atom entry for a given item id
297 * @param int $item_id The item id
298 * @param boolean $conversation Show the conversation. If false show the single post.
300 * @return string DFRN feed entry
302 public static function itemFeed($item_id, $conversation = false) {
304 $condition = '`item`.`parent`';
306 $condition = '`item`.`id`';
309 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`,
310 `contact`.`name`, `contact`.`network`, `contact`.`photo`, `contact`.`url`,
311 `contact`.`name-date`, `contact`.`uri-date`, `contact`.`avatar-date`,
312 `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
313 `sign`.`signed_text`, `sign`.`signature`, `sign`.`signer`
315 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
316 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
317 LEFT JOIN `sign` ON `sign`.`iid` = `item`.`id`
318 WHERE %s = %d AND `item`.`visible` AND NOT `item`.`moderated` AND `item`.`parent` != 0
319 AND NOT `item`.`private`",
324 if (!Dbm::is_result($r)) {
331 $r = q("SELECT `contact`.*, `user`.`nickname`, `user`.`timezone`, `user`.`page-flags`, `user`.`account-type`
332 FROM `contact` INNER JOIN `user` ON `user`.`uid` = `contact`.`uid`
333 WHERE `contact`.`self` AND `user`.`uid` = %d LIMIT 1",
337 if (!Dbm::is_result($r)) {
343 $doc = new DOMDocument('1.0', 'utf-8');
344 $doc->formatOutput = true;
348 $root = $doc->createElementNS(NAMESPACE_ATOM1, 'feed');
349 $doc->appendChild($root);
351 $root->setAttribute("xmlns:thr", NAMESPACE_THREAD);
352 $root->setAttribute("xmlns:at", NAMESPACE_TOMB);
353 $root->setAttribute("xmlns:media", NAMESPACE_MEDIA);
354 $root->setAttribute("xmlns:dfrn", NAMESPACE_DFRN);
355 $root->setAttribute("xmlns:activity", NAMESPACE_ACTIVITY);
356 $root->setAttribute("xmlns:georss", NAMESPACE_GEORSS);
357 $root->setAttribute("xmlns:poco", NAMESPACE_POCO);
358 $root->setAttribute("xmlns:ostatus", NAMESPACE_OSTATUS);
359 $root->setAttribute("xmlns:statusnet", NAMESPACE_STATUSNET);
361 //$root = self::add_header($doc, $owner, "dfrn:owner", "", false);
363 foreach ($items as $item) {
364 $entry = self::entry($doc, $type, $item, $owner, true, 0);
365 $root->appendChild($entry);
368 $root = self::entry($doc, $type, $item, $owner, true, 0, true);
371 $atom = trim($doc->saveXML());
376 * @brief Create XML text for DFRN mails
378 * @param array $item message elements
379 * @param array $owner Owner record
381 * @return string DFRN mail
382 * @todo Add type-hints
384 public static function mail($item, $owner) {
385 $doc = new DOMDocument('1.0', 'utf-8');
386 $doc->formatOutput = true;
388 $root = self::add_header($doc, $owner, "dfrn:owner", "", false);
390 $mail = $doc->createElement("dfrn:mail");
391 $sender = $doc->createElement("dfrn:sender");
393 xml::add_element($doc, $sender, "dfrn:name", $owner['name']);
394 xml::add_element($doc, $sender, "dfrn:uri", $owner['url']);
395 xml::add_element($doc, $sender, "dfrn:avatar", $owner['thumb']);
397 $mail->appendChild($sender);
399 xml::add_element($doc, $mail, "dfrn:id", $item['uri']);
400 xml::add_element($doc, $mail, "dfrn:in-reply-to", $item['parent-uri']);
401 xml::add_element($doc, $mail, "dfrn:sentdate", datetime_convert('UTC', 'UTC', $item['created'] . '+00:00' , ATOM_TIME));
402 xml::add_element($doc, $mail, "dfrn:subject", $item['title']);
403 xml::add_element($doc, $mail, "dfrn:content", $item['body']);
405 $root->appendChild($mail);
407 return(trim($doc->saveXML()));
411 * @brief Create XML text for DFRN friend suggestions
413 * @param array $item suggestion elements
414 * @param array $owner Owner record
416 * @return string DFRN suggestions
417 * @todo Add type-hints
419 public static function fsuggest($item, $owner) {
420 $doc = new DOMDocument('1.0', 'utf-8');
421 $doc->formatOutput = true;
423 $root = self::add_header($doc, $owner, "dfrn:owner", "", false);
425 $suggest = $doc->createElement("dfrn:suggest");
427 xml::add_element($doc, $suggest, "dfrn:url", $item['url']);
428 xml::add_element($doc, $suggest, "dfrn:name", $item['name']);
429 xml::add_element($doc, $suggest, "dfrn:photo", $item['photo']);
430 xml::add_element($doc, $suggest, "dfrn:request", $item['request']);
431 xml::add_element($doc, $suggest, "dfrn:note", $item['note']);
433 $root->appendChild($suggest);
435 return(trim($doc->saveXML()));
439 * @brief Create XML text for DFRN relocations
441 * @param array $owner Owner record
442 * @param int $uid User ID
444 * @return string DFRN relocations
445 * @todo Add type-hints
447 public static function relocate($owner, $uid) {
449 /* get site pubkey. this could be a new installation with no site keys*/
450 $pubkey = Config::get('system','site_pubkey');
452 $res = new_keypair(1024);
453 Config::set('system','site_prvkey', $res['prvkey']);
454 Config::set('system','site_pubkey', $res['pubkey']);
457 $rp = q("SELECT `resource-id` , `scale`, type FROM `photo`
458 WHERE `profile` = 1 AND `uid` = %d ORDER BY scale;", $uid);
460 $ext = Photo::supportedTypes();
462 foreach ($rp as $p) {
463 $photos[$p['scale']] = System::baseUrl().'/photo/'.$p['resource-id'].'-'.$p['scale'].'.'.$ext[$p['type']];
468 $doc = new DOMDocument('1.0', 'utf-8');
469 $doc->formatOutput = true;
471 $root = self::add_header($doc, $owner, "dfrn:owner", "", false);
473 $relocate = $doc->createElement("dfrn:relocate");
475 xml::add_element($doc, $relocate, "dfrn:url", $owner['url']);
476 xml::add_element($doc, $relocate, "dfrn:name", $owner['name']);
477 xml::add_element($doc, $relocate, "dfrn:addr", $owner['addr']);
478 xml::add_element($doc, $relocate, "dfrn:avatar", $owner['avatar']);
479 xml::add_element($doc, $relocate, "dfrn:photo", $photos[4]);
480 xml::add_element($doc, $relocate, "dfrn:thumb", $photos[5]);
481 xml::add_element($doc, $relocate, "dfrn:micro", $photos[6]);
482 xml::add_element($doc, $relocate, "dfrn:request", $owner['request']);
483 xml::add_element($doc, $relocate, "dfrn:confirm", $owner['confirm']);
484 xml::add_element($doc, $relocate, "dfrn:notify", $owner['notify']);
485 xml::add_element($doc, $relocate, "dfrn:poll", $owner['poll']);
486 xml::add_element($doc, $relocate, "dfrn:sitepubkey", Config::get('system','site_pubkey'));
488 $root->appendChild($relocate);
490 return(trim($doc->saveXML()));
494 * @brief Adds the header elements for the DFRN protocol
496 * @param object $doc XML document
497 * @param array $owner Owner record
498 * @param string $authorelement Element name for the author
499 * @param string $alternatelink link to profile or category
500 * @param bool $public Is it a header for public posts?
502 * @return object XML root object
503 * @todo Add type-hints
505 private static function add_header($doc, $owner, $authorelement, $alternatelink = "", $public = false) {
507 if ($alternatelink == "") {
508 $alternatelink = $owner['url'];
511 $root = $doc->createElementNS(NAMESPACE_ATOM1, 'feed');
512 $doc->appendChild($root);
514 $root->setAttribute("xmlns:thr", NAMESPACE_THREAD);
515 $root->setAttribute("xmlns:at", NAMESPACE_TOMB);
516 $root->setAttribute("xmlns:media", NAMESPACE_MEDIA);
517 $root->setAttribute("xmlns:dfrn", NAMESPACE_DFRN);
518 $root->setAttribute("xmlns:activity", NAMESPACE_ACTIVITY);
519 $root->setAttribute("xmlns:georss", NAMESPACE_GEORSS);
520 $root->setAttribute("xmlns:poco", NAMESPACE_POCO);
521 $root->setAttribute("xmlns:ostatus", NAMESPACE_OSTATUS);
522 $root->setAttribute("xmlns:statusnet", NAMESPACE_STATUSNET);
524 xml::add_element($doc, $root, "id", System::baseUrl()."/profile/".$owner["nick"]);
525 xml::add_element($doc, $root, "title", $owner["name"]);
527 $attributes = array("uri" => "https://friendi.ca", "version" => FRIENDICA_VERSION."-".DB_UPDATE_VERSION);
528 xml::add_element($doc, $root, "generator", FRIENDICA_PLATFORM, $attributes);
530 $attributes = array("rel" => "license", "href" => "http://creativecommons.org/licenses/by/3.0/");
531 xml::add_element($doc, $root, "link", "", $attributes);
533 $attributes = array("rel" => "alternate", "type" => "text/html", "href" => $alternatelink);
534 xml::add_element($doc, $root, "link", "", $attributes);
538 // DFRN itself doesn't uses this. But maybe someone else wants to subscribe to the public feed.
539 ostatus::hublinks($doc, $root, $owner["nick"]);
541 $attributes = array("rel" => "salmon", "href" => System::baseUrl()."/salmon/".$owner["nick"]);
542 xml::add_element($doc, $root, "link", "", $attributes);
544 $attributes = array("rel" => "http://salmon-protocol.org/ns/salmon-replies", "href" => System::baseUrl()."/salmon/".$owner["nick"]);
545 xml::add_element($doc, $root, "link", "", $attributes);
547 $attributes = array("rel" => "http://salmon-protocol.org/ns/salmon-mention", "href" => System::baseUrl()."/salmon/".$owner["nick"]);
548 xml::add_element($doc, $root, "link", "", $attributes);
551 // For backward compatibility we keep this element
552 if ($owner['page-flags'] == PAGE_COMMUNITY) {
553 xml::add_element($doc, $root, "dfrn:community", 1);
556 // The former element is replaced by this one
557 xml::add_element($doc, $root, "dfrn:account_type", $owner["account-type"]);
559 /// @todo We need a way to transmit the different page flags like "PAGE_PRVGROUP"
561 xml::add_element($doc, $root, "updated", datetime_convert("UTC", "UTC", "now", ATOM_TIME));
563 $author = self::add_author($doc, $owner, $authorelement, $public);
564 $root->appendChild($author);
570 * @brief Adds the author element in the header for the DFRN protocol
572 * @param object $doc XML document
573 * @param array $owner Owner record
574 * @param string $authorelement Element name for the author
576 * @return object XML author object
577 * @todo Add type-hints
579 private static function add_author($doc, $owner, $authorelement, $public) {
581 // Is the profile hidden or shouldn't be published in the net? Then add the "hide" element
582 $r = q("SELECT `id` FROM `profile` INNER JOIN `user` ON `user`.`uid` = `profile`.`uid`
583 WHERE (`hidewall` OR NOT `net-publish`) AND `user`.`uid` = %d",
584 intval($owner['uid']));
585 if (Dbm::is_result($r)) {
591 $author = $doc->createElement($authorelement);
593 $namdate = datetime_convert('UTC', 'UTC', $owner['name-date'].'+00:00', ATOM_TIME);
594 $uridate = datetime_convert('UTC', 'UTC', $owner['uri-date'].'+00:00', ATOM_TIME);
595 $picdate = datetime_convert('UTC', 'UTC', $owner['avatar-date'].'+00:00', ATOM_TIME);
597 $attributes = array();
599 if (!$public || !$hidewall) {
600 $attributes = array("dfrn:updated" => $namdate);
603 xml::add_element($doc, $author, "name", $owner["name"], $attributes);
604 xml::add_element($doc, $author, "uri", System::baseUrl().'/profile/'.$owner["nickname"], $attributes);
605 xml::add_element($doc, $author, "dfrn:handle", $owner["addr"], $attributes);
607 $attributes = array("rel" => "photo", "type" => "image/jpeg",
608 "media:width" => 175, "media:height" => 175, "href" => $owner['photo']);
610 if (!$public || !$hidewall) {
611 $attributes["dfrn:updated"] = $picdate;
614 xml::add_element($doc, $author, "link", "", $attributes);
616 $attributes["rel"] = "avatar";
617 xml::add_element($doc, $author, "link", "", $attributes);
620 xml::add_element($doc, $author, "dfrn:hide", "true");
623 // The following fields will only be generated if the data isn't meant for a public feed
628 $birthday = feed_birthday($owner['uid'], $owner['timezone']);
631 xml::add_element($doc, $author, "dfrn:birthday", $birthday);
633 // Only show contact details when we are allowed to
634 $r = q("SELECT `profile`.`about`, `profile`.`name`, `profile`.`homepage`, `user`.`nickname`,
635 `user`.`timezone`, `profile`.`locality`, `profile`.`region`, `profile`.`country-name`,
636 `profile`.`pub_keywords`, `profile`.`xmpp`, `profile`.`dob`
638 INNER JOIN `user` ON `user`.`uid` = `profile`.`uid`
639 WHERE `profile`.`is-default` AND NOT `user`.`hidewall` AND `user`.`uid` = %d",
640 intval($owner['uid']));
641 if (Dbm::is_result($r)) {
644 xml::add_element($doc, $author, "poco:displayName", $profile["name"]);
645 xml::add_element($doc, $author, "poco:updated", $namdate);
647 if (trim($profile["dob"]) > '0001-01-01') {
648 xml::add_element($doc, $author, "poco:birthday", "0000-".date("m-d", strtotime($profile["dob"])));
651 xml::add_element($doc, $author, "poco:note", $profile["about"]);
652 xml::add_element($doc, $author, "poco:preferredUsername", $profile["nickname"]);
654 $savetz = date_default_timezone_get();
655 date_default_timezone_set($profile["timezone"]);
656 xml::add_element($doc, $author, "poco:utcOffset", date("P"));
657 date_default_timezone_set($savetz);
659 if (trim($profile["homepage"]) != "") {
660 $urls = $doc->createElement("poco:urls");
661 xml::add_element($doc, $urls, "poco:type", "homepage");
662 xml::add_element($doc, $urls, "poco:value", $profile["homepage"]);
663 xml::add_element($doc, $urls, "poco:primary", "true");
664 $author->appendChild($urls);
667 if (trim($profile["pub_keywords"]) != "") {
668 $keywords = explode(",", $profile["pub_keywords"]);
670 foreach ($keywords AS $keyword) {
671 xml::add_element($doc, $author, "poco:tags", trim($keyword));
676 if (trim($profile["xmpp"]) != "") {
677 $ims = $doc->createElement("poco:ims");
678 xml::add_element($doc, $ims, "poco:type", "xmpp");
679 xml::add_element($doc, $ims, "poco:value", $profile["xmpp"]);
680 xml::add_element($doc, $ims, "poco:primary", "true");
681 $author->appendChild($ims);
684 if (trim($profile["locality"].$profile["region"].$profile["country-name"]) != "") {
685 $element = $doc->createElement("poco:address");
687 xml::add_element($doc, $element, "poco:formatted", formatted_location($profile));
689 if (trim($profile["locality"]) != "") {
690 xml::add_element($doc, $element, "poco:locality", $profile["locality"]);
693 if (trim($profile["region"]) != "") {
694 xml::add_element($doc, $element, "poco:region", $profile["region"]);
697 if (trim($profile["country-name"]) != "") {
698 xml::add_element($doc, $element, "poco:country", $profile["country-name"]);
701 $author->appendChild($element);
709 * @brief Adds the author elements in the "entry" elements of the DFRN protocol
711 * @param object $doc XML document
712 * @param string $element Element name for the author
713 * @param string $contact_url Link of the contact
714 * @param array $items Item elements
716 * @return object XML author object
717 * @todo Add type-hints
719 private static function add_entry_author($doc, $element, $contact_url, $item) {
721 $contact = get_contact_details_by_url($contact_url, $item["uid"]);
723 $author = $doc->createElement($element);
724 xml::add_element($doc, $author, "name", $contact["name"]);
725 xml::add_element($doc, $author, "uri", $contact["url"]);
726 xml::add_element($doc, $author, "dfrn:handle", $contact["addr"]);
729 /// - Check real image type and image size
730 /// - Check which of these boths elements we should use
733 "type" => "image/jpeg",
735 "media:height" => 80,
736 "href" => $contact["photo"]);
737 xml::add_element($doc, $author, "link", "", $attributes);
741 "type" => "image/jpeg",
743 "media:height" => 80,
744 "href" => $contact["photo"]);
745 xml::add_element($doc, $author, "link", "", $attributes);
751 * @brief Adds the activity elements
753 * @param object $doc XML document
754 * @param string $element Element name for the activity
755 * @param string $activity activity value
757 * @return object XML activity object
758 * @todo Add type-hints
760 private static function create_activity($doc, $element, $activity) {
763 $entry = $doc->createElement($element);
765 $r = parse_xml_string($activity, false);
770 xml::add_element($doc, $entry, "activity:object-type", $r->type);
773 xml::add_element($doc, $entry, "id", $r->id);
776 xml::add_element($doc, $entry, "title", $r->title);
780 if (substr($r->link, 0, 1) == '<') {
781 if (strstr($r->link, '&') && (! strstr($r->link, '&'))) {
782 $r->link = str_replace('&', '&', $r->link);
785 $r->link = preg_replace('/\<link(.*?)\"\>/', '<link$1"/>', $r->link);
787 // XML does need a single element as root element so we add a dummy element here
788 $data = parse_xml_string("<dummy>" . $r->link . "</dummy>", false);
789 if (is_object($data)) {
790 foreach ($data->link AS $link) {
791 $attributes = array();
792 foreach ($link->attributes() AS $parameter => $value) {
793 $attributes[$parameter] = $value;
795 xml::add_element($doc, $entry, "link", "", $attributes);
799 $attributes = array("rel" => "alternate", "type" => "text/html", "href" => $r->link);
800 xml::add_element($doc, $entry, "link", "", $attributes);
804 xml::add_element($doc, $entry, "content", bbcode($r->content), array("type" => "html"));
814 * @brief Adds the elements for attachments
816 * @param object $doc XML document
817 * @param object $root XML root
818 * @param array $item Item element
820 * @return object XML attachment object
821 * @todo Add type-hints
823 private static function get_attachment($doc, $root, $item) {
824 $arr = explode('[/attach],',$item['attach']);
826 foreach ($arr as $r) {
828 $cnt = preg_match('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\" title=\"(.*?)\"|',$r,$matches);
830 $attributes = array("rel" => "enclosure",
831 "href" => $matches[1],
832 "type" => $matches[3]);
834 if (intval($matches[2])) {
835 $attributes["length"] = intval($matches[2]);
838 if (trim($matches[4]) != "") {
839 $attributes["title"] = trim($matches[4]);
842 xml::add_element($doc, $root, "link", "", $attributes);
849 * @brief Adds the "entry" elements for the DFRN protocol
851 * @param object $doc XML document
852 * @param string $type "text" or "html"
853 * @param array $item Item element
854 * @param array $owner Owner record
855 * @param bool $comment Trigger the sending of the "comment" element
856 * @param int $cid Contact ID of the recipient
857 * @param bool $single If set, the entry is created as an XML document with a single "entry" element
859 * @return object XML entry object
860 * @todo Add type-hints
862 private static function entry($doc, $type, $item, $owner, $comment = false, $cid = 0, $single = false) {
864 $mentioned = array();
866 if (!$item['parent']) {
870 if ($item['deleted']) {
871 $attributes = array("ref" => $item['uri'], "when" => datetime_convert('UTC','UTC',$item['edited'] . '+00:00',ATOM_TIME));
872 return xml::create_element($doc, "at:deleted-entry", "", $attributes);
876 $entry = $doc->createElement("entry");
878 $entry = $doc->createElementNS(NAMESPACE_ATOM1, 'entry');
879 $doc->appendChild($entry);
881 $entry->setAttribute("xmlns:thr", NAMESPACE_THREAD);
882 $entry->setAttribute("xmlns:at", NAMESPACE_TOMB);
883 $entry->setAttribute("xmlns:media", NAMESPACE_MEDIA);
884 $entry->setAttribute("xmlns:dfrn", NAMESPACE_DFRN);
885 $entry->setAttribute("xmlns:activity", NAMESPACE_ACTIVITY);
886 $entry->setAttribute("xmlns:georss", NAMESPACE_GEORSS);
887 $entry->setAttribute("xmlns:poco", NAMESPACE_POCO);
888 $entry->setAttribute("xmlns:ostatus", NAMESPACE_OSTATUS);
889 $entry->setAttribute("xmlns:statusnet", NAMESPACE_STATUSNET);
892 if ($item['allow_cid'] || $item['allow_gid'] || $item['deny_cid'] || $item['deny_gid']) {
893 $body = fix_private_photos($item['body'],$owner['uid'],$item,$cid);
895 $body = $item['body'];
898 // Remove the abstract element. It is only locally important.
899 $body = remove_abstract($body);
901 if ($type == 'html') {
904 if ($item['title'] != "") {
905 $htmlbody = "[b]".$item['title']."[/b]\n\n".$htmlbody;
908 $htmlbody = bbcode($htmlbody, false, false, 7);
911 $author = self::add_entry_author($doc, "author", $item["author-link"], $item);
912 $entry->appendChild($author);
914 $dfrnowner = self::add_entry_author($doc, "dfrn:owner", $item["owner-link"], $item);
915 $entry->appendChild($dfrnowner);
917 if (($item['parent'] != $item['id']) || ($item['parent-uri'] !== $item['uri']) || (($item['thr-parent'] !== '') && ($item['thr-parent'] !== $item['uri']))) {
918 $parent_item = (($item['thr-parent']) ? $item['thr-parent'] : $item['parent-uri']);
919 $parent = q("SELECT `guid`,`plink` FROM `item` WHERE `uri` = '%s' AND `uid` = %d", dbesc($parent_item), intval($item['uid']));
920 $attributes = array("ref" => $parent_item, "type" => "text/html",
921 "href" => $parent[0]['plink'],
922 "dfrn:diaspora_guid" => $parent[0]['guid']);
923 xml::add_element($doc, $entry, "thr:in-reply-to", "", $attributes);
926 // Add conversation data. This is used for OStatus
927 $conversation_href = System::baseUrl()."/display/".$owner["nick"]."/".$item["parent"];
928 $conversation_uri = $conversation_href;
930 if (isset($parent_item)) {
931 $r = dba::fetch_first("SELECT `conversation-uri`, `conversation-href` FROM `conversation` WHERE `item-uri` = ?", $item['parent-uri']);
932 if (Dbm::is_result($r)) {
933 if ($r['conversation-uri'] != '') {
934 $conversation_uri = $r['conversation-uri'];
936 if ($r['conversation-href'] != '') {
937 $conversation_href = $r['conversation-href'];
943 "href" => $conversation_href,
944 "ref" => $conversation_uri);
946 xml::add_element($doc, $entry, "ostatus:conversation", $conversation_uri, $attributes);
948 xml::add_element($doc, $entry, "id", $item["uri"]);
949 xml::add_element($doc, $entry, "title", $item["title"]);
951 xml::add_element($doc, $entry, "published", datetime_convert("UTC","UTC",$item["created"]."+00:00",ATOM_TIME));
952 xml::add_element($doc, $entry, "updated", datetime_convert("UTC","UTC",$item["edited"]."+00:00",ATOM_TIME));
954 // "dfrn:env" is used to read the content
955 xml::add_element($doc, $entry, "dfrn:env", base64url_encode($body, true));
957 // The "content" field is not read by the receiver. We could remove it when the type is "text"
958 // We keep it at the moment, maybe there is some old version that doesn't read "dfrn:env"
959 xml::add_element($doc, $entry, "content", (($type == 'html') ? $htmlbody : $body), array("type" => $type));
961 // We save this value in "plink". Maybe we should read it from there as well?
962 xml::add_element($doc, $entry, "link", "", array("rel" => "alternate", "type" => "text/html",
963 "href" => System::baseUrl()."/display/".$item["guid"]));
965 // "comment-allow" is some old fashioned stuff for old Friendica versions.
966 // It is included in the rewritten code for completeness
968 xml::add_element($doc, $entry, "dfrn:comment-allow", intval($item['last-child']));
971 if ($item['location']) {
972 xml::add_element($doc, $entry, "dfrn:location", $item['location']);
975 if ($item['coord']) {
976 xml::add_element($doc, $entry, "georss:point", $item['coord']);
979 if (($item['private']) || strlen($item['allow_cid']) || strlen($item['allow_gid']) || strlen($item['deny_cid']) || strlen($item['deny_gid'])) {
980 xml::add_element($doc, $entry, "dfrn:private", (($item['private']) ? $item['private'] : 1));
983 if ($item['extid']) {
984 xml::add_element($doc, $entry, "dfrn:extid", $item['extid']);
987 if ($item['bookmark']) {
988 xml::add_element($doc, $entry, "dfrn:bookmark", "true");
992 xml::add_element($doc, $entry, "statusnet:notice_info", "", array("local_id" => $item['id'], "source" => $item['app']));
995 xml::add_element($doc, $entry, "dfrn:diaspora_guid", $item["guid"]);
997 // The signed text contains the content in Markdown, the sender handle and the signatur for the content
998 // It is needed for relayed comments to Diaspora.
999 if ($item['signed_text']) {
1000 $sign = base64_encode(json_encode(array('signed_text' => $item['signed_text'],'signature' => $item['signature'],'signer' => $item['signer'])));
1001 xml::add_element($doc, $entry, "dfrn:diaspora_signature", $sign);
1004 xml::add_element($doc, $entry, "activity:verb", construct_verb($item));
1006 if ($item['object-type'] != "") {
1007 xml::add_element($doc, $entry, "activity:object-type", $item['object-type']);
1008 } elseif ($item['id'] == $item['parent']) {
1009 xml::add_element($doc, $entry, "activity:object-type", ACTIVITY_OBJ_NOTE);
1011 xml::add_element($doc, $entry, "activity:object-type", ACTIVITY_OBJ_COMMENT);
1014 $actobj = self::create_activity($doc, "activity:object", $item['object']);
1016 $entry->appendChild($actobj);
1019 $actarg = self::create_activity($doc, "activity:target", $item['target']);
1021 $entry->appendChild($actarg);
1024 $tags = item_getfeedtags($item);
1027 foreach ($tags as $t) {
1028 if (($type != 'html') || ($t[0] != "@")) {
1029 xml::add_element($doc, $entry, "category", "", array("scheme" => "X-DFRN:".$t[0].":".$t[1], "term" => $t[2]));
1035 foreach ($tags as $t) {
1037 $mentioned[$t[1]] = $t[1];
1042 foreach ($mentioned AS $mention) {
1043 $r = q("SELECT `forum`, `prv` FROM `contact` WHERE `uid` = %d AND `nurl` = '%s'",
1044 intval($owner["uid"]),
1045 dbesc(normalise_link($mention)));
1047 if (Dbm::is_result($r) && ($r[0]["forum"] || $r[0]["prv"])) {
1048 xml::add_element($doc, $entry, "link", "", array("rel" => "mentioned",
1049 "ostatus:object-type" => ACTIVITY_OBJ_GROUP,
1050 "href" => $mention));
1052 xml::add_element($doc, $entry, "link", "", array("rel" => "mentioned",
1053 "ostatus:object-type" => ACTIVITY_OBJ_PERSON,
1054 "href" => $mention));
1058 self::get_attachment($doc, $entry, $item);
1064 * @brief encrypts data via AES
1066 * @param string $data The data that is to be encrypted
1067 * @param string $key The AES key
1069 * @return string encrypted data
1071 private static function aes_encrypt($data, $key) {
1072 return openssl_encrypt($data, 'aes-128-ecb', $key, OPENSSL_RAW_DATA);
1076 * @brief decrypts data via AES
1078 * @param string $encrypted The encrypted data
1079 * @param string $key The AES key
1081 * @return string decrypted data
1083 public static function aes_decrypt($encrypted, $key) {
1084 return openssl_decrypt($encrypted, 'aes-128-ecb', $key, OPENSSL_RAW_DATA);
1088 * @brief Delivers the atom content to the contacts
1090 * @param array $owner Owner record
1091 * @param array $contactr Contact record of the receiver
1092 * @param string $atom Content that will be transmitted
1093 * @param bool $dissolve (to be documented)
1095 * @return int Deliver status. -1 means an error.
1096 * @todo Add array type-hint for $owner, $contact
1098 public static function deliver($owner,$contact,$atom, $dissolve = false) {
1102 $idtosend = $orig_id = (($contact['dfrn-id']) ? $contact['dfrn-id'] : $contact['issued-id']);
1104 if ($contact['duplex'] && $contact['dfrn-id']) {
1105 $idtosend = '0:' . $orig_id;
1107 if ($contact['duplex'] && $contact['issued-id']) {
1108 $idtosend = '1:' . $orig_id;
1111 $rino = Config::get('system', 'rino_encrypt');
1112 $rino = intval($rino);
1114 logger("Local rino version: ". $rino, LOGGER_DEBUG);
1116 $ssl_val = intval(Config::get('system','ssl_policy'));
1120 case SSL_POLICY_FULL:
1121 $ssl_policy = 'full';
1123 case SSL_POLICY_SELFSIGN:
1124 $ssl_policy = 'self';
1126 case SSL_POLICY_NONE:
1128 $ssl_policy = 'none';
1132 $url = $contact['notify'] . '&dfrn_id=' . $idtosend . '&dfrn_version=' . DFRN_PROTOCOL_VERSION . (($rino) ? '&rino='.$rino : '');
1134 logger('dfrn_deliver: ' . $url);
1136 $ret = z_fetch_url($url);
1138 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
1139 return -2; // timed out
1142 $xml = $ret['body'];
1144 $curl_stat = $a->get_curl_code();
1146 return -3; // timed out
1149 logger('dfrn_deliver: ' . $xml, LOGGER_DATA);
1155 if (strpos($xml,'<?xml') === false) {
1156 logger('dfrn_deliver: no valid XML returned');
1157 logger('dfrn_deliver: returned XML: ' . $xml, LOGGER_DATA);
1161 $res = parse_xml_string($xml);
1163 if ((intval($res->status) != 0) || (! strlen($res->challenge)) || (! strlen($res->dfrn_id))) {
1164 return (($res->status) ? $res->status : 3);
1167 $postvars = array();
1168 $sent_dfrn_id = hex2bin((string) $res->dfrn_id);
1169 $challenge = hex2bin((string) $res->challenge);
1170 $perm = (($res->perm) ? $res->perm : null);
1171 $dfrn_version = (float) (($res->dfrn_version) ? $res->dfrn_version : 2.0);
1172 $rino_remote_version = intval($res->rino);
1173 $page = (($owner['page-flags'] == PAGE_COMMUNITY) ? 1 : 0);
1175 logger("Remote rino version: ".$rino_remote_version." for ".$contact["url"], LOGGER_DEBUG);
1177 if ($owner['page-flags'] == PAGE_PRVGROUP) {
1181 $final_dfrn_id = '';
1184 if ((($perm == 'rw') && (! intval($contact['writable'])))
1185 || (($perm == 'r') && (intval($contact['writable'])))) {
1186 q("update contact set writable = %d where id = %d",
1187 intval(($perm == 'rw') ? 1 : 0),
1188 intval($contact['id'])
1190 $contact['writable'] = (string) 1 - intval($contact['writable']);
1194 if (($contact['duplex'] && strlen($contact['pubkey']))
1195 || ($owner['page-flags'] == PAGE_COMMUNITY && strlen($contact['pubkey']))
1196 || ($contact['rel'] == CONTACT_IS_SHARING && strlen($contact['pubkey']))) {
1197 openssl_public_decrypt($sent_dfrn_id,$final_dfrn_id,$contact['pubkey']);
1198 openssl_public_decrypt($challenge,$postvars['challenge'],$contact['pubkey']);
1200 openssl_private_decrypt($sent_dfrn_id,$final_dfrn_id,$contact['prvkey']);
1201 openssl_private_decrypt($challenge,$postvars['challenge'],$contact['prvkey']);
1204 $final_dfrn_id = substr($final_dfrn_id, 0, strpos($final_dfrn_id, '.'));
1206 if (strpos($final_dfrn_id,':') == 1) {
1207 $final_dfrn_id = substr($final_dfrn_id,2);
1210 if ($final_dfrn_id != $orig_id) {
1211 logger('dfrn_deliver: wrong dfrn_id.');
1212 // did not decode properly - cannot trust this site
1216 $postvars['dfrn_id'] = $idtosend;
1217 $postvars['dfrn_version'] = DFRN_PROTOCOL_VERSION;
1219 $postvars['dissolve'] = '1';
1223 if ((($contact['rel']) && ($contact['rel'] != CONTACT_IS_SHARING) && (! $contact['blocked'])) || ($owner['page-flags'] == PAGE_COMMUNITY)) {
1224 $postvars['data'] = $atom;
1225 $postvars['perm'] = 'rw';
1227 $postvars['data'] = str_replace('<dfrn:comment-allow>1','<dfrn:comment-allow>0',$atom);
1228 $postvars['perm'] = 'r';
1231 $postvars['ssl_policy'] = $ssl_policy;
1234 $postvars['page'] = $page;
1238 if ($rino > 0 && $rino_remote_version > 0 && (! $dissolve)) {
1239 logger('rino version: '. $rino_remote_version);
1241 switch ($rino_remote_version) {
1243 // Deprecated rino version!
1244 $key = openssl_random_pseudo_bytes(16);
1245 $data = self::aes_encrypt($postvars['data'], $key);
1248 // RINO 2 based on php-encryption
1250 $key = Crypto::createNewRandomKey();
1251 } catch (CryptoTestFailed $ex) {
1252 logger('Cannot safely create a key');
1254 } catch (CannotPerformOperation $ex) {
1255 logger('Cannot safely create a key');
1259 $data = Crypto::encrypt($postvars['data'], $key);
1260 } catch (CryptoTestFailed $ex) {
1261 logger('Cannot safely perform encryption');
1263 } catch (CannotPerformOperation $ex) {
1264 logger('Cannot safely perform encryption');
1269 logger("rino: invalid requested verision '$rino_remote_version'");
1273 $postvars['rino'] = $rino_remote_version;
1274 $postvars['data'] = bin2hex($data);
1276 //logger('rino: sent key = ' . $key, LOGGER_DEBUG);
1279 if ($dfrn_version >= 2.1) {
1280 if (($contact['duplex'] && strlen($contact['pubkey']))
1281 || ($owner['page-flags'] == PAGE_COMMUNITY && strlen($contact['pubkey']))
1282 || ($contact['rel'] == CONTACT_IS_SHARING && strlen($contact['pubkey']))) {
1283 openssl_public_encrypt($key,$postvars['key'],$contact['pubkey']);
1285 openssl_private_encrypt($key,$postvars['key'],$contact['prvkey']);
1289 if (($contact['duplex'] && strlen($contact['prvkey'])) || ($owner['page-flags'] == PAGE_COMMUNITY)) {
1290 openssl_private_encrypt($key,$postvars['key'],$contact['prvkey']);
1292 openssl_public_encrypt($key,$postvars['key'],$contact['pubkey']);
1297 logger('md5 rawkey ' . md5($postvars['key']));
1299 $postvars['key'] = bin2hex($postvars['key']);
1303 logger('dfrn_deliver: ' . "SENDING: " . print_r($postvars,true), LOGGER_DATA);
1305 $xml = post_url($contact['notify'], $postvars);
1307 logger('dfrn_deliver: ' . "RECEIVED: " . $xml, LOGGER_DATA);
1309 $curl_stat = $a->get_curl_code();
1310 if ((!$curl_stat) || (!strlen($xml))) {
1311 return -9; // timed out
1314 if (($curl_stat == 503) && (stristr($a->get_curl_headers(),'retry-after'))) {
1318 if (strpos($xml,'<?xml') === false) {
1319 logger('dfrn_deliver: phase 2: no valid XML returned');
1320 logger('dfrn_deliver: phase 2: returned XML: ' . $xml, LOGGER_DATA);
1324 if ($contact['term-date'] > NULL_DATE) {
1325 logger("dfrn_deliver: $url back from the dead - removing mark for death");
1326 require_once('include/Contact.php');
1327 unmark_for_death($contact);
1330 $res = parse_xml_string($xml);
1332 if (!isset($res->status)) {
1336 if (!empty($res->message)) {
1337 logger('Delivery returned status '.$res->status.' - '.$res->message, LOGGER_DEBUG);
1340 return intval($res->status);
1344 * @brief Add new birthday event for this person
1346 * @param array $contact Contact record
1347 * @param string $birthday Birthday of the contact
1348 * @todo Add array type-hint for $contact
1350 private static function birthday_event($contact, $birthday) {
1352 // Check for duplicates
1353 $r = q("SELECT `id` FROM `event` WHERE `uid` = %d AND `cid` = %d AND `start` = '%s' AND `type` = '%s' LIMIT 1",
1354 intval($contact["uid"]),
1355 intval($contact["id"]),
1356 dbesc(datetime_convert("UTC","UTC", $birthday)),
1359 if (Dbm::is_result($r)) {
1363 logger("updating birthday: ".$birthday." for contact ".$contact["id"]);
1365 $bdtext = sprintf(t("%s\'s birthday"), $contact["name"]);
1366 $bdtext2 = sprintf(t("Happy Birthday %s"), " [url=".$contact["url"]."]".$contact["name"]."[/url]") ;
1368 $r = q("INSERT INTO `event` (`uid`,`cid`,`created`,`edited`,`start`,`finish`,`summary`,`desc`,`type`)
1369 VALUES ( %d, %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s') ",
1370 intval($contact["uid"]),
1371 intval($contact["id"]),
1372 dbesc(datetime_convert()),
1373 dbesc(datetime_convert()),
1374 dbesc(datetime_convert("UTC","UTC", $birthday)),
1375 dbesc(datetime_convert("UTC","UTC", $birthday." + 1 day ")),
1383 * @brief Fetch the author data from head or entry items
1385 * @param object $xpath XPath object
1386 * @param object $context In which context should the data be searched
1387 * @param array $importer Record of the importer user mixed with contact of the content
1388 * @param string $element Element name from which the data is fetched
1389 * @param bool $onlyfetch Should the data only be fetched or should it update the contact record as well
1391 * @return Returns an array with relevant data of the author
1392 * @todo Find good type-hints for all parameter
1394 private static function fetchauthor($xpath, $context, $importer, $element, $onlyfetch, $xml = "") {
1397 $author["name"] = $xpath->evaluate($element."/atom:name/text()", $context)->item(0)->nodeValue;
1398 $author["link"] = $xpath->evaluate($element."/atom:uri/text()", $context)->item(0)->nodeValue;
1400 $r = q("SELECT `id`, `uid`, `url`, `network`, `avatar-date`, `name-date`, `uri-date`, `addr`,
1401 `name`, `nick`, `about`, `location`, `keywords`, `xmpp`, `bdyear`, `bd`, `hidden`, `contact-type`
1402 FROM `contact` WHERE `uid` = %d AND `nurl` = '%s' AND `network` != '%s'",
1403 intval($importer["uid"]), dbesc(normalise_link($author["link"])), dbesc(NETWORK_STATUSNET));
1405 if (Dbm::is_result($r)) {
1407 $author["contact-id"] = $r[0]["id"];
1408 $author["network"] = $r[0]["network"];
1411 logger("Contact ".$author["link"]." wasn't found for user ".$importer["uid"]." XML: ".$xml, LOGGER_DEBUG);
1414 $author["contact-id"] = $importer["id"];
1415 $author["network"] = $importer["network"];
1419 // Until now we aren't serving different sizes - but maybe later
1420 $avatarlist = array();
1421 /// @todo check if "avatar" or "photo" would be the best field in the specification
1422 $avatars = $xpath->query($element."/atom:link[@rel='avatar']", $context);
1423 foreach ($avatars AS $avatar) {
1426 foreach ($avatar->attributes AS $attributes) {
1427 /// @TODO Rewrite these similar if () to one switch
1428 if ($attributes->name == "href") {
1429 $href = $attributes->textContent;
1431 if ($attributes->name == "width") {
1432 $width = $attributes->textContent;
1434 if ($attributes->name == "updated") {
1435 $contact["avatar-date"] = $attributes->textContent;
1438 if (($width > 0) && ($href != "")) {
1439 $avatarlist[$width] = $href;
1442 if (count($avatarlist) > 0) {
1443 krsort($avatarlist);
1444 $author["avatar"] = current($avatarlist);
1447 if (Dbm::is_result($r) && !$onlyfetch) {
1448 logger("Check if contact details for contact " . $r[0]["id"] . " (" . $r[0]["nick"] . ") have to be updated.", LOGGER_DEBUG);
1450 $poco = array("url" => $contact["url"]);
1452 // When was the last change to name or uri?
1453 $name_element = $xpath->query($element . "/atom:name", $context)->item(0);
1454 foreach ($name_element->attributes AS $attributes) {
1455 if ($attributes->name == "updated") {
1456 $poco["name-date"] = $attributes->textContent;
1460 $link_element = $xpath->query($element . "/atom:link", $context)->item(0);
1461 foreach ($link_element->attributes AS $attributes) {
1462 if ($attributes->name == "updated") {
1463 $poco["uri-date"] = $attributes->textContent;
1467 // Update contact data
1468 $value = $xpath->evaluate($element . "/dfrn:handle/text()", $context)->item(0)->nodeValue;
1470 $poco["addr"] = $value;
1473 $value = $xpath->evaluate($element . "/poco:displayName/text()", $context)->item(0)->nodeValue;
1475 $poco["name"] = $value;
1478 $value = $xpath->evaluate($element . "/poco:preferredUsername/text()", $context)->item(0)->nodeValue;
1480 $poco["nick"] = $value;
1483 $value = $xpath->evaluate($element . "/poco:note/text()", $context)->item(0)->nodeValue;
1485 $poco["about"] = $value;
1488 $value = $xpath->evaluate($element . "/poco:address/poco:formatted/text()", $context)->item(0)->nodeValue;
1490 $poco["location"] = $value;
1493 /// @todo Only search for elements with "poco:type" = "xmpp"
1494 $value = $xpath->evaluate($element . "/poco:ims/poco:value/text()", $context)->item(0)->nodeValue;
1496 $poco["xmpp"] = $value;
1499 /// @todo Add support for the following fields that we don't support by now in the contact table:
1500 /// - poco:utcOffset
1506 // If the "hide" element is present then the profile isn't searchable.
1507 $hide = intval($xpath->evaluate($element . "/dfrn:hide/text()", $context)->item(0)->nodeValue == "true");
1509 logger("Hidden status for contact " . $contact["url"] . ": " . $hide, LOGGER_DEBUG);
1511 // If the contact isn't searchable then set the contact to "hidden".
1512 // Problem: This can be manually overridden by the user.
1514 $contact["hidden"] = true;
1517 // Save the keywords into the contact table
1519 $tagelements = $xpath->evaluate($element . "/poco:tags/text()", $context);
1520 foreach ($tagelements AS $tag) {
1521 $tags[$tag->nodeValue] = $tag->nodeValue;
1525 $poco["keywords"] = implode(", ", $tags);
1528 // "dfrn:birthday" contains the birthday converted to UTC
1529 $old_bdyear = $contact["bdyear"];
1531 $birthday = $xpath->evaluate($element . "/dfrn:birthday/text()", $context)->item(0)->nodeValue;
1533 if (strtotime($birthday) > time()) {
1534 $bd_timestamp = strtotime($birthday);
1536 $poco["bdyear"] = date("Y", $bd_timestamp);
1539 // "poco:birthday" is the birthday in the format "yyyy-mm-dd"
1540 $value = $xpath->evaluate($element . "/poco:birthday/text()", $context)->item(0)->nodeValue;
1542 if (!in_array($value, array("", "0000-00-00", "0001-01-01"))) {
1543 $bdyear = date("Y");
1544 $value = str_replace("0000", $bdyear, $value);
1546 if (strtotime($value) < time()) {
1547 $value = str_replace($bdyear, $bdyear + 1, $value);
1548 $bdyear = $bdyear + 1;
1551 $poco["bd"] = $value;
1554 $contact = array_merge($contact, $poco);
1556 if ($old_bdyear != $contact["bdyear"]) {
1557 self::birthday_event($contact, $birthday);
1560 // Get all field names
1562 foreach ($r[0] AS $field => $data) {
1563 $fields[$field] = $data;
1566 unset($fields["id"]);
1567 unset($fields["uid"]);
1568 unset($fields["url"]);
1569 unset($fields["avatar-date"]);
1570 unset($fields["name-date"]);
1571 unset($fields["uri-date"]);
1573 // Update check for this field has to be done differently
1574 $datefields = array("name-date", "uri-date");
1575 foreach ($datefields AS $field) {
1576 if (strtotime($contact[$field]) > strtotime($r[0][$field])) {
1577 logger("Difference for contact " . $contact["id"] . " in field '" . $field . "'. New value: '" . $contact[$field] . "', old value '" . $r[0][$field] . "'", LOGGER_DEBUG);
1582 foreach ($fields AS $field => $data) {
1583 if ($contact[$field] != $r[0][$field]) {
1584 logger("Difference for contact " . $contact["id"] . " in field '" . $field . "'. New value: '" . $contact[$field] . "', old value '" . $r[0][$field] . "'", LOGGER_DEBUG);
1590 logger("Update contact data for contact " . $contact["id"] . " (" . $contact["nick"] . ")", LOGGER_DEBUG);
1592 q("UPDATE `contact` SET `name` = '%s', `nick` = '%s', `about` = '%s', `location` = '%s',
1593 `addr` = '%s', `keywords` = '%s', `bdyear` = '%s', `bd` = '%s', `hidden` = %d,
1594 `xmpp` = '%s', `name-date` = '%s', `uri-date` = '%s'
1595 WHERE `id` = %d AND `network` = '%s'",
1596 dbesc($contact["name"]), dbesc($contact["nick"]), dbesc($contact["about"]), dbesc($contact["location"]),
1597 dbesc($contact["addr"]), dbesc($contact["keywords"]), dbesc($contact["bdyear"]),
1598 dbesc($contact["bd"]), intval($contact["hidden"]), dbesc($contact["xmpp"]),
1599 dbesc(Dbm::date($contact["name-date"])), dbesc(Dbm::date($contact["uri-date"])),
1600 intval($contact["id"]), dbesc($contact["network"]));
1603 update_contact_avatar($author["avatar"], $importer["uid"], $contact["id"],
1604 (strtotime($contact["avatar-date"]) > strtotime($r[0]["avatar-date"])));
1607 * The generation is a sign for the reliability of the provided data.
1608 * It is used in the socgraph.php to prevent that old contact data
1609 * that was relayed over several servers can overwrite contact
1610 * data that we received directly.
1613 $poco["generation"] = 2;
1614 $poco["photo"] = $author["avatar"];
1615 $poco["hide"] = $hide;
1616 $poco["contact-type"] = $contact["contact-type"];
1617 $gcid = update_gcontact($poco);
1619 link_gcontact($gcid, $importer["uid"], $contact["id"]);
1626 * @brief Transforms activity objects into an XML string
1628 * @param object $xpath XPath object
1629 * @param object $activity Activity object
1630 * @param text $element element name
1632 * @return string XML string
1633 * @todo Find good type-hints for all parameter
1635 private static function transform_activity($xpath, $activity, $element) {
1636 if (!is_object($activity)) {
1640 $obj_doc = new DOMDocument("1.0", "utf-8");
1641 $obj_doc->formatOutput = true;
1643 $obj_element = $obj_doc->createElementNS(NAMESPACE_ATOM1, $element);
1645 $activity_type = $xpath->query("activity:object-type/text()", $activity)->item(0)->nodeValue;
1646 xml::add_element($obj_doc, $obj_element, "type", $activity_type);
1648 $id = $xpath->query("atom:id", $activity)->item(0);
1649 if (is_object($id)) {
1650 $obj_element->appendChild($obj_doc->importNode($id, true));
1653 $title = $xpath->query("atom:title", $activity)->item(0);
1654 if (is_object($title)) {
1655 $obj_element->appendChild($obj_doc->importNode($title, true));
1658 $links = $xpath->query("atom:link", $activity);
1659 if (is_object($links)) {
1660 foreach ($links AS $link) {
1661 $obj_element->appendChild($obj_doc->importNode($link, true));
1665 $content = $xpath->query("atom:content", $activity)->item(0);
1666 if (is_object($content)) {
1667 $obj_element->appendChild($obj_doc->importNode($content, true));
1670 $obj_doc->appendChild($obj_element);
1672 $objxml = $obj_doc->saveXML($obj_element);
1674 /// @todo This isn't totally clean. We should find a way to transform the namespaces
1675 $objxml = str_replace("<".$element.' xmlns="http://www.w3.org/2005/Atom">', "<".$element.">", $objxml);
1680 * @brief Processes the mail elements
1682 * @param object $xpath XPath object
1683 * @param object $mail mail elements
1684 * @param array $importer Record of the importer user mixed with contact of the content
1685 * @todo Find good type-hints for all parameter
1687 private static function process_mail($xpath, $mail, $importer) {
1689 logger("Processing mails");
1691 /// @TODO Rewrite this to one statement
1693 $msg["uid"] = $importer["importer_uid"];
1694 $msg["from-name"] = $xpath->query("dfrn:sender/dfrn:name/text()", $mail)->item(0)->nodeValue;
1695 $msg["from-url"] = $xpath->query("dfrn:sender/dfrn:uri/text()", $mail)->item(0)->nodeValue;
1696 $msg["from-photo"] = $xpath->query("dfrn:sender/dfrn:avatar/text()", $mail)->item(0)->nodeValue;
1697 $msg["contact-id"] = $importer["id"];
1698 $msg["uri"] = $xpath->query("dfrn:id/text()", $mail)->item(0)->nodeValue;
1699 $msg["parent-uri"] = $xpath->query("dfrn:in-reply-to/text()", $mail)->item(0)->nodeValue;
1700 $msg["created"] = $xpath->query("dfrn:sentdate/text()", $mail)->item(0)->nodeValue;
1701 $msg["title"] = $xpath->query("dfrn:subject/text()", $mail)->item(0)->nodeValue;
1702 $msg["body"] = $xpath->query("dfrn:content/text()", $mail)->item(0)->nodeValue;
1704 $msg["replied"] = 0;
1706 dba::insert('mail', $msg);
1708 // send notifications.
1709 /// @TODO Arange this mess
1710 $notif_params = array(
1711 "type" => NOTIFY_MAIL,
1712 "notify_flags" => $importer["notify-flags"],
1713 "language" => $importer["language"],
1714 "to_name" => $importer["username"],
1715 "to_email" => $importer["email"],
1716 "uid" => $importer["importer_uid"],
1718 "source_name" => $msg["from-name"],
1719 "source_link" => $importer["url"],
1720 "source_photo" => $importer["thumb"],
1721 "verb" => ACTIVITY_POST,
1725 notification($notif_params);
1727 logger("Mail is processed, notification was sent.");
1731 * @brief Processes the suggestion elements
1733 * @param object $xpath XPath object
1734 * @param object $suggestion suggestion elements
1735 * @param array $importer Record of the importer user mixed with contact of the content
1736 * @todo Find good type-hints for all parameter
1738 private static function process_suggestion($xpath, $suggestion, $importer) {
1741 logger("Processing suggestions");
1743 /// @TODO Rewrite this to one statement
1745 $suggest["uid"] = $importer["importer_uid"];
1746 $suggest["cid"] = $importer["id"];
1747 $suggest["url"] = $xpath->query("dfrn:url/text()", $suggestion)->item(0)->nodeValue;
1748 $suggest["name"] = $xpath->query("dfrn:name/text()", $suggestion)->item(0)->nodeValue;
1749 $suggest["photo"] = $xpath->query("dfrn:photo/text()", $suggestion)->item(0)->nodeValue;
1750 $suggest["request"] = $xpath->query("dfrn:request/text()", $suggestion)->item(0)->nodeValue;
1751 $suggest["body"] = $xpath->query("dfrn:note/text()", $suggestion)->item(0)->nodeValue;
1753 // Does our member already have a friend matching this description?
1755 $r = q("SELECT `id` FROM `contact` WHERE `name` = '%s' AND `nurl` = '%s' AND `uid` = %d LIMIT 1",
1756 dbesc($suggest["name"]),
1757 dbesc(normalise_link($suggest["url"])),
1758 intval($suggest["uid"])
1762 * The valid result means the friend we're about to send a friend
1763 * suggestion already has them in their contact, which means no further
1764 * action is required.
1766 * @see https://github.com/friendica/friendica/pull/3254#discussion_r107315246
1768 if (Dbm::is_result($r)) {
1772 // Do we already have an fcontact record for this person?
1775 $r = q("SELECT `id` FROM `fcontact` WHERE `url` = '%s' AND `name` = '%s' AND `request` = '%s' LIMIT 1",
1776 dbesc($suggest["url"]),
1777 dbesc($suggest["name"]),
1778 dbesc($suggest["request"])
1780 if (Dbm::is_result($r)) {
1783 // OK, we do. Do we already have an introduction for this person ?
1784 $r = q("SELECT `id` FROM `intro` WHERE `uid` = %d AND `fid` = %d LIMIT 1",
1785 intval($suggest["uid"]),
1790 * The valid result means the friend we're about to send a friend
1791 * suggestion already has them in their contact, which means no further
1792 * action is required.
1794 * @see https://github.com/friendica/friendica/pull/3254#discussion_r107315246
1796 if (Dbm::is_result($r)) {
1801 $r = q("INSERT INTO `fcontact` (`name`,`url`,`photo`,`request`) VALUES ('%s', '%s', '%s', '%s')",
1802 dbesc($suggest["name"]),
1803 dbesc($suggest["url"]),
1804 dbesc($suggest["photo"]),
1805 dbesc($suggest["request"])
1808 $r = q("SELECT `id` FROM `fcontact` WHERE `url` = '%s' AND `name` = '%s' AND `request` = '%s' LIMIT 1",
1809 dbesc($suggest["url"]),
1810 dbesc($suggest["name"]),
1811 dbesc($suggest["request"])
1815 * If no record in fcontact is found, below INSERT statement will not
1816 * link an introduction to it.
1818 if (!Dbm::is_result($r)) {
1819 // database record did not get created. Quietly give up.
1825 $hash = random_string();
1827 $r = q("INSERT INTO `intro` (`uid`, `fid`, `contact-id`, `note`, `hash`, `datetime`, `blocked`)
1828 VALUES(%d, %d, %d, '%s', '%s', '%s', %d)",
1829 intval($suggest["uid"]),
1831 intval($suggest["cid"]),
1832 dbesc($suggest["body"]),
1834 dbesc(datetime_convert()),
1839 "type" => NOTIFY_SUGGEST,
1840 "notify_flags" => $importer["notify-flags"],
1841 "language" => $importer["language"],
1842 "to_name" => $importer["username"],
1843 "to_email" => $importer["email"],
1844 "uid" => $importer["importer_uid"],
1846 "link" => System::baseUrl()."/notifications/intros",
1847 "source_name" => $importer["name"],
1848 "source_link" => $importer["url"],
1849 "source_photo" => $importer["photo"],
1850 "verb" => ACTIVITY_REQ_FRIEND,
1859 * @brief Processes the relocation elements
1861 * @param object $xpath XPath object
1862 * @param object $relocation relocation elements
1863 * @param array $importer Record of the importer user mixed with contact of the content
1864 * @todo Find good type-hints for all parameter
1866 private static function process_relocation($xpath, $relocation, $importer) {
1868 logger("Processing relocations");
1870 /// @TODO Rewrite this to one statement
1871 $relocate = array();
1872 $relocate["uid"] = $importer["importer_uid"];
1873 $relocate["cid"] = $importer["id"];
1874 $relocate["url"] = $xpath->query("dfrn:url/text()", $relocation)->item(0)->nodeValue;
1875 $relocate["addr"] = $xpath->query("dfrn:addr/text()", $relocation)->item(0)->nodeValue;
1876 $relocate["name"] = $xpath->query("dfrn:name/text()", $relocation)->item(0)->nodeValue;
1877 $relocate["avatar"] = $xpath->query("dfrn:avatar/text()", $relocation)->item(0)->nodeValue;
1878 $relocate["photo"] = $xpath->query("dfrn:photo/text()", $relocation)->item(0)->nodeValue;
1879 $relocate["thumb"] = $xpath->query("dfrn:thumb/text()", $relocation)->item(0)->nodeValue;
1880 $relocate["micro"] = $xpath->query("dfrn:micro/text()", $relocation)->item(0)->nodeValue;
1881 $relocate["request"] = $xpath->query("dfrn:request/text()", $relocation)->item(0)->nodeValue;
1882 $relocate["confirm"] = $xpath->query("dfrn:confirm/text()", $relocation)->item(0)->nodeValue;
1883 $relocate["notify"] = $xpath->query("dfrn:notify/text()", $relocation)->item(0)->nodeValue;
1884 $relocate["poll"] = $xpath->query("dfrn:poll/text()", $relocation)->item(0)->nodeValue;
1885 $relocate["sitepubkey"] = $xpath->query("dfrn:sitepubkey/text()", $relocation)->item(0)->nodeValue;
1887 if (($relocate["avatar"] == "") && ($relocate["photo"] != "")) {
1888 $relocate["avatar"] = $relocate["photo"];
1891 if ($relocate["addr"] == "") {
1892 $relocate["addr"] = preg_replace("=(https?://)(.*)/profile/(.*)=ism", "$3@$2", $relocate["url"]);
1896 $r = q("SELECT `photo`, `url` FROM `contact` WHERE `id` = %d AND `uid` = %d;",
1897 intval($importer["id"]),
1898 intval($importer["importer_uid"]));
1900 if (!Dbm::is_result($r)) {
1901 logger("Query failed to execute, no result returned in " . __FUNCTION__);
1907 // Update the gcontact entry
1908 $relocate["server_url"] = preg_replace("=(https?://)(.*)/profile/(.*)=ism", "$1$2", $relocate["url"]);
1910 $x = q("UPDATE `gcontact` SET
1919 WHERE `nurl` = '%s';",
1920 dbesc($relocate["name"]),
1921 dbesc($relocate["avatar"]),
1922 dbesc($relocate["url"]),
1923 dbesc(normalise_link($relocate["url"])),
1924 dbesc($relocate["addr"]),
1925 dbesc($relocate["addr"]),
1926 dbesc($relocate["notify"]),
1927 dbesc($relocate["server_url"]),
1928 dbesc(normalise_link($old["url"])));
1930 // Update the contact table. We try to find every entry.
1931 $x = q("UPDATE `contact` SET
1941 `site-pubkey` = '%s'
1942 WHERE (`id` = %d AND `uid` = %d) OR (`nurl` = '%s');",
1943 dbesc($relocate["name"]),
1944 dbesc($relocate["avatar"]),
1945 dbesc($relocate["url"]),
1946 dbesc(normalise_link($relocate["url"])),
1947 dbesc($relocate["addr"]),
1948 dbesc($relocate["request"]),
1949 dbesc($relocate["confirm"]),
1950 dbesc($relocate["notify"]),
1951 dbesc($relocate["poll"]),
1952 dbesc($relocate["sitepubkey"]),
1953 intval($importer["id"]),
1954 intval($importer["importer_uid"]),
1955 dbesc(normalise_link($old["url"])));
1957 update_contact_avatar($relocate["avatar"], $importer["importer_uid"], $importer["id"], true);
1964 /// @todo This is an extreme performance killer
1966 'owner-link' => array($old["url"], $relocate["url"]),
1967 'author-link' => array($old["url"], $relocate["url"]),
1968 //'owner-avatar' => array($old["photo"], $relocate["photo"]),
1969 //'author-avatar' => array($old["photo"], $relocate["photo"]),
1971 foreach ($fields as $n=>$f) {
1972 $r = q("SELECT `id` FROM `item` WHERE `%s` = '%s' AND `uid` = %d LIMIT 1",
1974 intval($importer["importer_uid"]));
1976 if (Dbm::is_result($r)) {
1977 $x = q("UPDATE `item` SET `%s` = '%s' WHERE `%s` = '%s' AND `uid` = %d",
1980 intval($importer["importer_uid"]));
1989 /// merge with current record, current contents have priority
1990 /// update record, set url-updated
1991 /// update profile photos
1992 /// schedule a scan?
1997 * @brief Updates an item
1999 * @param array $current the current item record
2000 * @param array $item the new item record
2001 * @param array $importer Record of the importer user mixed with contact of the content
2002 * @param int $entrytype Is it a toplevel entry, a comment or a relayed comment?
2003 * @todo set proper type-hints (array?)
2005 private static function update_content($current, $item, $importer, $entrytype) {
2008 if (edited_timestamp_is_newer($current, $item)) {
2010 // do not accept (ignore) an earlier edit than one we currently have.
2011 if (datetime_convert("UTC","UTC",$item["edited"]) < $current["edited"]) {
2015 $fields = array('title' => $item["title"], 'body' => $item["body"],
2016 'tag' => $item["tag"], 'changed' => datetime_convert(),
2017 'edited' => datetime_convert("UTC", "UTC", $item["edited"]));
2019 $condition = array("`uri` = ? AND `uid` IN (0, ?)", $item["uri"], $importer["importer_uid"]);
2020 dba::update('item', $fields, $condition);
2022 create_tags_from_itemuri($item["uri"], $importer["importer_uid"]);
2023 update_thread_uri($item["uri"], $importer["importer_uid"]);
2027 if ($entrytype == DFRN_REPLY_RC) {
2028 Worker::add(PRIORITY_HIGH, "notifier","comment-import", $current["id"]);
2032 // update last-child if it changes
2033 if ($item["last-child"] && ($item["last-child"] != $current["last-child"])) {
2034 $r = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` IN (0, %d)",
2035 dbesc(datetime_convert()),
2036 dbesc($item["parent-uri"]),
2037 intval($importer["importer_uid"])
2039 $r = q("UPDATE `item` SET `last-child` = %d , `changed` = '%s' WHERE `uri` = '%s' AND `uid` IN (0, %d)",
2040 intval($item["last-child"]),
2041 dbesc(datetime_convert()),
2042 dbesc($item["uri"]),
2043 intval($importer["importer_uid"])
2050 * @brief Detects the entry type of the item
2052 * @param array $importer Record of the importer user mixed with contact of the content
2053 * @param array $item the new item record
2055 * @return int Is it a toplevel entry, a comment or a relayed comment?
2056 * @todo set proper type-hints (array?)
2058 private static function get_entry_type($importer, $item) {
2059 if ($item["parent-uri"] != $item["uri"]) {
2062 if ($importer["page-flags"] == PAGE_COMMUNITY || $importer["page-flags"] == PAGE_PRVGROUP) {
2065 logger("possible community action");
2067 $sql_extra = " AND `contact`.`self` AND `item`.`wall` ";
2070 // was the top-level post for this action written by somebody on this site?
2071 // Specifically, the recipient?
2073 $is_a_remote_action = false;
2075 $r = q("SELECT `item`.`parent-uri` FROM `item`
2076 WHERE `item`.`uri` = '%s'
2078 dbesc($item["parent-uri"])
2080 if (Dbm::is_result($r)) {
2081 $r = q("SELECT `item`.`forum_mode`, `item`.`wall` FROM `item`
2082 INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
2083 WHERE `item`.`uri` = '%s' AND (`item`.`parent-uri` = '%s' OR `item`.`thr-parent` = '%s')
2084 AND `item`.`uid` = %d
2087 dbesc($r[0]["parent-uri"]),
2088 dbesc($r[0]["parent-uri"]),
2089 dbesc($r[0]["parent-uri"]),
2090 intval($importer["importer_uid"])
2092 if (Dbm::is_result($r)) {
2093 $is_a_remote_action = true;
2098 * Does this have the characteristics of a community or private group action?
2099 * If it's an action to a wall post on a community/prvgroup page it's a
2100 * valid community action. Also forum_mode makes it valid for sure.
2101 * If neither, it's not.
2104 /// @TODO Maybe merge these if() blocks into one?
2105 if ($is_a_remote_action && $community && (!$r[0]["forum_mode"]) && (!$r[0]["wall"])) {
2106 $is_a_remote_action = false;
2107 logger("not a community action");
2110 if ($is_a_remote_action) {
2111 return DFRN_REPLY_RC;
2116 return DFRN_TOP_LEVEL;
2122 * @brief Send a "poke"
2124 * @param array $item the new item record
2125 * @param array $importer Record of the importer user mixed with contact of the content
2126 * @param int $posted_id The record number of item record that was just posted
2127 * @todo set proper type-hints (array?)
2129 private static function do_poke($item, $importer, $posted_id) {
2130 $verb = urldecode(substr($item["verb"],strpos($item["verb"], "#")+1));
2134 $xo = parse_xml_string($item["object"],false);
2136 if (($xo->type == ACTIVITY_OBJ_PERSON) && ($xo->id)) {
2138 // somebody was poked/prodded. Was it me?
2139 foreach ($xo->link as $l) {
2140 $atts = $l->attributes();
2141 switch ($atts["rel"]) {
2143 $Blink = $atts["href"];
2150 if ($Blink && link_compare($Blink, System::baseUrl() . "/profile/" . $importer["nickname"])) {
2152 // send a notification
2154 "type" => NOTIFY_POKE,
2155 "notify_flags" => $importer["notify-flags"],
2156 "language" => $importer["language"],
2157 "to_name" => $importer["username"],
2158 "to_email" => $importer["email"],
2159 "uid" => $importer["importer_uid"],
2161 "link" => System::baseUrl()."/display/".urlencode(get_item_guid($posted_id)),
2162 "source_name" => stripslashes($item["author-name"]),
2163 "source_link" => $item["author-link"],
2164 "source_photo" => ((link_compare($item["author-link"],$importer["url"]))
2165 ? $importer["thumb"] : $item["author-avatar"]),
2166 "verb" => $item["verb"],
2167 "otype" => "person",
2168 "activity" => $verb,
2169 "parent" => $item["parent"]
2176 * @brief Processes several actions, depending on the verb
2178 * @param int $entrytype Is it a toplevel entry, a comment or a relayed comment?
2179 * @param array $importer Record of the importer user mixed with contact of the content
2180 * @param array $item the new item record
2181 * @param bool $is_like Is the verb a "like"?
2183 * @return bool Should the processing of the entries be continued?
2184 * @todo set proper type-hints (array?)
2186 private static function process_verbs($entrytype, $importer, &$item, &$is_like) {
2188 logger("Process verb ".$item["verb"]." and object-type ".$item["object-type"]." for entrytype ".$entrytype, LOGGER_DEBUG);
2190 if (($entrytype == DFRN_TOP_LEVEL)) {
2191 // The filling of the the "contact" variable is done for legcy reasons
2192 // The functions below are partly used by ostatus.php as well - where we have this variable
2193 $r = q("SELECT * FROM `contact` WHERE `id` = %d", intval($importer["id"]));
2195 $nickname = $contact["nick"];
2197 // Big question: Do we need these functions? They were part of the "consume_feed" function.
2198 // This function once was responsible for DFRN and OStatus.
2199 if (activity_match($item["verb"], ACTIVITY_FOLLOW)) {
2200 logger("New follower");
2201 new_follower($importer, $contact, $item, $nickname);
2204 if (activity_match($item["verb"], ACTIVITY_UNFOLLOW)) {
2205 logger("Lost follower");
2206 lose_follower($importer, $contact, $item);
2209 if (activity_match($item["verb"], ACTIVITY_REQ_FRIEND)) {
2210 logger("New friend request");
2211 new_follower($importer, $contact, $item, $nickname, true);
2214 if (activity_match($item["verb"], ACTIVITY_UNFRIEND)) {
2215 logger("Lost sharer");
2216 lose_sharer($importer, $contact, $item);
2220 if (($item["verb"] == ACTIVITY_LIKE)
2221 || ($item["verb"] == ACTIVITY_DISLIKE)
2222 || ($item["verb"] == ACTIVITY_ATTEND)
2223 || ($item["verb"] == ACTIVITY_ATTENDNO)
2224 || ($item["verb"] == ACTIVITY_ATTENDMAYBE)) {
2226 $item["type"] = "activity";
2227 $item["gravity"] = GRAVITY_LIKE;
2228 // only one like or dislike per person
2229 // splitted into two queries for performance issues
2230 $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",
2231 intval($item["uid"]),
2232 dbesc($item["author-link"]),
2233 dbesc($item["verb"]),
2234 dbesc($item["parent-uri"])
2236 if (Dbm::is_result($r)) {
2240 $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",
2241 intval($item["uid"]),
2242 dbesc($item["author-link"]),
2243 dbesc($item["verb"]),
2244 dbesc($item["parent-uri"])
2246 if (Dbm::is_result($r)) {
2253 if (($item["verb"] == ACTIVITY_TAG) && ($item["object-type"] == ACTIVITY_OBJ_TAGTERM)) {
2255 $xo = parse_xml_string($item["object"],false);
2256 $xt = parse_xml_string($item["target"],false);
2258 if ($xt->type == ACTIVITY_OBJ_NOTE) {
2259 $r = q("SELECT `id`, `tag` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2261 intval($importer["importer_uid"])
2264 if (!Dbm::is_result($r)) {
2265 logger("Query failed to execute, no result returned in " . __FUNCTION__);
2269 // extract tag, if not duplicate, add to parent item
2271 if (!(stristr($r[0]["tag"],trim($xo->content)))) {
2272 q("UPDATE `item` SET `tag` = '%s' WHERE `id` = %d",
2273 dbesc($r[0]["tag"] . (strlen($r[0]["tag"]) ? ',' : '') . '#[url=' . $xo->id . ']'. $xo->content . '[/url]'),
2276 create_tags_from_item($r[0]["id"]);
2286 * @brief Processes the link elements
2288 * @param object $links link elements
2289 * @param array $item the item record
2290 * @todo set proper type-hints
2292 private static function parse_links($links, &$item) {
2298 foreach ($links AS $link) {
2299 foreach ($link->attributes AS $attributes) {
2300 /// @TODO Rewrite these repeated (same) if () statements to a switch()
2301 if ($attributes->name == "href") {
2302 $href = $attributes->textContent;
2304 if ($attributes->name == "rel") {
2305 $rel = $attributes->textContent;
2307 if ($attributes->name == "type") {
2308 $type = $attributes->textContent;
2310 if ($attributes->name == "length") {
2311 $length = $attributes->textContent;
2313 if ($attributes->name == "title") {
2314 $title = $attributes->textContent;
2317 if (($rel != "") && ($href != "")) {
2320 $item["plink"] = $href;
2324 if (strlen($item["attach"])) {
2325 $item["attach"] .= ",";
2328 $item["attach"] .= '[attach]href="' . $href . '" length="' . $length . '" type="' . $type . '" title="' . $title . '"[/attach]';
2336 * @brief Processes the entry elements which contain the items and comments
2338 * @param array $header Array of the header elements that always stay the same
2339 * @param object $xpath XPath object
2340 * @param object $entry entry elements
2341 * @param array $importer Record of the importer user mixed with contact of the content
2342 * @todo Add type-hints
2344 private static function process_entry($header, $xpath, $entry, $importer, $xml) {
2346 logger("Processing entries");
2350 $item["protocol"] = PROTOCOL_DFRN;
2352 $item["source"] = $xml;
2355 $item["uri"] = $xpath->query("atom:id/text()", $entry)->item(0)->nodeValue;
2357 $item["edited"] = $xpath->query("atom:updated/text()", $entry)->item(0)->nodeValue;
2359 $current = q("SELECT `id`, `uid`, `last-child`, `edited`, `body` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2360 dbesc($item["uri"]),
2361 intval($importer["importer_uid"])
2364 // Is there an existing item?
2365 if (Dbm::is_result($current) && edited_timestamp_is_newer($current[0], $item) &&
2366 (datetime_convert("UTC","UTC",$item["edited"]) < $current[0]["edited"])) {
2367 logger("Item ".$item["uri"]." already existed.", LOGGER_DEBUG);
2372 $owner = self::fetchauthor($xpath, $entry, $importer, "dfrn:owner", true);
2374 $item["owner-name"] = $owner["name"];
2375 $item["owner-link"] = $owner["link"];
2376 $item["owner-avatar"] = $owner["avatar"];
2379 $author = self::fetchauthor($xpath, $entry, $importer, "atom:author", true);
2381 $item["author-name"] = $author["name"];
2382 $item["author-link"] = $author["link"];
2383 $item["author-avatar"] = $author["avatar"];
2385 $item["title"] = $xpath->query("atom:title/text()", $entry)->item(0)->nodeValue;
2387 $item["created"] = $xpath->query("atom:published/text()", $entry)->item(0)->nodeValue;
2389 $item["body"] = $xpath->query("dfrn:env/text()", $entry)->item(0)->nodeValue;
2390 $item["body"] = str_replace(array(' ',"\t","\r","\n"), array('','','',''),$item["body"]);
2391 // make sure nobody is trying to sneak some html tags by us
2392 $item["body"] = notags(base64url_decode($item["body"]));
2394 $item["body"] = limit_body_size($item["body"]);
2396 /// @todo Do we really need this check for HTML elements? (It was copied from the old function)
2397 if ((strpos($item['body'],'<') !== false) && (strpos($item['body'],'>') !== false)) {
2399 $item['body'] = reltoabs($item['body'],$base_url);
2401 $item['body'] = html2bb_video($item['body']);
2403 $item['body'] = oembed_html2bbcode($item['body']);
2405 $config = HTMLPurifier_Config::createDefault();
2406 $config->set('Cache.DefinitionImpl', null);
2408 // we shouldn't need a whitelist, because the bbcode converter
2409 // will strip out any unsupported tags.
2411 $purifier = new HTMLPurifier($config);
2412 $item['body'] = $purifier->purify($item['body']);
2414 $item['body'] = @html2bbcode($item['body']);
2417 /// @todo We should check for a repeated post and if we know the repeated author.
2419 // We don't need the content element since "dfrn:env" is always present
2420 //$item["body"] = $xpath->query("atom:content/text()", $entry)->item(0)->nodeValue;
2422 $item["last-child"] = $xpath->query("dfrn:comment-allow/text()", $entry)->item(0)->nodeValue;
2423 $item["location"] = $xpath->query("dfrn:location/text()", $entry)->item(0)->nodeValue;
2425 $georsspoint = $xpath->query("georss:point", $entry);
2427 $item["coord"] = $georsspoint->item(0)->nodeValue;
2430 $item["private"] = $xpath->query("dfrn:private/text()", $entry)->item(0)->nodeValue;
2432 $item["extid"] = $xpath->query("dfrn:extid/text()", $entry)->item(0)->nodeValue;
2434 if ($xpath->query("dfrn:bookmark/text()", $entry)->item(0)->nodeValue == "true") {
2435 $item["bookmark"] = true;
2438 $notice_info = $xpath->query("statusnet:notice_info", $entry);
2439 if ($notice_info && ($notice_info->length > 0)) {
2440 foreach ($notice_info->item(0)->attributes AS $attributes) {
2441 if ($attributes->name == "source") {
2442 $item["app"] = strip_tags($attributes->textContent);
2447 $item["guid"] = $xpath->query("dfrn:diaspora_guid/text()", $entry)->item(0)->nodeValue;
2449 // We store the data from "dfrn:diaspora_signature" in a different table, this is done in "item_store"
2450 $dsprsig = unxmlify($xpath->query("dfrn:diaspora_signature/text()", $entry)->item(0)->nodeValue);
2451 if ($dsprsig != "") {
2452 $item["dsprsig"] = $dsprsig;
2455 $item["verb"] = $xpath->query("activity:verb/text()", $entry)->item(0)->nodeValue;
2457 if ($xpath->query("activity:object-type/text()", $entry)->item(0)->nodeValue != "") {
2458 $item["object-type"] = $xpath->query("activity:object-type/text()", $entry)->item(0)->nodeValue;
2461 $object = $xpath->query("activity:object", $entry)->item(0);
2462 $item["object"] = self::transform_activity($xpath, $object, "object");
2464 if (trim($item["object"]) != "") {
2465 $r = parse_xml_string($item["object"], false);
2466 if (isset($r->type)) {
2467 $item["object-type"] = $r->type;
2471 $target = $xpath->query("activity:target", $entry)->item(0);
2472 $item["target"] = self::transform_activity($xpath, $target, "target");
2474 $categories = $xpath->query("atom:category", $entry);
2476 foreach ($categories AS $category) {
2479 foreach ($category->attributes AS $attributes) {
2480 if ($attributes->name == "term") {
2481 $term = $attributes->textContent;
2484 if ($attributes->name == "scheme") {
2485 $scheme = $attributes->textContent;
2489 if (($term != "") && ($scheme != "")) {
2490 $parts = explode(":", $scheme);
2491 if ((count($parts) >= 4) && (array_shift($parts) == "X-DFRN")) {
2492 $termhash = array_shift($parts);
2493 $termurl = implode(":", $parts);
2495 if (strlen($item["tag"])) {
2496 $item["tag"] .= ",";
2499 $item["tag"] .= $termhash . "[url=" . $termurl . "]" . $term . "[/url]";
2507 $links = $xpath->query("atom:link", $entry);
2509 self::parse_links($links, $item);
2512 $item['conversation-uri'] = $xpath->query('ostatus:conversation/text()', $entry)->item(0)->nodeValue;
2514 $conv = $xpath->query('ostatus:conversation', $entry);
2515 if (is_object($conv->item(0))) {
2516 foreach ($conv->item(0)->attributes AS $attributes) {
2517 if ($attributes->name == "ref") {
2518 $item['conversation-uri'] = $attributes->textContent;
2520 if ($attributes->name == "href") {
2521 $item['conversation-href'] = $attributes->textContent;
2526 // Is it a reply or a top level posting?
2527 $item["parent-uri"] = $item["uri"];
2529 $inreplyto = $xpath->query("thr:in-reply-to", $entry);
2530 if (is_object($inreplyto->item(0))) {
2531 foreach ($inreplyto->item(0)->attributes AS $attributes) {
2532 if ($attributes->name == "ref") {
2533 $item["parent-uri"] = $attributes->textContent;
2538 // Get the type of the item (Top level post, reply or remote reply)
2539 $entrytype = self::get_entry_type($importer, $item);
2541 // Now assign the rest of the values that depend on the type of the message
2542 if (in_array($entrytype, array(DFRN_REPLY, DFRN_REPLY_RC))) {
2543 if (!isset($item["object-type"])) {
2544 $item["object-type"] = ACTIVITY_OBJ_COMMENT;
2547 if ($item["contact-id"] != $owner["contact-id"]) {
2548 $item["contact-id"] = $owner["contact-id"];
2551 if (($item["network"] != $owner["network"]) && ($owner["network"] != "")) {
2552 $item["network"] = $owner["network"];
2555 if ($item["contact-id"] != $author["contact-id"]) {
2556 $item["contact-id"] = $author["contact-id"];
2559 if (($item["network"] != $author["network"]) && ($author["network"] != "")) {
2560 $item["network"] = $author["network"];
2563 /// @TODO maybe remove this old-lost code then?
2564 // This code was taken from the old DFRN code
2565 // When activated, forums don't work.
2566 // And: Why should we disallow commenting by followers?
2567 // the behaviour is now similar to the Diaspora part.
2568 //if ($importer["rel"] == CONTACT_IS_FOLLOWER) {
2569 // logger("Contact ".$importer["id"]." is only follower. Quitting", LOGGER_DEBUG);
2574 if ($entrytype == DFRN_REPLY_RC) {
2575 $item["type"] = "remote-comment";
2577 } elseif ($entrytype == DFRN_TOP_LEVEL) {
2578 if (!isset($item["object-type"])) {
2579 $item["object-type"] = ACTIVITY_OBJ_NOTE;
2583 if ($item["object-type"] == ACTIVITY_OBJ_EVENT) {
2584 logger("Item ".$item["uri"]." seems to contain an event.", LOGGER_DEBUG);
2585 $ev = bbtoevent($item["body"]);
2586 if ((x($ev, "desc") || x($ev, "summary")) && x($ev, "start")) {
2587 logger("Event in item ".$item["uri"]." was found.", LOGGER_DEBUG);
2588 /// @TODO Mixure of "/' ahead ...
2589 $ev["cid"] = $importer["id"];
2590 $ev["uid"] = $importer["uid"];
2591 $ev["uri"] = $item["uri"];
2592 $ev["edited"] = $item["edited"];
2593 $ev['private'] = $item['private'];
2594 $ev["guid"] = $item["guid"];
2596 $r = q("SELECT `id` FROM `event` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2597 dbesc($item["uri"]),
2598 intval($importer["uid"])
2600 if (Dbm::is_result($r)) {
2601 $ev["id"] = $r[0]["id"];
2604 $event_id = event_store($ev);
2605 logger("Event ".$event_id." was stored", LOGGER_DEBUG);
2611 if (!self::process_verbs($entrytype, $importer, $item, $is_like)) {
2612 logger("Exiting because 'process_verbs' told us so", LOGGER_DEBUG);
2616 // Update content if 'updated' changes
2617 if (Dbm::is_result($current)) {
2618 if (self::update_content($r[0], $item, $importer, $entrytype)) {
2619 logger("Item ".$item["uri"]." was updated.", LOGGER_DEBUG);
2621 logger("Item ".$item["uri"]." already existed.", LOGGER_DEBUG);
2626 if (in_array($entrytype, array(DFRN_REPLY, DFRN_REPLY_RC))) {
2627 $posted_id = item_store($item);
2632 logger("Reply from contact ".$item["contact-id"]." was stored with id ".$posted_id, LOGGER_DEBUG);
2634 $item["id"] = $posted_id;
2636 $r = q("SELECT `parent`, `parent-uri` FROM `item` WHERE `id` = %d AND `uid` = %d LIMIT 1",
2638 intval($importer["importer_uid"])
2640 if (Dbm::is_result($r)) {
2641 $parent = $r[0]["parent"];
2642 $parent_uri = $r[0]["parent-uri"];
2646 $r1 = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `uid` = %d AND `parent` = %d",
2647 dbesc(datetime_convert()),
2648 intval($importer["importer_uid"]),
2649 intval($r[0]["parent"])
2652 $r2 = q("UPDATE `item` SET `last-child` = 1, `changed` = '%s' WHERE `uid` = %d AND `id` = %d",
2653 dbesc(datetime_convert()),
2654 intval($importer["importer_uid"]),
2659 if ($posted_id && $parent && ($entrytype == DFRN_REPLY_RC)) {
2660 logger("Notifying followers about comment ".$posted_id, LOGGER_DEBUG);
2661 Worker::add(PRIORITY_HIGH, "notifier", "comment-import", $posted_id);
2666 } else { // $entrytype == DFRN_TOP_LEVEL
2667 if (!link_compare($item["owner-link"],$importer["url"])) {
2669 * The item owner info is not our contact. It's OK and is to be expected if this is a tgroup delivery,
2670 * but otherwise there's a possible data mixup on the sender's system.
2671 * the tgroup delivery code called from item_store will correct it if it's a forum,
2672 * but we're going to unconditionally correct it here so that the post will always be owned by our contact.
2674 logger('Correcting item owner.', LOGGER_DEBUG);
2675 $item["owner-name"] = $importer["senderName"];
2676 $item["owner-link"] = $importer["url"];
2677 $item["owner-avatar"] = $importer["thumb"];
2680 if (($importer["rel"] == CONTACT_IS_FOLLOWER) && (!tgroup_check($importer["importer_uid"], $item))) {
2681 logger("Contact ".$importer["id"]." is only follower and tgroup check was negative.", LOGGER_DEBUG);
2685 // This is my contact on another system, but it's really me.
2686 // Turn this into a wall post.
2687 $notify = item_is_remote_self($importer, $item);
2689 $posted_id = item_store($item, false, $notify);
2691 logger("Item was stored with id ".$posted_id, LOGGER_DEBUG);
2693 if (stristr($item["verb"],ACTIVITY_POKE))
2694 self::do_poke($item, $importer, $posted_id);
2699 * @brief Deletes items
2701 * @param object $xpath XPath object
2702 * @param object $deletion deletion elements
2703 * @param array $importer Record of the importer user mixed with contact of the content
2704 * @todo set proper type-hints
2706 private static function process_deletion($xpath, $deletion, $importer) {
2708 logger("Processing deletions");
2710 foreach ($deletion->attributes AS $attributes) {
2711 if ($attributes->name == "ref") {
2712 $uri = $attributes->textContent;
2714 if ($attributes->name == "when") {
2715 $when = $attributes->textContent;
2719 $when = datetime_convert("UTC", "UTC", $when, "Y-m-d H:i:s");
2721 $when = datetime_convert("UTC", "UTC", "now", "Y-m-d H:i:s");
2724 if (!$uri || !$importer["id"]) {
2728 /// @todo Only select the used fields
2729 $r = q("SELECT `item`.*, `contact`.`self` FROM `item` INNER JOIN `contact` on `item`.`contact-id` = `contact`.`id`
2730 WHERE `uri` = '%s' AND `item`.`uid` = %d AND `contact-id` = %d AND NOT `item`.`file` LIKE '%%[%%' LIMIT 1",
2732 intval($importer["uid"]),
2733 intval($importer["id"])
2735 if (!Dbm::is_result($r)) {
2736 logger("Item with uri " . $uri . " from contact " . $importer["id"] . " for user " . $importer["uid"] . " wasn't found.", LOGGER_DEBUG);
2742 $entrytype = self::get_entry_type($importer, $item);
2744 if (!$item["deleted"]) {
2745 logger('deleting item '.$item["id"].' uri='.$uri, LOGGER_DEBUG);
2750 if ($item["object-type"] == ACTIVITY_OBJ_EVENT) {
2751 logger("Deleting event ".$item["event-id"], LOGGER_DEBUG);
2752 event_delete($item["event-id"]);
2755 if (($item["verb"] == ACTIVITY_TAG) && ($item["object-type"] == ACTIVITY_OBJ_TAGTERM)) {
2757 $xo = parse_xml_string($item["object"],false);
2758 $xt = parse_xml_string($item["target"],false);
2760 if ($xt->type == ACTIVITY_OBJ_NOTE) {
2761 $i = q("SELECT `id`, `contact-id`, `tag` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2763 intval($importer["importer_uid"])
2765 if (Dbm::is_result($i)) {
2767 // For tags, the owner cannot remove the tag on the author's copy of the post.
2769 $owner_remove = (($item["contact-id"] == $i[0]["contact-id"]) ? true: false);
2770 $author_remove = (($item["origin"] && $item["self"]) ? true : false);
2771 $author_copy = (($item["origin"]) ? true : false);
2773 if ($owner_remove && $author_copy) {
2776 if ($author_remove || $owner_remove) {
2777 $tags = explode(',',$i[0]["tag"]);
2780 foreach ($tags as $tag) {
2781 if (trim($tag) !== trim($xo->body)) {
2782 $newtags[] = trim($tag);
2786 q("UPDATE `item` SET `tag` = '%s' WHERE `id` = %d",
2787 dbesc(implode(',', $newtags)),
2790 create_tags_from_item($i[0]["id"]);
2796 if ($entrytype == DFRN_TOP_LEVEL) {
2797 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s',
2798 `body` = '', `title` = ''
2799 WHERE `parent-uri` = '%s' AND `uid` IN (0, %d)",
2801 dbesc(datetime_convert()),
2803 intval($importer["uid"])
2805 create_tags_from_itemuri($uri, $importer["uid"]);
2806 create_files_from_itemuri($uri, $importer["uid"]);
2807 update_thread_uri($uri, $importer["uid"]);
2809 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s',
2810 `body` = '', `title` = ''
2811 WHERE `uri` = '%s' AND `uid` IN (0, %d)",
2813 dbesc(datetime_convert()),
2815 intval($importer["uid"])
2817 create_tags_from_itemuri($uri, $importer["uid"]);
2818 create_files_from_itemuri($uri, $importer["uid"]);
2819 update_thread_uri($uri, $importer["importer_uid"]);
2820 if ($item["last-child"]) {
2821 // ensure that last-child is set in case the comment that had it just got wiped.
2822 q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` IN (0, %d)",
2823 dbesc(datetime_convert()),
2824 dbesc($item["parent-uri"]),
2825 intval($item["uid"])
2827 // who is the last child now?
2828 $r = q("SELECT `id` FROM `item` WHERE `parent-uri` = '%s' AND `type` != 'activity' AND `deleted` = 0 AND `moderated` = 0 AND `uid` = %d
2829 ORDER BY `created` DESC LIMIT 1",
2830 dbesc($item["parent-uri"]),
2831 intval($importer["uid"])
2833 if (Dbm::is_result($r)) {
2834 q("UPDATE `item` SET `last-child` = 1 WHERE `id` = %d",
2839 // if this is a relayed delete, propagate it to other recipients
2841 if ($entrytype == DFRN_REPLY_RC) {
2842 logger("Notifying followers about deletion of post " . $item["id"], LOGGER_DEBUG);
2843 Worker::add(PRIORITY_HIGH, "notifier","drop", $item["id"]);
2850 * @brief Imports a DFRN message
2852 * @param text $xml The DFRN message
2853 * @param array $importer Record of the importer user mixed with contact of the content
2854 * @param bool $sort_by_date Is used when feeds are polled
2855 * @return integer Import status
2856 * @todo set proper type-hints
2858 public static function import($xml, $importer, $sort_by_date = false) {
2864 $doc = new DOMDocument();
2865 @$doc->loadXML($xml);
2867 $xpath = new DomXPath($doc);
2868 $xpath->registerNamespace("atom", NAMESPACE_ATOM1);
2869 $xpath->registerNamespace("thr", NAMESPACE_THREAD);
2870 $xpath->registerNamespace("at", NAMESPACE_TOMB);
2871 $xpath->registerNamespace("media", NAMESPACE_MEDIA);
2872 $xpath->registerNamespace("dfrn", NAMESPACE_DFRN);
2873 $xpath->registerNamespace("activity", NAMESPACE_ACTIVITY);
2874 $xpath->registerNamespace("georss", NAMESPACE_GEORSS);
2875 $xpath->registerNamespace("poco", NAMESPACE_POCO);
2876 $xpath->registerNamespace("ostatus", NAMESPACE_OSTATUS);
2877 $xpath->registerNamespace("statusnet", NAMESPACE_STATUSNET);
2880 $header["uid"] = $importer["uid"];
2881 $header["network"] = NETWORK_DFRN;
2882 $header["type"] = "remote";
2883 $header["wall"] = 0;
2884 $header["origin"] = 0;
2885 $header["contact-id"] = $importer["id"];
2887 // Update the contact table if the data has changed
2889 // The "atom:author" is only present in feeds
2890 if ($xpath->query("/atom:feed/atom:author")->length > 0) {
2891 self::fetchauthor($xpath, $doc->firstChild, $importer, "atom:author", false, $xml);
2894 // Only the "dfrn:owner" in the head section contains all data
2895 if ($xpath->query("/atom:feed/dfrn:owner")->length > 0) {
2896 self::fetchauthor($xpath, $doc->firstChild, $importer, "dfrn:owner", false, $xml);
2899 logger("Import DFRN message for user " . $importer["uid"] . " from contact " . $importer["id"], LOGGER_DEBUG);
2901 // The account type is new since 3.5.1
2902 if ($xpath->query("/atom:feed/dfrn:account_type")->length > 0) {
2903 $accounttype = intval($xpath->evaluate("/atom:feed/dfrn:account_type/text()", $context)->item(0)->nodeValue);
2905 if ($accounttype != $importer["contact-type"]) {
2906 dba::update('contact', array('contact-type' => $accounttype), array('id' => $importer["id"]));
2910 // is it a public forum? Private forums aren't supported with this method
2911 // This is deprecated since 3.5.1
2912 $forum = intval($xpath->evaluate("/atom:feed/dfrn:community/text()", $context)->item(0)->nodeValue);
2914 if ($forum != $importer["forum"]) {
2915 $condition = array('`forum` != ? AND `id` = ?', $forum, $importer["id"]);
2916 dba::update('contact', array('forum' => $forum), $condition);
2919 // We are processing relocations even if we are ignoring a contact
2920 $relocations = $xpath->query("/atom:feed/dfrn:relocate");
2921 foreach ($relocations AS $relocation) {
2922 self::process_relocation($xpath, $relocation, $importer);
2925 if ($importer["readonly"]) {
2926 // We aren't receiving stuff from this person. But we will quietly ignore them
2927 // rather than a blatant "go away" message.
2928 logger('ignoring contact '.$importer["id"]);
2932 $mails = $xpath->query("/atom:feed/dfrn:mail");
2933 foreach ($mails AS $mail) {
2934 self::process_mail($xpath, $mail, $importer);
2937 $suggestions = $xpath->query("/atom:feed/dfrn:suggest");
2938 foreach ($suggestions AS $suggestion) {
2939 self::process_suggestion($xpath, $suggestion, $importer);
2942 $deletions = $xpath->query("/atom:feed/at:deleted-entry");
2943 foreach ($deletions AS $deletion) {
2944 self::process_deletion($xpath, $deletion, $importer);
2947 if (!$sort_by_date) {
2948 $entries = $xpath->query("/atom:feed/atom:entry");
2949 foreach ($entries AS $entry) {
2950 self::process_entry($header, $xpath, $entry, $importer, $xml);
2953 $newentries = array();
2954 $entries = $xpath->query("/atom:feed/atom:entry");
2955 foreach ($entries AS $entry) {
2956 $created = $xpath->query("atom:published/text()", $entry)->item(0)->nodeValue;
2957 $newentries[strtotime($created)] = $entry;
2960 // Now sort after the publishing date
2963 foreach ($newentries AS $entry) {
2964 self::process_entry($header, $xpath, $entry, $importer, $xml);
2967 logger("Import done for user " . $importer["uid"] . " from contact " . $importer["id"], LOGGER_DEBUG);