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
9 namespace Friendica\Protocol;
12 use Friendica\Content\OEmbed;
13 use Friendica\Content\Text\BBCode;
14 use Friendica\Content\Text\HTML;
15 use Friendica\Core\Addon;
16 use Friendica\Core\Config;
17 use Friendica\Core\L10n;
18 use Friendica\Core\System;
19 use Friendica\Core\Worker;
20 use Friendica\Database\DBM;
21 use Friendica\Model\Contact;
22 use Friendica\Model\Event;
23 use Friendica\Model\GContact;
24 use Friendica\Model\Group;
25 use Friendica\Model\Item;
26 use Friendica\Model\Profile;
27 use Friendica\Model\User;
28 use Friendica\Object\Image;
29 use Friendica\Protocol\OStatus;
30 use Friendica\Util\Crypto;
31 use Friendica\Util\DateTimeFormat;
32 use Friendica\Util\Network;
33 use Friendica\Util\XML;
34 use Friendica\Protocol\Diaspora;
39 use HTMLPurifier_Config;
41 require_once 'boot.php';
42 require_once 'include/dba.php';
43 require_once "include/enotify.php";
44 require_once "include/items.php";
45 require_once "include/text.php";
48 * @brief This class contain functions to create and send DFRN XML files
53 const DFRN_TOP_LEVEL = 0; // Top level posting
54 const DFRN_REPLY = 1; // Regular reply that is stored locally
55 const DFRN_REPLY_RC = 2; // Reply that will be relayed
58 * @brief Generates the atom entries for delivery.php
60 * This function is used whenever content is transmitted via DFRN.
62 * @param array $items Item elements
63 * @param array $owner Owner record
65 * @return string DFRN entries
66 * @todo Find proper type-hints
68 public static function entries($items, $owner)
70 $doc = new DOMDocument('1.0', 'utf-8');
71 $doc->formatOutput = true;
73 $root = self::addHeader($doc, $owner, "dfrn:owner", "", false);
75 if (! count($items)) {
76 return trim($doc->saveXML());
79 foreach ($items as $item) {
80 $entry = self::entry($doc, "text", $item, $owner, $item["entry:comment-allow"], $item["entry:cid"]);
81 $root->appendChild($entry);
84 return trim($doc->saveXML());
88 * @brief Generate an atom feed for the given user
90 * This function is called when another server is pulling data from the user feed.
92 * @param string $dfrn_id DFRN ID from the requesting party
93 * @param string $owner_nick Owner nick name
94 * @param string $last_update Date of the last update
95 * @param int $direction Can be -1, 0 or 1.
96 * @param boolean $onlyheader Output only the header without content? (Default is "no")
98 * @return string DFRN feed entries
99 * @todo Find proper type-hints
101 public static function feed($dfrn_id, $owner_nick, $last_update, $direction = 0, $onlyheader = false)
105 $sitefeed = ((strlen($owner_nick)) ? false : true); // not yet implemented, need to rewrite huge chunks of following logic
106 $public_feed = (($dfrn_id) ? false : true);
107 $starred = false; // not yet implemented, possible security issues
110 if ($public_feed && $a->argc > 2) {
111 for ($x = 2; $x < $a->argc; $x++) {
112 if ($a->argv[$x] == 'converse') {
115 if ($a->argv[$x] == 'starred') {
118 if ($a->argv[$x] == 'category' && $a->argc > ($x + 1) && strlen($a->argv[$x+1])) {
119 $category = $a->argv[$x+1];
124 // default permissions - anonymous user
126 $sql_extra = " AND `item`.`allow_cid` = '' AND `item`.`allow_gid` = '' AND `item`.`deny_cid` = '' AND `item`.`deny_gid` = '' ";
129 "SELECT `contact`.*, `user`.`nickname`, `user`.`timezone`, `user`.`page-flags`, `user`.`account-type`
130 FROM `contact` INNER JOIN `user` ON `user`.`uid` = `contact`.`uid`
131 WHERE `contact`.`self` AND `user`.`nickname` = '%s' LIMIT 1",
135 if (! DBM::is_result($r)) {
136 logger(sprintf('No contact found for nickname=%d', $owner_nick), LOGGER_WARNING);
141 $owner_id = $owner['uid'];
142 $owner_nick = $owner['nickname'];
144 $sql_post_table = "";
146 if (! $public_feed) {
148 switch ($direction) {
150 $sql_extra = sprintf(" AND `issued-id` = '%s' ", dbesc($dfrn_id));
154 $sql_extra = sprintf(" AND `issued-id` = '%s' AND `duplex` = 1 ", dbesc($dfrn_id));
155 $my_id = '1:' . $dfrn_id;
158 $sql_extra = sprintf(" AND `dfrn-id` = '%s' AND `duplex` = 1 ", dbesc($dfrn_id));
159 $my_id = '0:' . $dfrn_id;
167 "SELECT * FROM `contact` WHERE NOT `blocked` AND `contact`.`uid` = %d $sql_extra LIMIT 1",
171 if (! DBM::is_result($r)) {
172 logger(sprintf('No contact found for uid=%d', $owner_id), LOGGER_WARNING);
177 include_once 'include/security.php';
178 $groups = Group::getIdsByContactId($contact['id']);
180 if (count($groups)) {
181 for ($x = 0; $x < count($groups); $x ++) {
182 $groups[$x] = '<' . intval($groups[$x]) . '>' ;
185 $gs = implode('|', $groups);
187 $gs = '<<>>' ; // Impossible to match
190 $sql_extra = sprintf(
192 AND ( `allow_cid` = '' OR `allow_cid` REGEXP '<%d>' )
193 AND ( `deny_cid` = '' OR NOT `deny_cid` REGEXP '<%d>' )
194 AND ( `allow_gid` = '' OR `allow_gid` REGEXP '%s' )
195 AND ( `deny_gid` = '' OR NOT `deny_gid` REGEXP '%s')
197 intval($contact['id']),
198 intval($contact['id']),
210 if (! strlen($last_update)) {
211 $last_update = 'now -30 days';
214 if (isset($category)) {
215 $sql_post_table = sprintf(
216 "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` ",
217 dbesc(protect_sprintf($category)),
218 intval(TERM_OBJ_POST),
219 intval(TERM_CATEGORY),
222 //$sql_extra .= file_tag_file_query('item',$category,'category');
225 if ($public_feed && ! $converse) {
226 $sql_extra .= " AND `contact`.`self` = 1 ";
229 $check_date = DateTimeFormat::utc($last_update);
232 "SELECT `item`.*, `item`.`id` AS `item_id`,
233 `contact`.`name`, `contact`.`network`, `contact`.`photo`, `contact`.`url`,
234 `contact`.`name-date`, `contact`.`uri-date`, `contact`.`avatar-date`,
235 `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
236 `sign`.`signed_text`, `sign`.`signature`, `sign`.`signer`
237 FROM `item` USE INDEX (`uid_wall_changed`) $sql_post_table
238 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
239 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
240 LEFT JOIN `sign` ON `sign`.`iid` = `item`.`id`
241 WHERE `item`.`uid` = %d AND `item`.`visible` AND NOT `item`.`moderated` AND `item`.`parent` != 0
242 AND `item`.`wall` AND `item`.`changed` > '%s'
244 ORDER BY `item`.`parent` ".$sort.", `item`.`created` ASC LIMIT 0, 300",
251 * Will check further below if this actually returned results.
252 * We will provide an empty feed if that is the case.
257 $doc = new DOMDocument('1.0', 'utf-8');
258 $doc->formatOutput = true;
260 $alternatelink = $owner['url'];
262 if (isset($category)) {
263 $alternatelink .= "/category/".$category;
267 $author = "dfrn:owner";
272 $root = self::addHeader($doc, $owner, $author, $alternatelink, true);
274 /// @TODO This hook can't work anymore
275 // Addon::callHooks('atom_feed', $atom);
277 if (!DBM::is_result($items) || $onlyheader) {
278 $atom = trim($doc->saveXML());
280 Addon::callHooks('atom_feed_end', $atom);
285 foreach ($items as $item) {
286 // prevent private email from leaking.
287 if ($item['network'] == NETWORK_MAIL) {
291 // public feeds get html, our own nodes use bbcode
295 // catch any email that's in a public conversation and make sure it doesn't leak
296 if ($item['private']) {
303 $entry = self::entry($doc, $type, $item, $owner, true);
304 $root->appendChild($entry);
307 $atom = trim($doc->saveXML());
309 Addon::callHooks('atom_feed_end', $atom);
315 * @brief Generate an atom entry for a given item id
317 * @param int $item_id The item id
318 * @param boolean $conversation Show the conversation. If false show the single post.
320 * @return string DFRN feed entry
322 public static function itemFeed($item_id, $conversation = false)
325 $condition = '`item`.`parent`';
327 $condition = '`item`.`id`';
331 "SELECT `item`.*, `item`.`id` AS `item_id`,
332 `contact`.`name`, `contact`.`network`, `contact`.`photo`, `contact`.`url`,
333 `contact`.`name-date`, `contact`.`uri-date`, `contact`.`avatar-date`,
334 `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
335 `sign`.`signed_text`, `sign`.`signature`, `sign`.`signer`
337 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
338 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
339 LEFT JOIN `sign` ON `sign`.`iid` = `item`.`id`
340 WHERE %s = %d AND `item`.`visible` AND NOT `item`.`moderated` AND `item`.`parent` != 0
341 AND NOT `item`.`private`",
346 if (!DBM::is_result($r)) {
353 if ($item['uid'] != 0) {
354 $owner = User::getOwnerDataById($item['uid']);
359 $owner = ['uid' => 0, 'nick' => 'feed-item'];
362 $doc = new DOMDocument('1.0', 'utf-8');
363 $doc->formatOutput = true;
367 $root = $doc->createElementNS(NAMESPACE_ATOM1, 'feed');
368 $doc->appendChild($root);
370 $root->setAttribute("xmlns:thr", NAMESPACE_THREAD);
371 $root->setAttribute("xmlns:at", NAMESPACE_TOMB);
372 $root->setAttribute("xmlns:media", NAMESPACE_MEDIA);
373 $root->setAttribute("xmlns:dfrn", NAMESPACE_DFRN);
374 $root->setAttribute("xmlns:activity", NAMESPACE_ACTIVITY);
375 $root->setAttribute("xmlns:georss", NAMESPACE_GEORSS);
376 $root->setAttribute("xmlns:poco", NAMESPACE_POCO);
377 $root->setAttribute("xmlns:ostatus", NAMESPACE_OSTATUS);
378 $root->setAttribute("xmlns:statusnet", NAMESPACE_STATUSNET);
380 //$root = self::addHeader($doc, $owner, "dfrn:owner", "", false);
382 foreach ($items as $item) {
383 $entry = self::entry($doc, $type, $item, $owner, true, 0);
384 $root->appendChild($entry);
387 $root = self::entry($doc, $type, $item, $owner, true, 0, true);
390 $atom = trim($doc->saveXML());
395 * @brief Create XML text for DFRN mails
397 * @param array $item message elements
398 * @param array $owner Owner record
400 * @return string DFRN mail
401 * @todo Find proper type-hints
403 public static function mail($item, $owner)
405 $doc = new DOMDocument('1.0', 'utf-8');
406 $doc->formatOutput = true;
408 $root = self::addHeader($doc, $owner, "dfrn:owner", "", false);
410 $mail = $doc->createElement("dfrn:mail");
411 $sender = $doc->createElement("dfrn:sender");
413 XML::addElement($doc, $sender, "dfrn:name", $owner['name']);
414 XML::addElement($doc, $sender, "dfrn:uri", $owner['url']);
415 XML::addElement($doc, $sender, "dfrn:avatar", $owner['thumb']);
417 $mail->appendChild($sender);
419 XML::addElement($doc, $mail, "dfrn:id", $item['uri']);
420 XML::addElement($doc, $mail, "dfrn:in-reply-to", $item['parent-uri']);
421 XML::addElement($doc, $mail, "dfrn:sentdate", DateTimeFormat::utc($item['created'] . '+00:00', DateTimeFormat::ATOM));
422 XML::addElement($doc, $mail, "dfrn:subject", $item['title']);
423 XML::addElement($doc, $mail, "dfrn:content", $item['body']);
425 $root->appendChild($mail);
427 return trim($doc->saveXML());
431 * @brief Create XML text for DFRN friend suggestions
433 * @param array $item suggestion elements
434 * @param array $owner Owner record
436 * @return string DFRN suggestions
437 * @todo Find proper type-hints
439 public static function fsuggest($item, $owner)
441 $doc = new DOMDocument('1.0', 'utf-8');
442 $doc->formatOutput = true;
444 $root = self::addHeader($doc, $owner, "dfrn:owner", "", false);
446 $suggest = $doc->createElement("dfrn:suggest");
448 XML::addElement($doc, $suggest, "dfrn:url", $item['url']);
449 XML::addElement($doc, $suggest, "dfrn:name", $item['name']);
450 XML::addElement($doc, $suggest, "dfrn:photo", $item['photo']);
451 XML::addElement($doc, $suggest, "dfrn:request", $item['request']);
452 XML::addElement($doc, $suggest, "dfrn:note", $item['note']);
454 $root->appendChild($suggest);
456 return trim($doc->saveXML());
460 * @brief Create XML text for DFRN relocations
462 * @param array $owner Owner record
463 * @param int $uid User ID
465 * @return string DFRN relocations
466 * @todo Find proper type-hints
468 public static function relocate($owner, $uid)
471 /* get site pubkey. this could be a new installation with no site keys*/
472 $pubkey = Config::get('system', 'site_pubkey');
474 $res = Crypto::newKeypair(1024);
475 Config::set('system', 'site_prvkey', $res['prvkey']);
476 Config::set('system', 'site_pubkey', $res['pubkey']);
480 "SELECT `resource-id` , `scale`, type FROM `photo`
481 WHERE `profile` = 1 AND `uid` = %d ORDER BY scale;",
485 $ext = Image::supportedTypes();
487 foreach ($rp as $p) {
488 $photos[$p['scale']] = System::baseUrl().'/photo/'.$p['resource-id'].'-'.$p['scale'].'.'.$ext[$p['type']];
492 $doc = new DOMDocument('1.0', 'utf-8');
493 $doc->formatOutput = true;
495 $root = self::addHeader($doc, $owner, "dfrn:owner", "", false);
497 $relocate = $doc->createElement("dfrn:relocate");
499 XML::addElement($doc, $relocate, "dfrn:url", $owner['url']);
500 XML::addElement($doc, $relocate, "dfrn:name", $owner['name']);
501 XML::addElement($doc, $relocate, "dfrn:addr", $owner['addr']);
502 XML::addElement($doc, $relocate, "dfrn:avatar", $owner['avatar']);
503 XML::addElement($doc, $relocate, "dfrn:photo", $photos[4]);
504 XML::addElement($doc, $relocate, "dfrn:thumb", $photos[5]);
505 XML::addElement($doc, $relocate, "dfrn:micro", $photos[6]);
506 XML::addElement($doc, $relocate, "dfrn:request", $owner['request']);
507 XML::addElement($doc, $relocate, "dfrn:confirm", $owner['confirm']);
508 XML::addElement($doc, $relocate, "dfrn:notify", $owner['notify']);
509 XML::addElement($doc, $relocate, "dfrn:poll", $owner['poll']);
510 XML::addElement($doc, $relocate, "dfrn:sitepubkey", Config::get('system', 'site_pubkey'));
512 $root->appendChild($relocate);
514 return trim($doc->saveXML());
518 * @brief Adds the header elements for the DFRN protocol
520 * @param object $doc XML document
521 * @param array $owner Owner record
522 * @param string $authorelement Element name for the author
523 * @param string $alternatelink link to profile or category
524 * @param bool $public Is it a header for public posts?
526 * @return object XML root object
527 * @todo Find proper type-hints
529 private static function addHeader($doc, $owner, $authorelement, $alternatelink = "", $public = false)
532 if ($alternatelink == "") {
533 $alternatelink = $owner['url'];
536 $root = $doc->createElementNS(NAMESPACE_ATOM1, 'feed');
537 $doc->appendChild($root);
539 $root->setAttribute("xmlns:thr", NAMESPACE_THREAD);
540 $root->setAttribute("xmlns:at", NAMESPACE_TOMB);
541 $root->setAttribute("xmlns:media", NAMESPACE_MEDIA);
542 $root->setAttribute("xmlns:dfrn", NAMESPACE_DFRN);
543 $root->setAttribute("xmlns:activity", NAMESPACE_ACTIVITY);
544 $root->setAttribute("xmlns:georss", NAMESPACE_GEORSS);
545 $root->setAttribute("xmlns:poco", NAMESPACE_POCO);
546 $root->setAttribute("xmlns:ostatus", NAMESPACE_OSTATUS);
547 $root->setAttribute("xmlns:statusnet", NAMESPACE_STATUSNET);
549 XML::addElement($doc, $root, "id", System::baseUrl()."/profile/".$owner["nick"]);
550 XML::addElement($doc, $root, "title", $owner["name"]);
552 $attributes = ["uri" => "https://friendi.ca", "version" => FRIENDICA_VERSION."-".DB_UPDATE_VERSION];
553 XML::addElement($doc, $root, "generator", FRIENDICA_PLATFORM, $attributes);
555 $attributes = ["rel" => "license", "href" => "http://creativecommons.org/licenses/by/3.0/"];
556 XML::addElement($doc, $root, "link", "", $attributes);
558 $attributes = ["rel" => "alternate", "type" => "text/html", "href" => $alternatelink];
559 XML::addElement($doc, $root, "link", "", $attributes);
563 // DFRN itself doesn't uses this. But maybe someone else wants to subscribe to the public feed.
564 OStatus::hublinks($doc, $root, $owner["nick"]);
566 $attributes = ["rel" => "salmon", "href" => System::baseUrl()."/salmon/".$owner["nick"]];
567 XML::addElement($doc, $root, "link", "", $attributes);
569 $attributes = ["rel" => "http://salmon-protocol.org/ns/salmon-replies", "href" => System::baseUrl()."/salmon/".$owner["nick"]];
570 XML::addElement($doc, $root, "link", "", $attributes);
572 $attributes = ["rel" => "http://salmon-protocol.org/ns/salmon-mention", "href" => System::baseUrl()."/salmon/".$owner["nick"]];
573 XML::addElement($doc, $root, "link", "", $attributes);
576 // For backward compatibility we keep this element
577 if ($owner['page-flags'] == PAGE_COMMUNITY) {
578 XML::addElement($doc, $root, "dfrn:community", 1);
581 // The former element is replaced by this one
582 XML::addElement($doc, $root, "dfrn:account_type", $owner["account-type"]);
584 /// @todo We need a way to transmit the different page flags like "PAGE_PRVGROUP"
586 XML::addElement($doc, $root, "updated", DateTimeFormat::utcNow(DateTimeFormat::ATOM));
588 $author = self::addAuthor($doc, $owner, $authorelement, $public);
589 $root->appendChild($author);
595 * @brief Adds the author element in the header for the DFRN protocol
597 * @param object $doc XML document
598 * @param array $owner Owner record
599 * @param string $authorelement Element name for the author
600 * @param boolean $public boolean
602 * @return object XML author object
603 * @todo Find proper type-hints
605 private static function addAuthor($doc, $owner, $authorelement, $public)
607 // Is the profile hidden or shouldn't be published in the net? Then add the "hide" element
609 "SELECT `id` FROM `profile` INNER JOIN `user` ON `user`.`uid` = `profile`.`uid`
610 WHERE (`hidewall` OR NOT `net-publish`) AND `user`.`uid` = %d",
611 intval($owner['uid'])
613 if (DBM::is_result($r)) {
619 $author = $doc->createElement($authorelement);
621 $namdate = DateTimeFormat::utc($owner['name-date'].'+00:00', DateTimeFormat::ATOM);
622 $uridate = DateTimeFormat::utc($owner['uri-date'].'+00:00', DateTimeFormat::ATOM);
623 $picdate = DateTimeFormat::utc($owner['avatar-date'].'+00:00', DateTimeFormat::ATOM);
627 if (!$public || !$hidewall) {
628 $attributes = ["dfrn:updated" => $namdate];
631 XML::addElement($doc, $author, "name", $owner["name"], $attributes);
632 XML::addElement($doc, $author, "uri", System::baseUrl().'/profile/'.$owner["nickname"], $attributes);
633 XML::addElement($doc, $author, "dfrn:handle", $owner["addr"], $attributes);
635 $attributes = ["rel" => "photo", "type" => "image/jpeg",
636 "media:width" => 175, "media:height" => 175, "href" => $owner['photo']];
638 if (!$public || !$hidewall) {
639 $attributes["dfrn:updated"] = $picdate;
642 XML::addElement($doc, $author, "link", "", $attributes);
644 $attributes["rel"] = "avatar";
645 XML::addElement($doc, $author, "link", "", $attributes);
648 XML::addElement($doc, $author, "dfrn:hide", "true");
651 // The following fields will only be generated if the data isn't meant for a public feed
656 $birthday = feed_birthday($owner['uid'], $owner['timezone']);
659 XML::addElement($doc, $author, "dfrn:birthday", $birthday);
662 // Only show contact details when we are allowed to
664 "SELECT `profile`.`about`, `profile`.`name`, `profile`.`homepage`, `user`.`nickname`,
665 `user`.`timezone`, `profile`.`locality`, `profile`.`region`, `profile`.`country-name`,
666 `profile`.`pub_keywords`, `profile`.`xmpp`, `profile`.`dob`
668 INNER JOIN `user` ON `user`.`uid` = `profile`.`uid`
669 WHERE `profile`.`is-default` AND NOT `user`.`hidewall` AND `user`.`uid` = %d",
670 intval($owner['uid'])
672 if (DBM::is_result($r)) {
675 XML::addElement($doc, $author, "poco:displayName", $profile["name"]);
676 XML::addElement($doc, $author, "poco:updated", $namdate);
678 if (trim($profile["dob"]) > '0001-01-01') {
679 XML::addElement($doc, $author, "poco:birthday", "0000-".date("m-d", strtotime($profile["dob"])));
682 XML::addElement($doc, $author, "poco:note", $profile["about"]);
683 XML::addElement($doc, $author, "poco:preferredUsername", $profile["nickname"]);
685 $savetz = date_default_timezone_get();
686 date_default_timezone_set($profile["timezone"]);
687 XML::addElement($doc, $author, "poco:utcOffset", date("P"));
688 date_default_timezone_set($savetz);
690 if (trim($profile["homepage"]) != "") {
691 $urls = $doc->createElement("poco:urls");
692 XML::addElement($doc, $urls, "poco:type", "homepage");
693 XML::addElement($doc, $urls, "poco:value", $profile["homepage"]);
694 XML::addElement($doc, $urls, "poco:primary", "true");
695 $author->appendChild($urls);
698 if (trim($profile["pub_keywords"]) != "") {
699 $keywords = explode(",", $profile["pub_keywords"]);
701 foreach ($keywords as $keyword) {
702 XML::addElement($doc, $author, "poco:tags", trim($keyword));
706 if (trim($profile["xmpp"]) != "") {
707 $ims = $doc->createElement("poco:ims");
708 XML::addElement($doc, $ims, "poco:type", "xmpp");
709 XML::addElement($doc, $ims, "poco:value", $profile["xmpp"]);
710 XML::addElement($doc, $ims, "poco:primary", "true");
711 $author->appendChild($ims);
714 if (trim($profile["locality"].$profile["region"].$profile["country-name"]) != "") {
715 $element = $doc->createElement("poco:address");
717 XML::addElement($doc, $element, "poco:formatted", Profile::formatLocation($profile));
719 if (trim($profile["locality"]) != "") {
720 XML::addElement($doc, $element, "poco:locality", $profile["locality"]);
723 if (trim($profile["region"]) != "") {
724 XML::addElement($doc, $element, "poco:region", $profile["region"]);
727 if (trim($profile["country-name"]) != "") {
728 XML::addElement($doc, $element, "poco:country", $profile["country-name"]);
731 $author->appendChild($element);
739 * @brief Adds the author elements in the "entry" elements of the DFRN protocol
741 * @param object $doc XML document
742 * @param string $element Element name for the author
743 * @param string $contact_url Link of the contact
744 * @param array $item Item elements
746 * @return object XML author object
747 * @todo Find proper type-hints
749 private static function addEntryAuthor($doc, $element, $contact_url, $item)
751 $contact = Contact::getDetailsByURL($contact_url, $item["uid"]);
753 $author = $doc->createElement($element);
754 XML::addElement($doc, $author, "name", $contact["name"]);
755 XML::addElement($doc, $author, "uri", $contact["url"]);
756 XML::addElement($doc, $author, "dfrn:handle", $contact["addr"]);
759 /// - Check real image type and image size
760 /// - Check which of these boths elements we should use
763 "type" => "image/jpeg",
765 "media:height" => 80,
766 "href" => $contact["photo"]];
767 XML::addElement($doc, $author, "link", "", $attributes);
771 "type" => "image/jpeg",
773 "media:height" => 80,
774 "href" => $contact["photo"]];
775 XML::addElement($doc, $author, "link", "", $attributes);
781 * @brief Adds the activity elements
783 * @param object $doc XML document
784 * @param string $element Element name for the activity
785 * @param string $activity activity value
787 * @return object XML activity object
788 * @todo Find proper type-hints
790 private static function createActivity($doc, $element, $activity)
793 $entry = $doc->createElement($element);
795 $r = XML::parseString($activity, false);
801 XML::addElement($doc, $entry, "activity:object-type", $r->type);
805 XML::addElement($doc, $entry, "id", $r->id);
809 XML::addElement($doc, $entry, "title", $r->title);
813 if (substr($r->link, 0, 1) == '<') {
814 if (strstr($r->link, '&') && (! strstr($r->link, '&'))) {
815 $r->link = str_replace('&', '&', $r->link);
818 $r->link = preg_replace('/\<link(.*?)\"\>/', '<link$1"/>', $r->link);
820 // XML does need a single element as root element so we add a dummy element here
821 $data = XML::parseString("<dummy>" . $r->link . "</dummy>", false);
822 if (is_object($data)) {
823 foreach ($data->link as $link) {
825 foreach ($link->attributes() as $parameter => $value) {
826 $attributes[$parameter] = $value;
828 XML::addElement($doc, $entry, "link", "", $attributes);
832 $attributes = ["rel" => "alternate", "type" => "text/html", "href" => $r->link];
833 XML::addElement($doc, $entry, "link", "", $attributes);
837 XML::addElement($doc, $entry, "content", BBCode::convert($r->content), ["type" => "html"]);
847 * @brief Adds the elements for attachments
849 * @param object $doc XML document
850 * @param object $root XML root
851 * @param array $item Item element
853 * @return object XML attachment object
854 * @todo Find proper type-hints
856 private static function getAttachment($doc, $root, $item)
858 $arr = explode('[/attach],', $item['attach']);
860 foreach ($arr as $r) {
862 $cnt = preg_match('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\" title=\"(.*?)\"|', $r, $matches);
864 $attributes = ["rel" => "enclosure",
865 "href" => $matches[1],
866 "type" => $matches[3]];
868 if (intval($matches[2])) {
869 $attributes["length"] = intval($matches[2]);
872 if (trim($matches[4]) != "") {
873 $attributes["title"] = trim($matches[4]);
876 XML::addElement($doc, $root, "link", "", $attributes);
883 * @brief Adds the "entry" elements for the DFRN protocol
885 * @param object $doc XML document
886 * @param string $type "text" or "html"
887 * @param array $item Item element
888 * @param array $owner Owner record
889 * @param bool $comment Trigger the sending of the "comment" element
890 * @param int $cid Contact ID of the recipient
891 * @param bool $single If set, the entry is created as an XML document with a single "entry" element
893 * @return object XML entry object
894 * @todo Find proper type-hints
896 private static function entry($doc, $type, $item, $owner, $comment = false, $cid = 0, $single = false)
900 if (!$item['parent']) {
904 if ($item['deleted']) {
905 $attributes = ["ref" => $item['uri'], "when" => DateTimeFormat::utc($item['edited'] . '+00:00', DateTimeFormat::ATOM)];
906 return XML::createElement($doc, "at:deleted-entry", "", $attributes);
910 $entry = $doc->createElement("entry");
912 $entry = $doc->createElementNS(NAMESPACE_ATOM1, 'entry');
913 $doc->appendChild($entry);
915 $entry->setAttribute("xmlns:thr", NAMESPACE_THREAD);
916 $entry->setAttribute("xmlns:at", NAMESPACE_TOMB);
917 $entry->setAttribute("xmlns:media", NAMESPACE_MEDIA);
918 $entry->setAttribute("xmlns:dfrn", NAMESPACE_DFRN);
919 $entry->setAttribute("xmlns:activity", NAMESPACE_ACTIVITY);
920 $entry->setAttribute("xmlns:georss", NAMESPACE_GEORSS);
921 $entry->setAttribute("xmlns:poco", NAMESPACE_POCO);
922 $entry->setAttribute("xmlns:ostatus", NAMESPACE_OSTATUS);
923 $entry->setAttribute("xmlns:statusnet", NAMESPACE_STATUSNET);
926 if ($item['allow_cid'] || $item['allow_gid'] || $item['deny_cid'] || $item['deny_gid']) {
927 $body = Item::fixPrivatePhotos($item['body'], $owner['uid'], $item, $cid);
929 $body = $item['body'];
932 // Remove the abstract element. It is only locally important.
933 $body = BBCode::stripAbstract($body);
936 if ($type == 'html') {
939 if ($item['title'] != "") {
940 $htmlbody = "[b]" . $item['title'] . "[/b]\n\n" . $htmlbody;
943 $htmlbody = BBCode::convert($htmlbody, false, 7);
946 $author = self::addEntryAuthor($doc, "author", $item["author-link"], $item);
947 $entry->appendChild($author);
949 $dfrnowner = self::addEntryAuthor($doc, "dfrn:owner", $item["owner-link"], $item);
950 $entry->appendChild($dfrnowner);
952 if (($item['parent'] != $item['id']) || ($item['parent-uri'] !== $item['uri']) || (($item['thr-parent'] !== '') && ($item['thr-parent'] !== $item['uri']))) {
953 $parent_item = (($item['thr-parent']) ? $item['thr-parent'] : $item['parent-uri']);
954 $parent = q("SELECT `guid`,`plink` FROM `item` WHERE `uri` = '%s' AND `uid` = %d", dbesc($parent_item), intval($item['uid']));
955 $attributes = ["ref" => $parent_item, "type" => "text/html",
956 "href" => $parent[0]['plink'],
957 "dfrn:diaspora_guid" => $parent[0]['guid']];
958 XML::addElement($doc, $entry, "thr:in-reply-to", "", $attributes);
961 // Add conversation data. This is used for OStatus
962 $conversation_href = System::baseUrl()."/display/".$owner["nick"]."/".$item["parent"];
963 $conversation_uri = $conversation_href;
965 if (isset($parent_item)) {
966 $r = dba::fetch_first("SELECT `conversation-uri`, `conversation-href` FROM `conversation` WHERE `item-uri` = ?", $item['parent-uri']);
967 if (DBM::is_result($r)) {
968 if ($r['conversation-uri'] != '') {
969 $conversation_uri = $r['conversation-uri'];
971 if ($r['conversation-href'] != '') {
972 $conversation_href = $r['conversation-href'];
978 "href" => $conversation_href,
979 "ref" => $conversation_uri];
981 XML::addElement($doc, $entry, "ostatus:conversation", $conversation_uri, $attributes);
983 XML::addElement($doc, $entry, "id", $item["uri"]);
984 XML::addElement($doc, $entry, "title", $item["title"]);
986 XML::addElement($doc, $entry, "published", DateTimeFormat::utc($item["created"] . "+00:00", DateTimeFormat::ATOM));
987 XML::addElement($doc, $entry, "updated", DateTimeFormat::utc($item["edited"] . "+00:00", DateTimeFormat::ATOM));
989 // "dfrn:env" is used to read the content
990 XML::addElement($doc, $entry, "dfrn:env", base64url_encode($body, true));
992 // The "content" field is not read by the receiver. We could remove it when the type is "text"
993 // We keep it at the moment, maybe there is some old version that doesn't read "dfrn:env"
994 XML::addElement($doc, $entry, "content", (($type == 'html') ? $htmlbody : $body), ["type" => $type]);
996 // We save this value in "plink". Maybe we should read it from there as well?
1002 ["rel" => "alternate", "type" => "text/html",
1003 "href" => System::baseUrl() . "/display/" . $item["guid"]]
1006 // "comment-allow" is some old fashioned stuff for old Friendica versions.
1007 // It is included in the rewritten code for completeness
1009 XML::addElement($doc, $entry, "dfrn:comment-allow", 1);
1012 if ($item['location']) {
1013 XML::addElement($doc, $entry, "dfrn:location", $item['location']);
1016 if ($item['coord']) {
1017 XML::addElement($doc, $entry, "georss:point", $item['coord']);
1020 if (($item['private']) || strlen($item['allow_cid']) || strlen($item['allow_gid']) || strlen($item['deny_cid']) || strlen($item['deny_gid'])) {
1021 XML::addElement($doc, $entry, "dfrn:private", (($item['private']) ? $item['private'] : 1));
1024 if ($item['extid']) {
1025 XML::addElement($doc, $entry, "dfrn:extid", $item['extid']);
1028 if ($item['bookmark']) {
1029 XML::addElement($doc, $entry, "dfrn:bookmark", "true");
1033 XML::addElement($doc, $entry, "statusnet:notice_info", "", ["local_id" => $item['id'], "source" => $item['app']]);
1036 XML::addElement($doc, $entry, "dfrn:diaspora_guid", $item["guid"]);
1038 // The signed text contains the content in Markdown, the sender handle and the signatur for the content
1039 // It is needed for relayed comments to Diaspora.
1040 if ($item['signed_text']) {
1041 $sign = base64_encode(json_encode(['signed_text' => $item['signed_text'],'signature' => $item['signature'],'signer' => $item['signer']]));
1042 XML::addElement($doc, $entry, "dfrn:diaspora_signature", $sign);
1045 XML::addElement($doc, $entry, "activity:verb", self::constructVerb($item));
1047 if ($item['object-type'] != "") {
1048 XML::addElement($doc, $entry, "activity:object-type", $item['object-type']);
1049 } elseif ($item['id'] == $item['parent']) {
1050 XML::addElement($doc, $entry, "activity:object-type", ACTIVITY_OBJ_NOTE);
1052 XML::addElement($doc, $entry, "activity:object-type", ACTIVITY_OBJ_COMMENT);
1055 $actobj = self::createActivity($doc, "activity:object", $item['object']);
1057 $entry->appendChild($actobj);
1060 $actarg = self::createActivity($doc, "activity:target", $item['target']);
1062 $entry->appendChild($actarg);
1065 $tags = Item::getFeedTags($item);
1067 /// @TODO Combine this with similar below if() block?
1069 foreach ($tags as $t) {
1070 if (($type != 'html') || ($t[0] != "@")) {
1071 XML::addElement($doc, $entry, "category", "", ["scheme" => "X-DFRN:".$t[0].":".$t[1], "term" => $t[2]]);
1077 foreach ($tags as $t) {
1079 $mentioned[$t[1]] = $t[1];
1084 foreach ($mentioned as $mention) {
1086 "SELECT `forum`, `prv` FROM `contact` WHERE `uid` = %d AND `nurl` = '%s'",
1087 intval($owner["uid"]),
1088 dbesc(normalise_link($mention))
1091 if (DBM::is_result($r) && ($r[0]["forum"] || $r[0]["prv"])) {
1097 ["rel" => "mentioned",
1098 "ostatus:object-type" => ACTIVITY_OBJ_GROUP,
1107 ["rel" => "mentioned",
1108 "ostatus:object-type" => ACTIVITY_OBJ_PERSON,
1114 self::getAttachment($doc, $entry, $item);
1120 * @brief encrypts data via AES
1122 * @param string $data The data that is to be encrypted
1123 * @param string $key The AES key
1125 * @return string encrypted data
1127 private static function aesEncrypt($data, $key)
1129 return openssl_encrypt($data, 'aes-128-ecb', $key, OPENSSL_RAW_DATA);
1133 * @brief decrypts data via AES
1135 * @param string $encrypted The encrypted data
1136 * @param string $key The AES key
1138 * @return string decrypted data
1140 public static function aesDecrypt($encrypted, $key)
1142 return openssl_decrypt($encrypted, 'aes-128-ecb', $key, OPENSSL_RAW_DATA);
1146 * @brief Delivers the atom content to the contacts
1148 * @param array $owner Owner record
1149 * @param array $contact Contact record of the receiver
1150 * @param string $atom Content that will be transmitted
1151 * @param bool $dissolve (to be documented)
1153 * @return int Deliver status. Negative values mean an error.
1154 * @todo Add array type-hint for $owner, $contact
1156 public static function deliver($owner, $contact, $atom, $dissolve = false)
1160 // At first try the Diaspora transport layer
1161 $ret = self::transmit($owner, $contact, $atom);
1163 logger('Delivery via Diaspora transport layer was successful with status ' . $ret);
1167 $idtosend = $orig_id = (($contact['dfrn-id']) ? $contact['dfrn-id'] : $contact['issued-id']);
1169 if ($contact['duplex'] && $contact['dfrn-id']) {
1170 $idtosend = '0:' . $orig_id;
1172 if ($contact['duplex'] && $contact['issued-id']) {
1173 $idtosend = '1:' . $orig_id;
1176 $rino = Config::get('system', 'rino_encrypt');
1177 $rino = intval($rino);
1179 logger("Local rino version: ". $rino, LOGGER_DEBUG);
1181 $ssl_val = intval(Config::get('system', 'ssl_policy'));
1185 case SSL_POLICY_FULL:
1186 $ssl_policy = 'full';
1188 case SSL_POLICY_SELFSIGN:
1189 $ssl_policy = 'self';
1191 case SSL_POLICY_NONE:
1193 $ssl_policy = 'none';
1197 $url = $contact['notify'] . '&dfrn_id=' . $idtosend . '&dfrn_version=' . DFRN_PROTOCOL_VERSION . (($rino) ? '&rino='.$rino : '');
1199 logger('dfrn_deliver: ' . $url);
1201 $ret = Network::curl($url);
1203 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
1204 Contact::markForArchival($contact);
1205 return -2; // timed out
1208 $xml = $ret['body'];
1210 $curl_stat = $a->get_curl_code();
1211 if (empty($curl_stat)) {
1212 Contact::markForArchival($contact);
1213 return -3; // timed out
1216 logger('dfrn_deliver: ' . $xml, LOGGER_DATA);
1219 Contact::markForArchival($contact);
1223 if (strpos($xml, '<?xml') === false) {
1224 logger('dfrn_deliver: no valid XML returned');
1225 logger('dfrn_deliver: returned XML: ' . $xml, LOGGER_DATA);
1226 Contact::markForArchival($contact);
1230 $res = XML::parseString($xml);
1232 if ((intval($res->status) != 0) || !strlen($res->challenge) || !strlen($res->dfrn_id)) {
1233 Contact::markForArchival($contact);
1234 return ($res->status ? $res->status : 3);
1238 $sent_dfrn_id = hex2bin((string) $res->dfrn_id);
1239 $challenge = hex2bin((string) $res->challenge);
1240 $perm = (($res->perm) ? $res->perm : null);
1241 $dfrn_version = (float) (($res->dfrn_version) ? $res->dfrn_version : 2.0);
1242 $rino_remote_version = intval($res->rino);
1243 $page = (($owner['page-flags'] == PAGE_COMMUNITY) ? 1 : 0);
1245 logger("Remote rino version: ".$rino_remote_version." for ".$contact["url"], LOGGER_DEBUG);
1247 if ($owner['page-flags'] == PAGE_PRVGROUP) {
1251 $final_dfrn_id = '';
1254 if ((($perm == 'rw') && (! intval($contact['writable'])))
1255 || (($perm == 'r') && (intval($contact['writable'])))
1258 "update contact set writable = %d where id = %d",
1259 intval(($perm == 'rw') ? 1 : 0),
1260 intval($contact['id'])
1262 $contact['writable'] = (string) 1 - intval($contact['writable']);
1266 if (($contact['duplex'] && strlen($contact['pubkey']))
1267 || ($owner['page-flags'] == PAGE_COMMUNITY && strlen($contact['pubkey']))
1268 || ($contact['rel'] == CONTACT_IS_SHARING && strlen($contact['pubkey']))
1270 openssl_public_decrypt($sent_dfrn_id, $final_dfrn_id, $contact['pubkey']);
1271 openssl_public_decrypt($challenge, $postvars['challenge'], $contact['pubkey']);
1273 openssl_private_decrypt($sent_dfrn_id, $final_dfrn_id, $contact['prvkey']);
1274 openssl_private_decrypt($challenge, $postvars['challenge'], $contact['prvkey']);
1277 $final_dfrn_id = substr($final_dfrn_id, 0, strpos($final_dfrn_id, '.'));
1279 if (strpos($final_dfrn_id, ':') == 1) {
1280 $final_dfrn_id = substr($final_dfrn_id, 2);
1283 if ($final_dfrn_id != $orig_id) {
1284 logger('dfrn_deliver: wrong dfrn_id.');
1285 // did not decode properly - cannot trust this site
1286 Contact::markForArchival($contact);
1290 $postvars['dfrn_id'] = $idtosend;
1291 $postvars['dfrn_version'] = DFRN_PROTOCOL_VERSION;
1293 $postvars['dissolve'] = '1';
1296 if ((($contact['rel']) && ($contact['rel'] != CONTACT_IS_SHARING) && (! $contact['blocked'])) || ($owner['page-flags'] == PAGE_COMMUNITY)) {
1297 $postvars['data'] = $atom;
1298 $postvars['perm'] = 'rw';
1300 $postvars['data'] = str_replace('<dfrn:comment-allow>1', '<dfrn:comment-allow>0', $atom);
1301 $postvars['perm'] = 'r';
1304 $postvars['ssl_policy'] = $ssl_policy;
1307 $postvars['page'] = $page;
1311 if ($rino > 0 && $rino_remote_version > 0 && (! $dissolve)) {
1312 logger('rino version: '. $rino_remote_version);
1314 switch ($rino_remote_version) {
1316 $key = openssl_random_pseudo_bytes(16);
1317 $data = self::aesEncrypt($postvars['data'], $key);
1320 logger("rino: invalid requested version '$rino_remote_version'");
1321 Contact::markForArchival($contact);
1325 $postvars['rino'] = $rino_remote_version;
1326 $postvars['data'] = bin2hex($data);
1328 if ($dfrn_version >= 2.1) {
1329 if (($contact['duplex'] && strlen($contact['pubkey']))
1330 || ($owner['page-flags'] == PAGE_COMMUNITY && strlen($contact['pubkey']))
1331 || ($contact['rel'] == CONTACT_IS_SHARING && strlen($contact['pubkey']))
1333 openssl_public_encrypt($key, $postvars['key'], $contact['pubkey']);
1335 openssl_private_encrypt($key, $postvars['key'], $contact['prvkey']);
1338 if (($contact['duplex'] && strlen($contact['prvkey'])) || ($owner['page-flags'] == PAGE_COMMUNITY)) {
1339 openssl_private_encrypt($key, $postvars['key'], $contact['prvkey']);
1341 openssl_public_encrypt($key, $postvars['key'], $contact['pubkey']);
1345 logger('md5 rawkey ' . md5($postvars['key']));
1347 $postvars['key'] = bin2hex($postvars['key']);
1351 logger('dfrn_deliver: ' . "SENDING: " . print_r($postvars, true), LOGGER_DATA);
1353 $xml = Network::post($contact['notify'], $postvars);
1355 logger('dfrn_deliver: ' . "RECEIVED: " . $xml, LOGGER_DATA);
1357 $curl_stat = $a->get_curl_code();
1358 if (empty($curl_stat) || empty($xml)) {
1359 Contact::markForArchival($contact);
1360 return -9; // timed out
1363 if (($curl_stat == 503) && stristr($a->get_curl_headers(), 'retry-after')) {
1364 Contact::markForArchival($contact);
1368 if (strpos($xml, '<?xml') === false) {
1369 logger('dfrn_deliver: phase 2: no valid XML returned');
1370 logger('dfrn_deliver: phase 2: returned XML: ' . $xml, LOGGER_DATA);
1371 Contact::markForArchival($contact);
1375 $res = XML::parseString($xml);
1377 if (!isset($res->status)) {
1378 Contact::markForArchival($contact);
1382 // Possibly old servers had returned an empty value when everything was okay
1383 if (empty($res->status)) {
1387 if (!empty($res->message)) {
1388 logger('Delivery returned status '.$res->status.' - '.$res->message, LOGGER_DEBUG);
1391 if (($res->status >= 200) && ($res->status <= 299)) {
1392 Contact::unmarkForArchival($contact);
1395 return intval($res->status);
1399 * @brief Transmits atom content to the contacts via the Diaspora transport layer
1401 * @param array $owner Owner record
1402 * @param array $contact Contact record of the receiver
1403 * @param string $atom Content that will be transmitted
1405 * @return int Deliver status. Negative values mean an error.
1407 public static function transmit($owner, $contact, $atom, $public_batch = false)
1411 if (!$public_batch) {
1412 if (empty($contact['addr'])) {
1413 logger('Empty contact handle for ' . $contact['id'] . ' - ' . $contact['url'] . ' - trying to update it.');
1414 if (Contact::updateFromProbe($contact['id'])) {
1415 $new_contact = dba::selectFirst('contact', ['addr'], ['id' => $contact['id']]);
1416 $contact['addr'] = $new_contact['addr'];
1419 if (empty($contact['addr'])) {
1420 logger('Unable to find contact handle for ' . $contact['id'] . ' - ' . $contact['url']);
1421 Contact::markForArchival($contact);
1426 $fcontact = Diaspora::personByHandle($contact['addr']);
1427 if (empty($fcontact)) {
1428 logger('Unable to find contact details for ' . $contact['id'] . ' - ' . $contact['addr']);
1429 Contact::markForArchival($contact);
1432 $pubkey = $fcontact['pubkey'];
1437 $envelope = Diaspora::buildMessage($atom, $owner, $contact, $owner['uprvkey'], $pubkey, $public_batch);
1439 // Create the endpoint for public posts. This is some WIP and should later be added to the probing
1440 if ($public_batch && empty($contact["batch"])) {
1441 $parts = parse_url($contact["notify"]);
1442 $path_parts = explode('/', $parts['path']);
1443 array_pop($path_parts);
1444 $parts['path'] = implode('/', $path_parts);
1445 $contact["batch"] = Network::unparseURL($parts);
1448 $dest_url = ($public_batch ? $contact["batch"] : $contact["notify"]);
1450 $content_type = ($public_batch ? "application/magic-envelope+xml" : "application/json");
1452 $xml = Network::post($dest_url, $envelope, ["Content-Type: ".$content_type]);
1454 $curl_stat = $a->get_curl_code();
1455 if (empty($curl_stat) || empty($xml)) {
1456 logger('Empty answer from ' . $contact['id'] . ' - ' . $dest_url);
1457 Contact::markForArchival($contact);
1458 return -9; // timed out
1461 if (($curl_stat == 503) && (stristr($a->get_curl_headers(), 'retry-after'))) {
1462 Contact::markForArchival($contact);
1466 if (strpos($xml, '<?xml') === false) {
1467 logger('No valid XML returned from ' . $contact['id'] . ' - ' . $dest_url);
1468 logger('Returned XML: ' . $xml, LOGGER_DATA);
1469 Contact::markForArchival($contact);
1473 $res = XML::parseString($xml);
1475 if (empty($res->status)) {
1476 Contact::markForArchival($contact);
1480 if (!empty($res->message)) {
1481 logger('Transmit to ' . $dest_url . ' returned status '.$res->status.' - '.$res->message, LOGGER_DEBUG);
1484 if (($res->status >= 200) && ($res->status <= 299)) {
1485 Contact::unmarkForArchival($contact);
1488 return intval($res->status);
1492 * @brief Add new birthday event for this person
1494 * @param array $contact Contact record
1495 * @param string $birthday Birthday of the contact
1497 * @todo Add array type-hint for $contact
1499 private static function birthdayEvent($contact, $birthday)
1501 // Check for duplicates
1503 "SELECT `id` FROM `event` WHERE `uid` = %d AND `cid` = %d AND `start` = '%s' AND `type` = '%s' LIMIT 1",
1504 intval($contact['uid']),
1505 intval($contact['id']),
1506 dbesc(DateTimeFormat::utc($birthday)),
1510 if (DBM::is_result($r)) {
1514 logger('updating birthday: ' . $birthday . ' for contact ' . $contact['id']);
1516 $bdtext = L10n::t('%s\'s birthday', $contact['name']);
1517 $bdtext2 = L10n::t('Happy Birthday %s', ' [url=' . $contact['url'] . ']' . $contact['name'] . '[/url]');
1520 "INSERT INTO `event` (`uid`,`cid`,`created`,`edited`,`start`,`finish`,`summary`,`desc`,`type`)
1521 VALUES ( %d, %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s') ",
1522 intval($contact['uid']),
1523 intval($contact['id']),
1524 dbesc(DateTimeFormat::utcNow()),
1525 dbesc(DateTimeFormat::utcNow()),
1526 dbesc(DateTimeFormat::utc($birthday)),
1527 dbesc(DateTimeFormat::utc($birthday . ' + 1 day ')),
1535 * @brief Fetch the author data from head or entry items
1537 * @param object $xpath XPath object
1538 * @param object $context In which context should the data be searched
1539 * @param array $importer Record of the importer user mixed with contact of the content
1540 * @param string $element Element name from which the data is fetched
1541 * @param bool $onlyfetch Should the data only be fetched or should it update the contact record as well
1542 * @param string $xml optional, default empty
1544 * @return array Relevant data of the author
1545 * @todo Find good type-hints for all parameter
1547 private static function fetchauthor($xpath, $context, $importer, $element, $onlyfetch, $xml = "")
1550 $author["name"] = $xpath->evaluate($element."/atom:name/text()", $context)->item(0)->nodeValue;
1551 $author["link"] = $xpath->evaluate($element."/atom:uri/text()", $context)->item(0)->nodeValue;
1553 $contact_old = dba::fetch_first("SELECT `id`, `uid`, `url`, `network`, `avatar-date`, `avatar`, `name-date`, `uri-date`, `addr`,
1554 `name`, `nick`, `about`, `location`, `keywords`, `xmpp`, `bdyear`, `bd`, `hidden`, `contact-type`
1555 FROM `contact` WHERE `uid` = ? AND `nurl` = ? AND `network` != ?",
1556 $importer["importer_uid"],
1557 normalise_link($author["link"]),
1561 if (DBM::is_result($contact_old)) {
1562 $author["contact-id"] = $contact_old["id"];
1563 $author["network"] = $contact_old["network"];
1566 logger("Contact ".$author["link"]." wasn't found for user ".$importer["importer_uid"]." XML: ".$xml, LOGGER_DEBUG);
1569 $author["contact-id"] = $importer["id"];
1570 $author["network"] = $importer["network"];
1574 // Until now we aren't serving different sizes - but maybe later
1576 /// @todo check if "avatar" or "photo" would be the best field in the specification
1577 $avatars = $xpath->query($element . "/atom:link[@rel='avatar']", $context);
1578 foreach ($avatars as $avatar) {
1581 foreach ($avatar->attributes as $attributes) {
1582 /// @TODO Rewrite these similar if() to one switch
1583 if ($attributes->name == "href") {
1584 $href = $attributes->textContent;
1586 if ($attributes->name == "width") {
1587 $width = $attributes->textContent;
1589 if ($attributes->name == "updated") {
1590 $author["avatar-date"] = $attributes->textContent;
1593 if (($width > 0) && ($href != "")) {
1594 $avatarlist[$width] = $href;
1598 if (count($avatarlist) > 0) {
1599 krsort($avatarlist);
1600 $author["avatar"] = current($avatarlist);
1603 if (DBM::is_result($contact_old) && !$onlyfetch) {
1604 logger("Check if contact details for contact " . $contact_old["id"] . " (" . $contact_old["nick"] . ") have to be updated.", LOGGER_DEBUG);
1606 $poco = ["url" => $contact_old["url"]];
1608 // When was the last change to name or uri?
1609 $name_element = $xpath->query($element . "/atom:name", $context)->item(0);
1610 foreach ($name_element->attributes as $attributes) {
1611 if ($attributes->name == "updated") {
1612 $poco["name-date"] = $attributes->textContent;
1616 $link_element = $xpath->query($element . "/atom:link", $context)->item(0);
1617 foreach ($link_element->attributes as $attributes) {
1618 if ($attributes->name == "updated") {
1619 $poco["uri-date"] = $attributes->textContent;
1623 // Update contact data
1624 $value = $xpath->evaluate($element . "/dfrn:handle/text()", $context)->item(0)->nodeValue;
1626 $poco["addr"] = $value;
1629 $value = $xpath->evaluate($element . "/poco:displayName/text()", $context)->item(0)->nodeValue;
1631 $poco["name"] = $value;
1634 $value = $xpath->evaluate($element . "/poco:preferredUsername/text()", $context)->item(0)->nodeValue;
1636 $poco["nick"] = $value;
1639 $value = $xpath->evaluate($element . "/poco:note/text()", $context)->item(0)->nodeValue;
1641 $poco["about"] = $value;
1644 $value = $xpath->evaluate($element . "/poco:address/poco:formatted/text()", $context)->item(0)->nodeValue;
1646 $poco["location"] = $value;
1649 /// @todo Only search for elements with "poco:type" = "xmpp"
1650 $value = $xpath->evaluate($element . "/poco:ims/poco:value/text()", $context)->item(0)->nodeValue;
1652 $poco["xmpp"] = $value;
1655 /// @todo Add support for the following fields that we don't support by now in the contact table:
1656 /// - poco:utcOffset
1662 // If the "hide" element is present then the profile isn't searchable.
1663 $hide = intval($xpath->evaluate($element . "/dfrn:hide/text()", $context)->item(0)->nodeValue == "true");
1665 logger("Hidden status for contact " . $contact_old["url"] . ": " . $hide, LOGGER_DEBUG);
1667 // If the contact isn't searchable then set the contact to "hidden".
1668 // Problem: This can be manually overridden by the user.
1670 $contact_old["hidden"] = true;
1673 // Save the keywords into the contact table
1675 $tagelements = $xpath->evaluate($element . "/poco:tags/text()", $context);
1676 foreach ($tagelements as $tag) {
1677 $tags[$tag->nodeValue] = $tag->nodeValue;
1681 $poco["keywords"] = implode(", ", $tags);
1684 // "dfrn:birthday" contains the birthday converted to UTC
1685 $birthday = $xpath->evaluate($element . "/dfrn:birthday/text()", $context)->item(0)->nodeValue;
1687 if (strtotime($birthday) > time()) {
1688 $bd_timestamp = strtotime($birthday);
1690 $poco["bdyear"] = date("Y", $bd_timestamp);
1693 // "poco:birthday" is the birthday in the format "yyyy-mm-dd"
1694 $value = $xpath->evaluate($element . "/poco:birthday/text()", $context)->item(0)->nodeValue;
1696 if (!in_array($value, ["", "0000-00-00", "0001-01-01"])) {
1697 $bdyear = date("Y");
1698 $value = str_replace("0000", $bdyear, $value);
1700 if (strtotime($value) < time()) {
1701 $value = str_replace($bdyear, $bdyear + 1, $value);
1702 $bdyear = $bdyear + 1;
1705 $poco["bd"] = $value;
1708 $contact = array_merge($contact_old, $poco);
1710 if ($contact_old["bdyear"] != $contact["bdyear"]) {
1711 self::birthdayEvent($contact, $birthday);
1714 // Get all field names
1716 foreach ($contact_old as $field => $data) {
1717 $fields[$field] = $data;
1720 unset($fields["id"]);
1721 unset($fields["uid"]);
1722 unset($fields["url"]);
1723 unset($fields["avatar-date"]);
1724 unset($fields["avatar"]);
1725 unset($fields["name-date"]);
1726 unset($fields["uri-date"]);
1729 // Update check for this field has to be done differently
1730 $datefields = ["name-date", "uri-date"];
1731 foreach ($datefields as $field) {
1732 if (strtotime($contact[$field]) > strtotime($contact_old[$field])) {
1733 logger("Difference for contact " . $contact["id"] . " in field '" . $field . "'. New value: '" . $contact[$field] . "', old value '" . $contact_old[$field] . "'", LOGGER_DEBUG);
1738 foreach ($fields as $field => $data) {
1739 if ($contact[$field] != $contact_old[$field]) {
1740 logger("Difference for contact " . $contact["id"] . " in field '" . $field . "'. New value: '" . $contact[$field] . "', old value '" . $contact_old[$field] . "'", LOGGER_DEBUG);
1746 logger("Update contact data for contact " . $contact["id"] . " (" . $contact["nick"] . ")", LOGGER_DEBUG);
1749 "UPDATE `contact` SET `name` = '%s', `nick` = '%s', `about` = '%s', `location` = '%s',
1750 `addr` = '%s', `keywords` = '%s', `bdyear` = '%s', `bd` = '%s', `hidden` = %d,
1751 `xmpp` = '%s', `name-date` = '%s', `uri-date` = '%s'
1752 WHERE `id` = %d AND `network` = '%s'",
1753 dbesc($contact["name"]), dbesc($contact["nick"]), dbesc($contact["about"]), dbesc($contact["location"]),
1754 dbesc($contact["addr"]), dbesc($contact["keywords"]), dbesc($contact["bdyear"]),
1755 dbesc($contact["bd"]), intval($contact["hidden"]), dbesc($contact["xmpp"]),
1756 dbesc(DBM::date($contact["name-date"])), dbesc(DBM::date($contact["uri-date"])),
1757 intval($contact["id"]), dbesc($contact["network"])
1761 Contact::updateAvatar(
1763 $importer['importer_uid'],
1765 (strtotime($contact['avatar-date']) > strtotime($contact_old['avatar-date']) || ($author['avatar'] != $contact_old['avatar']))
1769 * The generation is a sign for the reliability of the provided data.
1770 * It is used in the socgraph.php to prevent that old contact data
1771 * that was relayed over several servers can overwrite contact
1772 * data that we received directly.
1775 $poco["generation"] = 2;
1776 $poco["photo"] = $author["avatar"];
1777 $poco["hide"] = $hide;
1778 $poco["contact-type"] = $contact["contact-type"];
1779 $gcid = GContact::update($poco);
1781 GContact::link($gcid, $importer["importer_uid"], $contact["id"]);
1788 * @brief Transforms activity objects into an XML string
1790 * @param object $xpath XPath object
1791 * @param object $activity Activity object
1792 * @param string $element element name
1794 * @return string XML string
1795 * @todo Find good type-hints for all parameter
1797 private static function transformActivity($xpath, $activity, $element)
1799 if (!is_object($activity)) {
1803 $obj_doc = new DOMDocument("1.0", "utf-8");
1804 $obj_doc->formatOutput = true;
1806 $obj_element = $obj_doc->createElementNS(NAMESPACE_ATOM1, $element);
1808 $activity_type = $xpath->query("activity:object-type/text()", $activity)->item(0)->nodeValue;
1809 XML::addElement($obj_doc, $obj_element, "type", $activity_type);
1811 $id = $xpath->query("atom:id", $activity)->item(0);
1812 if (is_object($id)) {
1813 $obj_element->appendChild($obj_doc->importNode($id, true));
1816 $title = $xpath->query("atom:title", $activity)->item(0);
1817 if (is_object($title)) {
1818 $obj_element->appendChild($obj_doc->importNode($title, true));
1821 $links = $xpath->query("atom:link", $activity);
1822 if (is_object($links)) {
1823 foreach ($links as $link) {
1824 $obj_element->appendChild($obj_doc->importNode($link, true));
1828 $content = $xpath->query("atom:content", $activity)->item(0);
1829 if (is_object($content)) {
1830 $obj_element->appendChild($obj_doc->importNode($content, true));
1833 $obj_doc->appendChild($obj_element);
1835 $objxml = $obj_doc->saveXML($obj_element);
1837 /// @todo This isn't totally clean. We should find a way to transform the namespaces
1838 $objxml = str_replace("<".$element.' xmlns="http://www.w3.org/2005/Atom">', "<".$element.">", $objxml);
1843 * @brief Processes the mail elements
1845 * @param object $xpath XPath object
1846 * @param object $mail mail elements
1847 * @param array $importer Record of the importer user mixed with contact of the content
1849 * @todo Find good type-hints for all parameter
1851 private static function processMail($xpath, $mail, $importer)
1853 logger("Processing mails");
1855 /// @TODO Rewrite this to one statement
1857 $msg["uid"] = $importer["importer_uid"];
1858 $msg["from-name"] = $xpath->query("dfrn:sender/dfrn:name/text()", $mail)->item(0)->nodeValue;
1859 $msg["from-url"] = $xpath->query("dfrn:sender/dfrn:uri/text()", $mail)->item(0)->nodeValue;
1860 $msg["from-photo"] = $xpath->query("dfrn:sender/dfrn:avatar/text()", $mail)->item(0)->nodeValue;
1861 $msg["contact-id"] = $importer["id"];
1862 $msg["uri"] = $xpath->query("dfrn:id/text()", $mail)->item(0)->nodeValue;
1863 $msg["parent-uri"] = $xpath->query("dfrn:in-reply-to/text()", $mail)->item(0)->nodeValue;
1864 $msg["created"] = DateTimeFormat::utc($xpath->query("dfrn:sentdate/text()", $mail)->item(0)->nodeValue);
1865 $msg["title"] = $xpath->query("dfrn:subject/text()", $mail)->item(0)->nodeValue;
1866 $msg["body"] = $xpath->query("dfrn:content/text()", $mail)->item(0)->nodeValue;
1868 $msg["replied"] = 0;
1870 dba::insert('mail', $msg);
1872 // send notifications.
1873 /// @TODO Arange this mess
1875 "type" => NOTIFY_MAIL,
1876 "notify_flags" => $importer["notify-flags"],
1877 "language" => $importer["language"],
1878 "to_name" => $importer["username"],
1879 "to_email" => $importer["email"],
1880 "uid" => $importer["importer_uid"],
1882 "source_name" => $msg["from-name"],
1883 "source_link" => $importer["url"],
1884 "source_photo" => $importer["thumb"],
1885 "verb" => ACTIVITY_POST,
1889 notification($notif_params);
1891 logger("Mail is processed, notification was sent.");
1895 * @brief Processes the suggestion elements
1897 * @param object $xpath XPath object
1898 * @param object $suggestion suggestion elements
1899 * @param array $importer Record of the importer user mixed with contact of the content
1901 * @todo Find good type-hints for all parameter
1903 private static function processSuggestion($xpath, $suggestion, $importer)
1907 logger("Processing suggestions");
1909 /// @TODO Rewrite this to one statement
1911 $suggest["uid"] = $importer["importer_uid"];
1912 $suggest["cid"] = $importer["id"];
1913 $suggest["url"] = $xpath->query("dfrn:url/text()", $suggestion)->item(0)->nodeValue;
1914 $suggest["name"] = $xpath->query("dfrn:name/text()", $suggestion)->item(0)->nodeValue;
1915 $suggest["photo"] = $xpath->query("dfrn:photo/text()", $suggestion)->item(0)->nodeValue;
1916 $suggest["request"] = $xpath->query("dfrn:request/text()", $suggestion)->item(0)->nodeValue;
1917 $suggest["body"] = $xpath->query("dfrn:note/text()", $suggestion)->item(0)->nodeValue;
1919 // Does our member already have a friend matching this description?
1922 "SELECT `id` FROM `contact` WHERE `name` = '%s' AND `nurl` = '%s' AND `uid` = %d LIMIT 1",
1923 dbesc($suggest["name"]),
1924 dbesc(normalise_link($suggest["url"])),
1925 intval($suggest["uid"])
1929 * The valid result means the friend we're about to send a friend
1930 * suggestion already has them in their contact, which means no further
1931 * action is required.
1933 * @see https://github.com/friendica/friendica/pull/3254#discussion_r107315246
1935 if (DBM::is_result($r)) {
1939 // Do we already have an fcontact record for this person?
1943 "SELECT `id` FROM `fcontact` WHERE `url` = '%s' AND `name` = '%s' AND `request` = '%s' LIMIT 1",
1944 dbesc($suggest["url"]),
1945 dbesc($suggest["name"]),
1946 dbesc($suggest["request"])
1948 if (DBM::is_result($r)) {
1951 // OK, we do. Do we already have an introduction for this person ?
1953 "SELECT `id` FROM `intro` WHERE `uid` = %d AND `fid` = %d LIMIT 1",
1954 intval($suggest["uid"]),
1959 * The valid result means the friend we're about to send a friend
1960 * suggestion already has them in their contact, which means no further
1961 * action is required.
1963 * @see https://github.com/friendica/friendica/pull/3254#discussion_r107315246
1965 if (DBM::is_result($r)) {
1971 "INSERT INTO `fcontact` (`name`,`url`,`photo`,`request`) VALUES ('%s', '%s', '%s', '%s')",
1972 dbesc($suggest["name"]),
1973 dbesc($suggest["url"]),
1974 dbesc($suggest["photo"]),
1975 dbesc($suggest["request"])
1979 "SELECT `id` FROM `fcontact` WHERE `url` = '%s' AND `name` = '%s' AND `request` = '%s' LIMIT 1",
1980 dbesc($suggest["url"]),
1981 dbesc($suggest["name"]),
1982 dbesc($suggest["request"])
1986 * If no record in fcontact is found, below INSERT statement will not
1987 * link an introduction to it.
1989 if (!DBM::is_result($r)) {
1990 // database record did not get created. Quietly give up.
1996 $hash = random_string();
1999 "INSERT INTO `intro` (`uid`, `fid`, `contact-id`, `note`, `hash`, `datetime`, `blocked`)
2000 VALUES(%d, %d, %d, '%s', '%s', '%s', %d)",
2001 intval($suggest["uid"]),
2003 intval($suggest["cid"]),
2004 dbesc($suggest["body"]),
2006 dbesc(DateTimeFormat::utcNow()),
2012 "type" => NOTIFY_SUGGEST,
2013 "notify_flags" => $importer["notify-flags"],
2014 "language" => $importer["language"],
2015 "to_name" => $importer["username"],
2016 "to_email" => $importer["email"],
2017 "uid" => $importer["importer_uid"],
2019 "link" => System::baseUrl()."/notifications/intros",
2020 "source_name" => $importer["name"],
2021 "source_link" => $importer["url"],
2022 "source_photo" => $importer["photo"],
2023 "verb" => ACTIVITY_REQ_FRIEND,
2031 * @brief Processes the relocation elements
2033 * @param object $xpath XPath object
2034 * @param object $relocation relocation elements
2035 * @param array $importer Record of the importer user mixed with contact of the content
2037 * @todo Find good type-hints for all parameter
2039 private static function processRelocation($xpath, $relocation, $importer)
2041 logger("Processing relocations");
2043 /// @TODO Rewrite this to one statement
2045 $relocate["uid"] = $importer["importer_uid"];
2046 $relocate["cid"] = $importer["id"];
2047 $relocate["url"] = $xpath->query("dfrn:url/text()", $relocation)->item(0)->nodeValue;
2048 $relocate["addr"] = $xpath->query("dfrn:addr/text()", $relocation)->item(0)->nodeValue;
2049 $relocate["name"] = $xpath->query("dfrn:name/text()", $relocation)->item(0)->nodeValue;
2050 $relocate["avatar"] = $xpath->query("dfrn:avatar/text()", $relocation)->item(0)->nodeValue;
2051 $relocate["photo"] = $xpath->query("dfrn:photo/text()", $relocation)->item(0)->nodeValue;
2052 $relocate["thumb"] = $xpath->query("dfrn:thumb/text()", $relocation)->item(0)->nodeValue;
2053 $relocate["micro"] = $xpath->query("dfrn:micro/text()", $relocation)->item(0)->nodeValue;
2054 $relocate["request"] = $xpath->query("dfrn:request/text()", $relocation)->item(0)->nodeValue;
2055 $relocate["confirm"] = $xpath->query("dfrn:confirm/text()", $relocation)->item(0)->nodeValue;
2056 $relocate["notify"] = $xpath->query("dfrn:notify/text()", $relocation)->item(0)->nodeValue;
2057 $relocate["poll"] = $xpath->query("dfrn:poll/text()", $relocation)->item(0)->nodeValue;
2058 $relocate["sitepubkey"] = $xpath->query("dfrn:sitepubkey/text()", $relocation)->item(0)->nodeValue;
2060 if (($relocate["avatar"] == "") && ($relocate["photo"] != "")) {
2061 $relocate["avatar"] = $relocate["photo"];
2064 if ($relocate["addr"] == "") {
2065 $relocate["addr"] = preg_replace("=(https?://)(.*)/profile/(.*)=ism", "$3@$2", $relocate["url"]);
2070 "SELECT `photo`, `url` FROM `contact` WHERE `id` = %d AND `uid` = %d;",
2071 intval($importer["id"]),
2072 intval($importer["importer_uid"])
2075 if (!DBM::is_result($r)) {
2076 logger("Query failed to execute, no result returned in " . __FUNCTION__);
2082 // Update the gcontact entry
2083 $relocate["server_url"] = preg_replace("=(https?://)(.*)/profile/(.*)=ism", "$1$2", $relocate["url"]);
2085 $fields = ['name' => $relocate["name"], 'photo' => $relocate["avatar"],
2086 'url' => $relocate["url"], 'nurl' => normalise_link($relocate["url"]),
2087 'addr' => $relocate["addr"], 'connect' => $relocate["addr"],
2088 'notify' => $relocate["notify"], 'server_url' => $relocate["server_url"]];
2089 dba::update('gcontact', $fields, ['nurl' => normalise_link($old["url"])]);
2091 // Update the contact table. We try to find every entry.
2092 $fields = ['name' => $relocate["name"], 'avatar' => $relocate["avatar"],
2093 'url' => $relocate["url"], 'nurl' => normalise_link($relocate["url"]),
2094 'addr' => $relocate["addr"], 'request' => $relocate["request"],
2095 'confirm' => $relocate["confirm"], 'notify' => $relocate["notify"],
2096 'poll' => $relocate["poll"], 'site-pubkey' => $relocate["sitepubkey"]];
2097 $condition = ["(`id` = ?) OR (`nurl` = ?)", $importer["id"], normalise_link($old["url"])];
2098 dba::update('contact', $fields, $condition);
2100 // @TODO No dba:update here?
2101 dba::update('contact', $fields, $condition);
2103 Contact::updateAvatar($relocate["avatar"], $importer["importer_uid"], $importer["id"], true);
2105 logger('Contacts are updated.');
2108 // This is an extreme performance killer
2109 Item::update(['owner-link' => $relocate["url"]], ['owner-link' => $old["url"], 'uid' => $importer["importer_uid"]]);
2110 Item::update(['author-link' => $relocate["url"]], ['author-link' => $old["url"], 'uid' => $importer["importer_uid"]]);
2112 logger('Items are updated.');
2115 /// merge with current record, current contents have priority
2116 /// update record, set url-updated
2117 /// update profile photos
2118 /// schedule a scan?
2123 * @brief Updates an item
2125 * @param array $current the current item record
2126 * @param array $item the new item record
2127 * @param array $importer Record of the importer user mixed with contact of the content
2128 * @param int $entrytype Is it a toplevel entry, a comment or a relayed comment?
2130 * @todo set proper type-hints (array?)
2132 private static function updateContent($current, $item, $importer, $entrytype)
2136 if (self::isEditedTimestampNewer($current, $item)) {
2137 // do not accept (ignore) an earlier edit than one we currently have.
2138 if (DateTimeFormat::utc($item["edited"]) < $current["edited"]) {
2142 $fields = ['title' => defaults($item, 'title', ''), 'body' => defaults($item, 'body', ''),
2143 'tag' => defaults($item, 'tag', ''), 'changed' => DateTimeFormat::utcNow(),
2144 'edited' => DateTimeFormat::utc($item["edited"])];
2146 $condition = ["`uri` = ? AND `uid` IN (0, ?)", $item["uri"], $importer["importer_uid"]];
2147 Item::update($fields, $condition);
2151 if ($entrytype == DFRN_REPLY_RC) {
2152 Worker::add(PRIORITY_HIGH, "Notifier", "comment-import", $current["id"]);
2159 * @brief Detects the entry type of the item
2161 * @param array $importer Record of the importer user mixed with contact of the content
2162 * @param array $item the new item record
2164 * @return int Is it a toplevel entry, a comment or a relayed comment?
2165 * @todo set proper type-hints (array?)
2167 private static function getEntryType($importer, $item)
2169 if ($item["parent-uri"] != $item["uri"]) {
2172 if ($importer["page-flags"] == PAGE_COMMUNITY || $importer["page-flags"] == PAGE_PRVGROUP) {
2175 logger("possible community action");
2177 $sql_extra = " AND `contact`.`self` AND `item`.`wall` ";
2180 // was the top-level post for this action written by somebody on this site?
2181 // Specifically, the recipient?
2183 $is_a_remote_action = false;
2186 "SELECT `item`.`parent-uri` FROM `item`
2187 WHERE `item`.`uri` = '%s'
2189 dbesc($item["parent-uri"])
2191 if (DBM::is_result($r)) {
2193 "SELECT `item`.`forum_mode`, `item`.`wall` FROM `item`
2194 INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
2195 WHERE `item`.`uri` = '%s' AND (`item`.`parent-uri` = '%s' OR `item`.`thr-parent` = '%s')
2196 AND `item`.`uid` = %d
2199 dbesc($r[0]["parent-uri"]),
2200 dbesc($r[0]["parent-uri"]),
2201 dbesc($r[0]["parent-uri"]),
2202 intval($importer["importer_uid"])
2204 if (DBM::is_result($r)) {
2205 $is_a_remote_action = true;
2210 * Does this have the characteristics of a community or private group action?
2211 * If it's an action to a wall post on a community/prvgroup page it's a
2212 * valid community action. Also forum_mode makes it valid for sure.
2213 * If neither, it's not.
2215 if ($is_a_remote_action && $community && (!$r[0]["forum_mode"]) && (!$r[0]["wall"])) {
2216 $is_a_remote_action = false;
2217 logger("not a community action");
2220 if ($is_a_remote_action) {
2221 return DFRN_REPLY_RC;
2226 return DFRN_TOP_LEVEL;
2231 * @brief Send a "poke"
2233 * @param array $item the new item record
2234 * @param array $importer Record of the importer user mixed with contact of the content
2235 * @param int $posted_id The record number of item record that was just posted
2237 * @todo set proper type-hints (array?)
2239 private static function doPoke($item, $importer, $posted_id)
2241 $verb = urldecode(substr($item["verb"], strpos($item["verb"], "#")+1));
2245 $xo = XML::parseString($item["object"], false);
2247 if (($xo->type == ACTIVITY_OBJ_PERSON) && ($xo->id)) {
2248 // somebody was poked/prodded. Was it me?
2249 foreach ($xo->link as $l) {
2250 $atts = $l->attributes();
2251 switch ($atts["rel"]) {
2253 $Blink = $atts["href"];
2260 if ($Blink && link_compare($Blink, System::baseUrl() . "/profile/" . $importer["nickname"])) {
2261 // send a notification
2264 "type" => NOTIFY_POKE,
2265 "notify_flags" => $importer["notify-flags"],
2266 "language" => $importer["language"],
2267 "to_name" => $importer["username"],
2268 "to_email" => $importer["email"],
2269 "uid" => $importer["importer_uid"],
2271 "link" => System::baseUrl()."/display/".urlencode(Item::getGuidById($posted_id)),
2272 "source_name" => stripslashes($item["author-name"]),
2273 "source_link" => $item["author-link"],
2274 "source_photo" => ((link_compare($item["author-link"], $importer["url"]))
2275 ? $importer["thumb"] : $item["author-avatar"]),
2276 "verb" => $item["verb"],
2277 "otype" => "person",
2278 "activity" => $verb,
2279 "parent" => $item["parent"]]
2286 * @brief Processes several actions, depending on the verb
2288 * @param int $entrytype Is it a toplevel entry, a comment or a relayed comment?
2289 * @param array $importer Record of the importer user mixed with contact of the content
2290 * @param array $item the new item record
2291 * @param bool $is_like Is the verb a "like"?
2293 * @return bool Should the processing of the entries be continued?
2294 * @todo set proper type-hints (array?)
2296 private static function processVerbs($entrytype, $importer, &$item, &$is_like)
2298 logger("Process verb ".$item["verb"]." and object-type ".$item["object-type"]." for entrytype ".$entrytype, LOGGER_DEBUG);
2300 if (($entrytype == DFRN_TOP_LEVEL)) {
2301 // The filling of the the "contact" variable is done for legcy reasons
2302 // The functions below are partly used by ostatus.php as well - where we have this variable
2303 $r = q("SELECT * FROM `contact` WHERE `id` = %d", intval($importer["id"]));
2305 $nickname = $contact["nick"];
2307 // Big question: Do we need these functions? They were part of the "consume_feed" function.
2308 // This function once was responsible for DFRN and OStatus.
2309 if (activity_match($item["verb"], ACTIVITY_FOLLOW)) {
2310 logger("New follower");
2311 Contact::addRelationship($importer, $contact, $item, $nickname);
2314 if (activity_match($item["verb"], ACTIVITY_UNFOLLOW)) {
2315 logger("Lost follower");
2316 Contact::removeFollower($importer, $contact, $item);
2319 if (activity_match($item["verb"], ACTIVITY_REQ_FRIEND)) {
2320 logger("New friend request");
2321 Contact::addRelationship($importer, $contact, $item, $nickname, true);
2324 if (activity_match($item["verb"], ACTIVITY_UNFRIEND)) {
2325 logger("Lost sharer");
2326 Contact::removeSharer($importer, $contact, $item);
2330 if (($item["verb"] == ACTIVITY_LIKE)
2331 || ($item["verb"] == ACTIVITY_DISLIKE)
2332 || ($item["verb"] == ACTIVITY_ATTEND)
2333 || ($item["verb"] == ACTIVITY_ATTENDNO)
2334 || ($item["verb"] == ACTIVITY_ATTENDMAYBE)
2337 $item["type"] = "activity";
2338 $item["gravity"] = GRAVITY_LIKE;
2339 // only one like or dislike per person
2340 // splitted into two queries for performance issues
2342 "SELECT `id` FROM `item` WHERE `uid` = %d AND `author-link` = '%s' AND `verb` = '%s' AND `parent-uri` = '%s' AND NOT `deleted` LIMIT 1",
2343 intval($item["uid"]),
2344 dbesc($item["author-link"]),
2345 dbesc($item["verb"]),
2346 dbesc($item["parent-uri"])
2348 if (DBM::is_result($r)) {
2353 "SELECT `id` FROM `item` WHERE `uid` = %d AND `author-link` = '%s' AND `verb` = '%s' AND `thr-parent` = '%s' AND NOT `deleted` LIMIT 1",
2354 intval($item["uid"]),
2355 dbesc($item["author-link"]),
2356 dbesc($item["verb"]),
2357 dbesc($item["parent-uri"])
2359 if (DBM::is_result($r)) {
2366 if (($item["verb"] == ACTIVITY_TAG) && ($item["object-type"] == ACTIVITY_OBJ_TAGTERM)) {
2367 $xo = XML::parseString($item["object"], false);
2368 $xt = XML::parseString($item["target"], false);
2370 if ($xt->type == ACTIVITY_OBJ_NOTE) {
2372 "SELECT `id`, `tag` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2374 intval($importer["importer_uid"])
2377 if (!DBM::is_result($r)) {
2378 logger("Query failed to execute, no result returned in " . __FUNCTION__);
2382 // extract tag, if not duplicate, add to parent item
2384 if (!stristr($r[0]["tag"], trim($xo->content))) {
2385 $tag = $r[0]["tag"] . (strlen($r[0]["tag"]) ? ',' : '') . '#[url=' . $xo->id . ']'. $xo->content . '[/url]';
2386 Item::update(['tag' => $tag], ['id' => $r[0]["id"]]);
2396 * @brief Processes the link elements
2398 * @param object $links link elements
2399 * @param array $item the item record
2401 * @todo set proper type-hints
2403 private static function parseLinks($links, &$item)
2410 foreach ($links as $link) {
2411 foreach ($link->attributes as $attributes) {
2412 switch ($attributes->name) {
2413 case "href" : $href = $attributes->textContent; break;
2414 case "rel" : $rel = $attributes->textContent; break;
2415 case "type" : $type = $attributes->textContent; break;
2416 case "length": $length = $attributes->textContent; break;
2417 case "title" : $title = $attributes->textContent; break;
2420 if (($rel != "") && ($href != "")) {
2423 $item["plink"] = $href;
2427 if (strlen($item["attach"])) {
2428 $item["attach"] .= ",";
2431 $item["attach"] .= '[attach]href="' . $href . '" length="' . $length . '" type="' . $type . '" title="' . $title . '"[/attach]';
2439 * @brief Processes the entry elements which contain the items and comments
2441 * @param array $header Array of the header elements that always stay the same
2442 * @param object $xpath XPath object
2443 * @param object $entry entry elements
2444 * @param array $importer Record of the importer user mixed with contact of the content
2445 * @param object $xml xml
2447 * @todo Add type-hints
2449 private static function processEntry($header, $xpath, $entry, $importer, $xml)
2451 logger("Processing entries");
2455 $item["protocol"] = PROTOCOL_DFRN;
2457 $item["source"] = $xml;
2460 $item["uri"] = $xpath->query("atom:id/text()", $entry)->item(0)->nodeValue;
2462 $item["edited"] = $xpath->query("atom:updated/text()", $entry)->item(0)->nodeValue;
2464 $current = dba::selectFirst('item',
2465 ['id', 'uid', 'edited', 'body'],
2466 ['uri' => $item["uri"], 'uid' => $importer["importer_uid"]]
2468 // Is there an existing item?
2469 if (DBM::is_result($current) && !self::isEditedTimestampNewer($current, $item)) {
2470 logger("Item ".$item["uri"]." (".$item['edited'].") already existed.", LOGGER_DEBUG);
2475 $owner = self::fetchauthor($xpath, $entry, $importer, "dfrn:owner", true);
2477 $item["owner-name"] = $owner["name"];
2478 $item["owner-link"] = $owner["link"];
2479 $item["owner-avatar"] = $owner["avatar"];
2482 $author = self::fetchauthor($xpath, $entry, $importer, "atom:author", true);
2484 $item["author-name"] = $author["name"];
2485 $item["author-link"] = $author["link"];
2486 $item["author-avatar"] = $author["avatar"];
2488 $item["title"] = $xpath->query("atom:title/text()", $entry)->item(0)->nodeValue;
2490 $item["created"] = $xpath->query("atom:published/text()", $entry)->item(0)->nodeValue;
2492 $item["body"] = $xpath->query("dfrn:env/text()", $entry)->item(0)->nodeValue;
2493 $item["body"] = str_replace([' ',"\t","\r","\n"], ['','','',''], $item["body"]);
2494 // make sure nobody is trying to sneak some html tags by us
2495 $item["body"] = notags(base64url_decode($item["body"]));
2497 $item["body"] = BBCode::limitBodySize($item["body"]);
2499 /// @todo Do we really need this check for HTML elements? (It was copied from the old function)
2500 if ((strpos($item['body'], '<') !== false) && (strpos($item['body'], '>') !== false)) {
2501 $base_url = get_app()->get_baseurl();
2502 $item['body'] = reltoabs($item['body'], $base_url);
2504 $item['body'] = html2bb_video($item['body']);
2506 $item['body'] = OEmbed::HTML2BBCode($item['body']);
2508 $config = HTMLPurifier_Config::createDefault();
2509 $config->set('Cache.DefinitionImpl', null);
2511 // we shouldn't need a whitelist, because the bbcode converter
2512 // will strip out any unsupported tags.
2514 $purifier = new HTMLPurifier($config);
2515 $item['body'] = $purifier->purify($item['body']);
2517 $item['body'] = @HTML::toBBCode($item['body']);
2520 /// @todo We should check for a repeated post and if we know the repeated author.
2522 // We don't need the content element since "dfrn:env" is always present
2523 //$item["body"] = $xpath->query("atom:content/text()", $entry)->item(0)->nodeValue;
2525 $item["location"] = $xpath->query("dfrn:location/text()", $entry)->item(0)->nodeValue;
2527 $georsspoint = $xpath->query("georss:point", $entry);
2529 $item["coord"] = $georsspoint->item(0)->nodeValue;
2532 $item["private"] = $xpath->query("dfrn:private/text()", $entry)->item(0)->nodeValue;
2534 $item["extid"] = $xpath->query("dfrn:extid/text()", $entry)->item(0)->nodeValue;
2536 if ($xpath->query("dfrn:bookmark/text()", $entry)->item(0)->nodeValue == "true") {
2537 $item["bookmark"] = true;
2540 $notice_info = $xpath->query("statusnet:notice_info", $entry);
2541 if ($notice_info && ($notice_info->length > 0)) {
2542 foreach ($notice_info->item(0)->attributes as $attributes) {
2543 if ($attributes->name == "source") {
2544 $item["app"] = strip_tags($attributes->textContent);
2549 $item["guid"] = $xpath->query("dfrn:diaspora_guid/text()", $entry)->item(0)->nodeValue;
2551 // We store the data from "dfrn:diaspora_signature" in a different table, this is done in "Item::insert"
2552 $dsprsig = unxmlify($xpath->query("dfrn:diaspora_signature/text()", $entry)->item(0)->nodeValue);
2553 if ($dsprsig != "") {
2554 $item["dsprsig"] = $dsprsig;
2557 $item["verb"] = $xpath->query("activity:verb/text()", $entry)->item(0)->nodeValue;
2559 if ($xpath->query("activity:object-type/text()", $entry)->item(0)->nodeValue != "") {
2560 $item["object-type"] = $xpath->query("activity:object-type/text()", $entry)->item(0)->nodeValue;
2563 $object = $xpath->query("activity:object", $entry)->item(0);
2564 $item["object"] = self::transformActivity($xpath, $object, "object");
2566 if (trim($item["object"]) != "") {
2567 $r = XML::parseString($item["object"], false);
2568 if (isset($r->type)) {
2569 $item["object-type"] = $r->type;
2573 $target = $xpath->query("activity:target", $entry)->item(0);
2574 $item["target"] = self::transformActivity($xpath, $target, "target");
2576 $categories = $xpath->query("atom:category", $entry);
2578 foreach ($categories as $category) {
2581 foreach ($category->attributes as $attributes) {
2582 if ($attributes->name == "term") {
2583 $term = $attributes->textContent;
2586 if ($attributes->name == "scheme") {
2587 $scheme = $attributes->textContent;
2591 if (($term != "") && ($scheme != "")) {
2592 $parts = explode(":", $scheme);
2593 if ((count($parts) >= 4) && (array_shift($parts) == "X-DFRN")) {
2594 $termhash = array_shift($parts);
2595 $termurl = implode(":", $parts);
2597 if (strlen($item["tag"])) {
2598 $item["tag"] .= ",";
2601 $item["tag"] .= $termhash . "[url=" . $termurl . "]" . $term . "[/url]";
2609 $links = $xpath->query("atom:link", $entry);
2611 self::parseLinks($links, $item);
2614 $item['conversation-uri'] = $xpath->query('ostatus:conversation/text()', $entry)->item(0)->nodeValue;
2616 $conv = $xpath->query('ostatus:conversation', $entry);
2617 if (is_object($conv->item(0))) {
2618 foreach ($conv->item(0)->attributes as $attributes) {
2619 if ($attributes->name == "ref") {
2620 $item['conversation-uri'] = $attributes->textContent;
2622 if ($attributes->name == "href") {
2623 $item['conversation-href'] = $attributes->textContent;
2628 // Is it a reply or a top level posting?
2629 $item["parent-uri"] = $item["uri"];
2631 $inreplyto = $xpath->query("thr:in-reply-to", $entry);
2632 if (is_object($inreplyto->item(0))) {
2633 foreach ($inreplyto->item(0)->attributes as $attributes) {
2634 if ($attributes->name == "ref") {
2635 $item["parent-uri"] = $attributes->textContent;
2640 // Get the type of the item (Top level post, reply or remote reply)
2641 $entrytype = self::getEntryType($importer, $item);
2643 // Now assign the rest of the values that depend on the type of the message
2644 if (in_array($entrytype, [DFRN_REPLY, DFRN_REPLY_RC])) {
2645 if (!isset($item["object-type"])) {
2646 $item["object-type"] = ACTIVITY_OBJ_COMMENT;
2649 if ($item["contact-id"] != $owner["contact-id"]) {
2650 $item["contact-id"] = $owner["contact-id"];
2653 if (($item["network"] != $owner["network"]) && ($owner["network"] != "")) {
2654 $item["network"] = $owner["network"];
2657 if ($item["contact-id"] != $author["contact-id"]) {
2658 $item["contact-id"] = $author["contact-id"];
2661 if (($item["network"] != $author["network"]) && ($author["network"] != "")) {
2662 $item["network"] = $author["network"];
2666 if ($entrytype == DFRN_REPLY_RC) {
2667 $item["type"] = "remote-comment";
2669 } elseif ($entrytype == DFRN_TOP_LEVEL) {
2670 if (!isset($item["object-type"])) {
2671 $item["object-type"] = ACTIVITY_OBJ_NOTE;
2675 if ($item["object-type"] == ACTIVITY_OBJ_EVENT) {
2676 logger("Item ".$item["uri"]." seems to contain an event.", LOGGER_DEBUG);
2677 $ev = Event::fromBBCode($item["body"]);
2678 if ((x($ev, "desc") || x($ev, "summary")) && x($ev, "start")) {
2679 logger("Event in item ".$item["uri"]." was found.", LOGGER_DEBUG);
2680 $ev["cid"] = $importer["id"];
2681 $ev["uid"] = $importer["importer_uid"];
2682 $ev["uri"] = $item["uri"];
2683 $ev["edited"] = $item["edited"];
2684 $ev["private"] = $item["private"];
2685 $ev["guid"] = $item["guid"];
2688 "SELECT `id` FROM `event` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2689 dbesc($item["uri"]),
2690 intval($importer["importer_uid"])
2692 if (DBM::is_result($r)) {
2693 $ev["id"] = $r[0]["id"];
2696 $event_id = Event::store($ev);
2697 logger("Event ".$event_id." was stored", LOGGER_DEBUG);
2703 if (!self::processVerbs($entrytype, $importer, $item, $is_like)) {
2704 logger("Exiting because 'processVerbs' told us so", LOGGER_DEBUG);
2708 // Update content if 'updated' changes
2709 if (DBM::is_result($current)) {
2710 if (self::updateContent($current, $item, $importer, $entrytype)) {
2711 logger("Item ".$item["uri"]." was updated.", LOGGER_DEBUG);
2713 logger("Item " . $item["uri"] . " already existed.", LOGGER_DEBUG);
2718 if (in_array($entrytype, [DFRN_REPLY, DFRN_REPLY_RC])) {
2719 $posted_id = Item::insert($item);
2723 logger("Reply from contact ".$item["contact-id"]." was stored with id ".$posted_id, LOGGER_DEBUG);
2725 if ($item['uid'] == 0) {
2726 Item::distribute($posted_id);
2729 $item["id"] = $posted_id;
2732 "SELECT `parent`, `parent-uri` FROM `item` WHERE `id` = %d AND `uid` = %d LIMIT 1",
2734 intval($importer["importer_uid"])
2736 if (DBM::is_result($r)) {
2737 $parent = $r[0]["parent"];
2738 $parent_uri = $r[0]["parent-uri"];
2741 if ($posted_id && $parent && ($entrytype == DFRN_REPLY_RC)) {
2742 logger("Notifying followers about comment ".$posted_id, LOGGER_DEBUG);
2743 Worker::add(PRIORITY_HIGH, "Notifier", "comment-import", $posted_id);
2748 } else { // $entrytype == DFRN_TOP_LEVEL
2749 if (($importer["uid"] == 0) && ($importer["importer_uid"] != 0)) {
2750 logger("Contact ".$importer["id"]." isn't known to user ".$importer["importer_uid"].". The post will be ignored.", LOGGER_DEBUG);
2753 if (!link_compare($item["owner-link"], $importer["url"])) {
2755 * The item owner info is not our contact. It's OK and is to be expected if this is a tgroup delivery,
2756 * but otherwise there's a possible data mixup on the sender's system.
2757 * the tgroup delivery code called from Item::insert will correct it if it's a forum,
2758 * but we're going to unconditionally correct it here so that the post will always be owned by our contact.
2760 logger('Correcting item owner.', LOGGER_DEBUG);
2761 $item["owner-name"] = $importer["senderName"];
2762 $item["owner-link"] = $importer["url"];
2763 $item["owner-avatar"] = $importer["thumb"];
2766 if (($importer["rel"] == CONTACT_IS_FOLLOWER) && (!self::tgroupCheck($importer["importer_uid"], $item))) {
2767 logger("Contact ".$importer["id"]." is only follower and tgroup check was negative.", LOGGER_DEBUG);
2771 // This is my contact on another system, but it's really me.
2772 // Turn this into a wall post.
2773 $notify = Item::isRemoteSelf($importer, $item);
2775 $posted_id = Item::insert($item, false, $notify);
2778 $posted_id = $notify;
2781 logger("Item was stored with id ".$posted_id, LOGGER_DEBUG);
2783 if ($item['uid'] == 0) {
2784 Item::distribute($posted_id);
2787 if (stristr($item["verb"], ACTIVITY_POKE)) {
2788 self::doPoke($item, $importer, $posted_id);
2794 * @brief Deletes items
2796 * @param object $xpath XPath object
2797 * @param object $deletion deletion elements
2798 * @param array $importer Record of the importer user mixed with contact of the content
2800 * @todo set proper type-hints
2802 private static function processDeletion($xpath, $deletion, $importer)
2804 logger("Processing deletions");
2807 foreach ($deletion->attributes as $attributes) {
2808 if ($attributes->name == "ref") {
2809 $uri = $attributes->textContent;
2813 if (!$uri || !$importer["id"]) {
2817 $condition = ["`uri` = ? AND `uid` = ? AND NOT `file` LIKE '%[%'", $uri, $importer["importer_uid"]];
2818 $item = dba::selectFirst('item', ['id', 'parent', 'contact-id'], $condition);
2819 if (!DBM::is_result($item)) {
2820 logger("Item with uri " . $uri . " for user " . $importer["importer_uid"] . " wasn't found.", LOGGER_DEBUG);
2824 // When it is a starting post it has to belong to the person that wants to delete it
2825 if (($item['id'] == $item['parent']) && ($item['contact-id'] != $importer["id"])) {
2826 logger("Item with uri " . $uri . " don't belong to contact " . $importer["id"] . " - ignoring deletion.", LOGGER_DEBUG);
2830 // Comments can be deleted by the thread owner or comment owner
2831 if (($item['id'] != $item['parent']) && ($item['contact-id'] != $importer["id"])) {
2832 $condition = ['id' => $item['parent'], 'contact-id' => $importer["id"]];
2833 if (!dba::exists('item', $condition)) {
2834 logger("Item with uri " . $uri . " wasn't found or mustn't be deleted by contact " . $importer["id"] . " - ignoring deletion.", LOGGER_DEBUG);
2839 $entrytype = self::getEntryType($importer, $item);
2841 if (!$item["deleted"]) {
2842 logger('deleting item '.$item["id"].' uri='.$uri, LOGGER_DEBUG);
2847 Item::deleteById($item["id"]);
2849 if ($entrytype != DFRN_TOP_LEVEL) {
2850 // if this is a relayed delete, propagate it to other recipients
2851 if ($entrytype == DFRN_REPLY_RC) {
2852 logger("Notifying followers about deletion of post " . $item["id"], LOGGER_DEBUG);
2853 Worker::add(PRIORITY_HIGH, "Notifier", "drop", $item["id"]);
2859 * @brief Imports a DFRN message
2861 * @param string $xml The DFRN message
2862 * @param array $importer Record of the importer user mixed with contact of the content
2863 * @param bool $sort_by_date Is used when feeds are polled
2864 * @return integer Import status
2865 * @todo set proper type-hints
2867 public static function import($xml, $importer, $sort_by_date = false)
2873 $doc = new DOMDocument();
2874 @$doc->loadXML($xml);
2876 $xpath = new DOMXPath($doc);
2877 $xpath->registerNamespace("atom", NAMESPACE_ATOM1);
2878 $xpath->registerNamespace("thr", NAMESPACE_THREAD);
2879 $xpath->registerNamespace("at", NAMESPACE_TOMB);
2880 $xpath->registerNamespace("media", NAMESPACE_MEDIA);
2881 $xpath->registerNamespace("dfrn", NAMESPACE_DFRN);
2882 $xpath->registerNamespace("activity", NAMESPACE_ACTIVITY);
2883 $xpath->registerNamespace("georss", NAMESPACE_GEORSS);
2884 $xpath->registerNamespace("poco", NAMESPACE_POCO);
2885 $xpath->registerNamespace("ostatus", NAMESPACE_OSTATUS);
2886 $xpath->registerNamespace("statusnet", NAMESPACE_STATUSNET);
2889 $header["uid"] = $importer["importer_uid"];
2890 $header["network"] = NETWORK_DFRN;
2891 $header["type"] = "remote";
2892 $header["wall"] = 0;
2893 $header["origin"] = 0;
2894 $header["contact-id"] = $importer["id"];
2896 // Update the contact table if the data has changed
2898 // The "atom:author" is only present in feeds
2899 if ($xpath->query("/atom:feed/atom:author")->length > 0) {
2900 self::fetchauthor($xpath, $doc->firstChild, $importer, "atom:author", false, $xml);
2903 // Only the "dfrn:owner" in the head section contains all data
2904 if ($xpath->query("/atom:feed/dfrn:owner")->length > 0) {
2905 self::fetchauthor($xpath, $doc->firstChild, $importer, "dfrn:owner", false, $xml);
2908 logger("Import DFRN message for user " . $importer["importer_uid"] . " from contact " . $importer["id"], LOGGER_DEBUG);
2910 // is it a public forum? Private forums aren't exposed with this method
2911 $forum = intval($xpath->evaluate("/atom:feed/dfrn:community/text()")->item(0)->nodeValue);
2913 // The account type is new since 3.5.1
2914 if ($xpath->query("/atom:feed/dfrn:account_type")->length > 0) {
2915 $accounttype = intval($xpath->evaluate("/atom:feed/dfrn:account_type/text()")->item(0)->nodeValue);
2917 if ($accounttype != $importer["contact-type"]) {
2918 dba::update('contact', ['contact-type' => $accounttype], ['id' => $importer["id"]]);
2920 // A forum contact can either have set "forum" or "prv" - but not both
2921 if (($accounttype == ACCOUNT_TYPE_COMMUNITY) && (($forum != $importer["forum"]) || ($forum == $importer["prv"]))) {
2922 $condition = ['(`forum` != ? OR `prv` != ?) AND `id` = ?', $forum, !$forum, $importer["id"]];
2923 dba::update('contact', ['forum' => $forum, 'prv' => !$forum], $condition);
2925 } elseif ($forum != $importer["forum"]) { // Deprecated since 3.5.1
2926 $condition = ['`forum` != ? AND `id` = ?', $forum, $importer["id"]];
2927 dba::update('contact', ['forum' => $forum], $condition);
2931 // We are processing relocations even if we are ignoring a contact
2932 $relocations = $xpath->query("/atom:feed/dfrn:relocate");
2933 foreach ($relocations as $relocation) {
2934 self::processRelocation($xpath, $relocation, $importer);
2937 if (($importer["uid"] != 0) && !$importer["readonly"]) {
2938 $mails = $xpath->query("/atom:feed/dfrn:mail");
2939 foreach ($mails as $mail) {
2940 self::processMail($xpath, $mail, $importer);
2943 $suggestions = $xpath->query("/atom:feed/dfrn:suggest");
2944 foreach ($suggestions as $suggestion) {
2945 self::processSuggestion($xpath, $suggestion, $importer);
2949 $deletions = $xpath->query("/atom:feed/at:deleted-entry");
2950 foreach ($deletions as $deletion) {
2951 self::processDeletion($xpath, $deletion, $importer);
2954 if (!$sort_by_date) {
2955 $entries = $xpath->query("/atom:feed/atom:entry");
2956 foreach ($entries as $entry) {
2957 self::processEntry($header, $xpath, $entry, $importer, $xml);
2961 $entries = $xpath->query("/atom:feed/atom:entry");
2962 foreach ($entries as $entry) {
2963 $created = $xpath->query("atom:published/text()", $entry)->item(0)->nodeValue;
2964 $newentries[strtotime($created)] = $entry;
2967 // Now sort after the publishing date
2970 foreach ($newentries as $entry) {
2971 self::processEntry($header, $xpath, $entry, $importer, $xml);
2974 logger("Import done for user " . $importer["importer_uid"] . " from contact " . $importer["id"], LOGGER_DEBUG);
2980 * @param string $contact_nick contact nickname
2982 public static function autoRedir(App $a, $contact_nick)
2985 if (x($_REQUEST, 'redir') && intval($_REQUEST['redir'])) {
2989 if ((! $contact_nick) || ($contact_nick === $a->user['nickname'])) {
2994 // We need to find out if $contact_nick is a user on this hub, and if so, if I
2995 // am a contact of that user. However, that user may have other contacts with the
2996 // same nickname as me on other hubs or other networks. Exclude these by requiring
2997 // that the contact have a local URL. I will be the only person with my nickname at
2998 // this URL, so if a result is found, then I am a contact of the $contact_nick user.
3000 // We also have to make sure that I'm a legitimate contact--I'm not blocked or pending.
3002 $baseurl = System::baseUrl();
3003 $domain_st = strpos($baseurl, "://");
3004 if ($domain_st === false) {
3007 $baseurl = substr($baseurl, $domain_st + 3);
3008 $nurl = normalise_link($baseurl);
3010 /// @todo Why is there a query for "url" *and* "nurl"? Especially this normalising is strange.
3011 $r = q("SELECT `id` FROM `contact` WHERE `uid` = (SELECT `uid` FROM `user` WHERE `nickname` = '%s' LIMIT 1)
3012 AND `nick` = '%s' AND NOT `self` AND (`url` LIKE '%%%s%%' OR `nurl` LIKE '%%%s%%') AND NOT `blocked` AND NOT `pending` LIMIT 1",
3013 dbesc($contact_nick),
3014 dbesc($a->user['nickname']),
3018 if ((! DBM::is_result($r)) || $r[0]['id'] == remote_user()) {
3022 $r = q("SELECT * FROM contact WHERE nick = '%s'
3023 AND network = '%s' AND uid = %d AND url LIKE '%%%s%%' LIMIT 1",
3024 dbesc($contact_nick),
3025 dbesc(NETWORK_DFRN),
3026 intval(local_user()),
3029 if (! DBM::is_result($r)) {
3035 $dfrn_id = (($r[0]['issued-id']) ? $r[0]['issued-id'] : $r[0]['dfrn-id']);
3037 if ($r[0]['duplex'] && $r[0]['issued-id']) {
3038 $orig_id = $r[0]['issued-id'];
3039 $dfrn_id = '1:' . $orig_id;
3041 if ($r[0]['duplex'] && $r[0]['dfrn-id']) {
3042 $orig_id = $r[0]['dfrn-id'];
3043 $dfrn_id = '0:' . $orig_id;
3046 // ensure that we've got a valid ID. There may be some edge cases with forums and non-duplex mode
3047 // that may have triggered some of the "went to {profile/intro} and got an RSS feed" issues
3049 if (strlen($dfrn_id) < 3) {
3053 $sec = random_string();
3055 dba::insert('profile_check', ['uid' => local_user(), 'cid' => $cid, 'dfrn_id' => $dfrn_id, 'sec' => $sec, 'expire' => time() + 45]);
3057 $url = curPageURL();
3059 logger('auto_redir: ' . $r[0]['name'] . ' ' . $sec, LOGGER_DEBUG);
3060 $dest = (($url) ? '&destination_url=' . $url : '');
3061 goaway($r[0]['poll'] . '?dfrn_id=' . $dfrn_id
3062 . '&dfrn_version=' . DFRN_PROTOCOL_VERSION . '&type=profile&sec=' . $sec . $dest);
3069 * @brief Returns the activity verb
3071 * @param array $item Item array
3073 * @return string activity verb
3075 private static function constructVerb(array $item)
3077 if ($item['verb']) {
3078 return $item['verb'];
3080 return ACTIVITY_POST;
3083 private static function tgroupCheck($uid, $item)
3087 // check that the message originated elsewhere and is a top-level post
3089 if ($item['wall'] || $item['origin'] || ($item['uri'] != $item['parent-uri'])) {
3093 $u = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1",
3096 if (!DBM::is_result($u)) {
3100 $community_page = ($u[0]['page-flags'] == PAGE_COMMUNITY);
3101 $prvgroup = ($u[0]['page-flags'] == PAGE_PRVGROUP);
3103 $link = normalise_link(System::baseUrl() . '/profile/' . $u[0]['nickname']);
3106 * Diaspora uses their own hardwired link URL in @-tags
3107 * instead of the one we supply with webfinger
3109 $dlink = normalise_link(System::baseUrl() . '/u/' . $u[0]['nickname']);
3111 $cnt = preg_match_all('/[\@\!]\[url\=(.*?)\](.*?)\[\/url\]/ism', $item['body'], $matches, PREG_SET_ORDER);
3113 foreach ($matches as $mtch) {
3114 if (link_compare($link, $mtch[1]) || link_compare($dlink, $mtch[1])) {
3116 logger('mention found: ' . $mtch[2]);
3125 return $community_page || $prvgroup;
3129 * This function returns true if $update has an edited timestamp newer
3130 * than $existing, i.e. $update contains new data which should override
3131 * what's already there. If there is no timestamp yet, the update is
3132 * assumed to be newer. If the update has no timestamp, the existing
3133 * item is assumed to be up-to-date. If the timestamps are equal it
3134 * assumes the update has been seen before and should be ignored.
3137 private static function isEditedTimestampNewer($existing, $update)
3139 if (!x($existing, 'edited') || !$existing['edited']) {
3142 if (!x($update, 'edited') || !$update['edited']) {
3146 $existing_edited = DateTimeFormat::utc($existing['edited']);
3147 $update_edited = DateTimeFormat::utc($update['edited']);
3149 return (strcmp($existing_edited, $update_edited) < 0);