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\Core\Addon;
15 use Friendica\Core\Config;
16 use Friendica\Core\L10n;
17 use Friendica\Core\System;
18 use Friendica\Core\Worker;
19 use Friendica\Database\DBM;
20 use Friendica\Model\Contact;
21 use Friendica\Model\GContact;
22 use Friendica\Model\Group;
23 use Friendica\Model\Item;
24 use Friendica\Model\Profile;
25 use Friendica\Model\Term;
26 use Friendica\Model\User;
27 use Friendica\Object\Image;
28 use Friendica\Protocol\OStatus;
29 use Friendica\Util\Crypto;
30 use Friendica\Util\DateTimeFormat;
31 use Friendica\Util\Network;
32 use Friendica\Util\XML;
37 use HTMLPurifier_Config;
39 require_once 'boot.php';
40 require_once 'include/dba.php';
41 require_once "include/enotify.php";
42 require_once "include/items.php";
43 require_once "include/event.php";
44 require_once "include/text.php";
45 require_once "include/html2bbcode.php";
46 require_once "include/bbcode.php";
49 * @brief This class contain functions to create and send DFRN XML files
54 const DFRN_TOP_LEVEL = 0; // Top level posting
55 const DFRN_REPLY = 1; // Regular reply that is stored locally
56 const DFRN_REPLY_RC = 2; // Reply that will be relayed
59 * @brief Generates the atom entries for delivery.php
61 * This function is used whenever content is transmitted via DFRN.
63 * @param array $items Item elements
64 * @param array $owner Owner record
66 * @return string DFRN entries
67 * @todo Add type-hints
69 public static function entries($items, $owner)
71 $doc = new DOMDocument('1.0', 'utf-8');
72 $doc->formatOutput = true;
74 $root = self::addHeader($doc, $owner, "dfrn:owner", "", false);
76 if (! count($items)) {
77 return trim($doc->saveXML());
80 foreach ($items as $item) {
81 $entry = self::entry($doc, "text", $item, $owner, $item["entry:comment-allow"], $item["entry:cid"]);
82 $root->appendChild($entry);
85 return(trim($doc->saveXML()));
89 * @brief Generate an atom feed for the given user
91 * This function is called when another server is pulling data from the user feed.
93 * @param string $dfrn_id DFRN ID from the requesting party
94 * @param string $owner_nick Owner nick name
95 * @param string $last_update Date of the last update
96 * @param int $direction Can be -1, 0 or 1.
97 * @param boolean $onlyheader Output only the header without content? (Default is "no")
99 * @return string DFRN feed entries
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];
126 // default permissions - anonymous user
128 $sql_extra = " AND `item`.`allow_cid` = '' AND `item`.`allow_gid` = '' AND `item`.`deny_cid` = '' AND `item`.`deny_gid` = '' ";
131 "SELECT `contact`.*, `user`.`nickname`, `user`.`timezone`, `user`.`page-flags`, `user`.`account-type`
132 FROM `contact` INNER JOIN `user` ON `user`.`uid` = `contact`.`uid`
133 WHERE `contact`.`self` AND `user`.`nickname` = '%s' LIMIT 1",
137 if (! DBM::is_result($r)) {
142 $owner_id = $owner['uid'];
143 $owner_nick = $owner['nickname'];
145 $sql_post_table = "";
147 if (! $public_feed) {
149 switch ($direction) {
151 $sql_extra = sprintf(" AND `issued-id` = '%s' ", dbesc($dfrn_id));
155 $sql_extra = sprintf(" AND `issued-id` = '%s' AND `duplex` = 1 ", dbesc($dfrn_id));
156 $my_id = '1:' . $dfrn_id;
159 $sql_extra = sprintf(" AND `dfrn-id` = '%s' AND `duplex` = 1 ", dbesc($dfrn_id));
160 $my_id = '0:' . $dfrn_id;
168 "SELECT * FROM `contact` WHERE NOT `blocked` AND `contact`.`uid` = %d $sql_extra LIMIT 1",
172 if (! DBM::is_result($r)) {
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]) . '>' ;
183 $gs = implode('|', $groups);
185 $gs = '<<>>' ; // Impossible to match
188 $sql_extra = sprintf(
190 AND ( `allow_cid` = '' OR `allow_cid` REGEXP '<%d>' )
191 AND ( `deny_cid` = '' OR NOT `deny_cid` REGEXP '<%d>' )
192 AND ( `allow_gid` = '' OR `allow_gid` REGEXP '%s' )
193 AND ( `deny_gid` = '' OR NOT `deny_gid` REGEXP '%s')
195 intval($contact['id']),
196 intval($contact['id']),
208 if (! strlen($last_update)) {
209 $last_update = 'now -30 days';
212 if (isset($category)) {
213 $sql_post_table = sprintf(
214 "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` ",
215 dbesc(protect_sprintf($category)),
216 intval(TERM_OBJ_POST),
217 intval(TERM_CATEGORY),
220 //$sql_extra .= file_tag_file_query('item',$category,'category');
225 $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 Add 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 Add 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 Add 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']];
493 $doc = new DOMDocument('1.0', 'utf-8');
494 $doc->formatOutput = true;
496 $root = self::addHeader($doc, $owner, "dfrn:owner", "", false);
498 $relocate = $doc->createElement("dfrn:relocate");
500 XML::addElement($doc, $relocate, "dfrn:url", $owner['url']);
501 XML::addElement($doc, $relocate, "dfrn:name", $owner['name']);
502 XML::addElement($doc, $relocate, "dfrn:addr", $owner['addr']);
503 XML::addElement($doc, $relocate, "dfrn:avatar", $owner['avatar']);
504 XML::addElement($doc, $relocate, "dfrn:photo", $photos[4]);
505 XML::addElement($doc, $relocate, "dfrn:thumb", $photos[5]);
506 XML::addElement($doc, $relocate, "dfrn:micro", $photos[6]);
507 XML::addElement($doc, $relocate, "dfrn:request", $owner['request']);
508 XML::addElement($doc, $relocate, "dfrn:confirm", $owner['confirm']);
509 XML::addElement($doc, $relocate, "dfrn:notify", $owner['notify']);
510 XML::addElement($doc, $relocate, "dfrn:poll", $owner['poll']);
511 XML::addElement($doc, $relocate, "dfrn:sitepubkey", Config::get('system', 'site_pubkey'));
513 $root->appendChild($relocate);
515 return(trim($doc->saveXML()));
519 * @brief Adds the header elements for the DFRN protocol
521 * @param object $doc XML document
522 * @param array $owner Owner record
523 * @param string $authorelement Element name for the author
524 * @param string $alternatelink link to profile or category
525 * @param bool $public Is it a header for public posts?
527 * @return object XML root object
528 * @todo Add type-hints
530 private static function addHeader($doc, $owner, $authorelement, $alternatelink = "", $public = false)
533 if ($alternatelink == "") {
534 $alternatelink = $owner['url'];
537 $root = $doc->createElementNS(NAMESPACE_ATOM1, 'feed');
538 $doc->appendChild($root);
540 $root->setAttribute("xmlns:thr", NAMESPACE_THREAD);
541 $root->setAttribute("xmlns:at", NAMESPACE_TOMB);
542 $root->setAttribute("xmlns:media", NAMESPACE_MEDIA);
543 $root->setAttribute("xmlns:dfrn", NAMESPACE_DFRN);
544 $root->setAttribute("xmlns:activity", NAMESPACE_ACTIVITY);
545 $root->setAttribute("xmlns:georss", NAMESPACE_GEORSS);
546 $root->setAttribute("xmlns:poco", NAMESPACE_POCO);
547 $root->setAttribute("xmlns:ostatus", NAMESPACE_OSTATUS);
548 $root->setAttribute("xmlns:statusnet", NAMESPACE_STATUSNET);
550 XML::addElement($doc, $root, "id", System::baseUrl()."/profile/".$owner["nick"]);
551 XML::addElement($doc, $root, "title", $owner["name"]);
553 $attributes = ["uri" => "https://friendi.ca", "version" => FRIENDICA_VERSION."-".DB_UPDATE_VERSION];
554 XML::addElement($doc, $root, "generator", FRIENDICA_PLATFORM, $attributes);
556 $attributes = ["rel" => "license", "href" => "http://creativecommons.org/licenses/by/3.0/"];
557 XML::addElement($doc, $root, "link", "", $attributes);
559 $attributes = ["rel" => "alternate", "type" => "text/html", "href" => $alternatelink];
560 XML::addElement($doc, $root, "link", "", $attributes);
564 // DFRN itself doesn't uses this. But maybe someone else wants to subscribe to the public feed.
565 OStatus::hublinks($doc, $root, $owner["nick"]);
567 $attributes = ["rel" => "salmon", "href" => System::baseUrl()."/salmon/".$owner["nick"]];
568 XML::addElement($doc, $root, "link", "", $attributes);
570 $attributes = ["rel" => "http://salmon-protocol.org/ns/salmon-replies", "href" => System::baseUrl()."/salmon/".$owner["nick"]];
571 XML::addElement($doc, $root, "link", "", $attributes);
573 $attributes = ["rel" => "http://salmon-protocol.org/ns/salmon-mention", "href" => System::baseUrl()."/salmon/".$owner["nick"]];
574 XML::addElement($doc, $root, "link", "", $attributes);
577 // For backward compatibility we keep this element
578 if ($owner['page-flags'] == PAGE_COMMUNITY) {
579 XML::addElement($doc, $root, "dfrn:community", 1);
582 // The former element is replaced by this one
583 XML::addElement($doc, $root, "dfrn:account_type", $owner["account-type"]);
585 /// @todo We need a way to transmit the different page flags like "PAGE_PRVGROUP"
587 XML::addElement($doc, $root, "updated", DateTimeFormat::utcNow(DateTimeFormat::ATOM));
589 $author = self::addAuthor($doc, $owner, $authorelement, $public);
590 $root->appendChild($author);
596 * @brief Adds the author element in the header for the DFRN protocol
598 * @param object $doc XML document
599 * @param array $owner Owner record
600 * @param string $authorelement Element name for the author
601 * @param boolean $public boolean
603 * @return object XML author object
604 * @todo Add type-hints
606 private static function addAuthor($doc, $owner, $authorelement, $public)
608 // Is the profile hidden or shouldn't be published in the net? Then add the "hide" element
610 "SELECT `id` FROM `profile` INNER JOIN `user` ON `user`.`uid` = `profile`.`uid`
611 WHERE (`hidewall` OR NOT `net-publish`) AND `user`.`uid` = %d",
612 intval($owner['uid'])
614 if (DBM::is_result($r)) {
620 $author = $doc->createElement($authorelement);
622 $namdate = DateTimeFormat::utc($owner['name-date'].'+00:00', DateTimeFormat::ATOM);
623 $uridate = DateTimeFormat::utc($owner['uri-date'].'+00:00', DateTimeFormat::ATOM);
624 $picdate = DateTimeFormat::utc($owner['avatar-date'].'+00:00', DateTimeFormat::ATOM);
628 if (!$public || !$hidewall) {
629 $attributes = ["dfrn:updated" => $namdate];
632 XML::addElement($doc, $author, "name", $owner["name"], $attributes);
633 XML::addElement($doc, $author, "uri", System::baseUrl().'/profile/'.$owner["nickname"], $attributes);
634 XML::addElement($doc, $author, "dfrn:handle", $owner["addr"], $attributes);
636 $attributes = ["rel" => "photo", "type" => "image/jpeg",
637 "media:width" => 175, "media:height" => 175, "href" => $owner['photo']];
639 if (!$public || !$hidewall) {
640 $attributes["dfrn:updated"] = $picdate;
643 XML::addElement($doc, $author, "link", "", $attributes);
645 $attributes["rel"] = "avatar";
646 XML::addElement($doc, $author, "link", "", $attributes);
649 XML::addElement($doc, $author, "dfrn:hide", "true");
652 // The following fields will only be generated if the data isn't meant for a public feed
657 $birthday = feed_birthday($owner['uid'], $owner['timezone']);
660 XML::addElement($doc, $author, "dfrn:birthday", $birthday);
663 // Only show contact details when we are allowed to
665 "SELECT `profile`.`about`, `profile`.`name`, `profile`.`homepage`, `user`.`nickname`,
666 `user`.`timezone`, `profile`.`locality`, `profile`.`region`, `profile`.`country-name`,
667 `profile`.`pub_keywords`, `profile`.`xmpp`, `profile`.`dob`
669 INNER JOIN `user` ON `user`.`uid` = `profile`.`uid`
670 WHERE `profile`.`is-default` AND NOT `user`.`hidewall` AND `user`.`uid` = %d",
671 intval($owner['uid'])
673 if (DBM::is_result($r)) {
676 XML::addElement($doc, $author, "poco:displayName", $profile["name"]);
677 XML::addElement($doc, $author, "poco:updated", $namdate);
679 if (trim($profile["dob"]) > '0001-01-01') {
680 XML::addElement($doc, $author, "poco:birthday", "0000-".date("m-d", strtotime($profile["dob"])));
683 XML::addElement($doc, $author, "poco:note", $profile["about"]);
684 XML::addElement($doc, $author, "poco:preferredUsername", $profile["nickname"]);
686 $savetz = date_default_timezone_get();
687 date_default_timezone_set($profile["timezone"]);
688 XML::addElement($doc, $author, "poco:utcOffset", date("P"));
689 date_default_timezone_set($savetz);
691 if (trim($profile["homepage"]) != "") {
692 $urls = $doc->createElement("poco:urls");
693 XML::addElement($doc, $urls, "poco:type", "homepage");
694 XML::addElement($doc, $urls, "poco:value", $profile["homepage"]);
695 XML::addElement($doc, $urls, "poco:primary", "true");
696 $author->appendChild($urls);
699 if (trim($profile["pub_keywords"]) != "") {
700 $keywords = explode(",", $profile["pub_keywords"]);
702 foreach ($keywords as $keyword) {
703 XML::addElement($doc, $author, "poco:tags", trim($keyword));
707 if (trim($profile["xmpp"]) != "") {
708 $ims = $doc->createElement("poco:ims");
709 XML::addElement($doc, $ims, "poco:type", "xmpp");
710 XML::addElement($doc, $ims, "poco:value", $profile["xmpp"]);
711 XML::addElement($doc, $ims, "poco:primary", "true");
712 $author->appendChild($ims);
715 if (trim($profile["locality"].$profile["region"].$profile["country-name"]) != "") {
716 $element = $doc->createElement("poco:address");
718 XML::addElement($doc, $element, "poco:formatted", Profile::formatLocation($profile));
720 if (trim($profile["locality"]) != "") {
721 XML::addElement($doc, $element, "poco:locality", $profile["locality"]);
724 if (trim($profile["region"]) != "") {
725 XML::addElement($doc, $element, "poco:region", $profile["region"]);
728 if (trim($profile["country-name"]) != "") {
729 XML::addElement($doc, $element, "poco:country", $profile["country-name"]);
732 $author->appendChild($element);
740 * @brief Adds the author elements in the "entry" elements of the DFRN protocol
742 * @param object $doc XML document
743 * @param string $element Element name for the author
744 * @param string $contact_url Link of the contact
745 * @param array $item Item elements
747 * @return object XML author object
748 * @todo Add type-hints
750 private static function addEntryAuthor($doc, $element, $contact_url, $item)
752 $contact = Contact::getDetailsByURL($contact_url, $item["uid"]);
754 $author = $doc->createElement($element);
755 XML::addElement($doc, $author, "name", $contact["name"]);
756 XML::addElement($doc, $author, "uri", $contact["url"]);
757 XML::addElement($doc, $author, "dfrn:handle", $contact["addr"]);
760 /// - Check real image type and image size
761 /// - Check which of these boths elements we should use
764 "type" => "image/jpeg",
766 "media:height" => 80,
767 "href" => $contact["photo"]];
768 XML::addElement($doc, $author, "link", "", $attributes);
772 "type" => "image/jpeg",
774 "media:height" => 80,
775 "href" => $contact["photo"]];
776 XML::addElement($doc, $author, "link", "", $attributes);
782 * @brief Adds the activity elements
784 * @param object $doc XML document
785 * @param string $element Element name for the activity
786 * @param string $activity activity value
788 * @return object XML activity object
789 * @todo Add type-hints
791 private static function createActivity($doc, $element, $activity)
794 $entry = $doc->createElement($element);
796 $r = XML::parseString($activity, false);
801 XML::addElement($doc, $entry, "activity:object-type", $r->type);
804 XML::addElement($doc, $entry, "id", $r->id);
807 XML::addElement($doc, $entry, "title", $r->title);
811 if (substr($r->link, 0, 1) == '<') {
812 if (strstr($r->link, '&') && (! strstr($r->link, '&'))) {
813 $r->link = str_replace('&', '&', $r->link);
816 $r->link = preg_replace('/\<link(.*?)\"\>/', '<link$1"/>', $r->link);
818 // XML does need a single element as root element so we add a dummy element here
819 $data = XML::parseString("<dummy>" . $r->link . "</dummy>", false);
820 if (is_object($data)) {
821 foreach ($data->link as $link) {
823 foreach ($link->attributes() as $parameter => $value) {
824 $attributes[$parameter] = $value;
826 XML::addElement($doc, $entry, "link", "", $attributes);
830 $attributes = ["rel" => "alternate", "type" => "text/html", "href" => $r->link];
831 XML::addElement($doc, $entry, "link", "", $attributes);
835 XML::addElement($doc, $entry, "content", bbcode($r->content), ["type" => "html"]);
845 * @brief Adds the elements for attachments
847 * @param object $doc XML document
848 * @param object $root XML root
849 * @param array $item Item element
851 * @return object XML attachment object
852 * @todo Add type-hints
854 private static function getAttachment($doc, $root, $item)
856 $arr = explode('[/attach],', $item['attach']);
858 foreach ($arr as $r) {
860 $cnt = preg_match('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\" title=\"(.*?)\"|', $r, $matches);
862 $attributes = ["rel" => "enclosure",
863 "href" => $matches[1],
864 "type" => $matches[3]];
866 if (intval($matches[2])) {
867 $attributes["length"] = intval($matches[2]);
870 if (trim($matches[4]) != "") {
871 $attributes["title"] = trim($matches[4]);
874 XML::addElement($doc, $root, "link", "", $attributes);
881 * @brief Adds the "entry" elements for the DFRN protocol
883 * @param object $doc XML document
884 * @param string $type "text" or "html"
885 * @param array $item Item element
886 * @param array $owner Owner record
887 * @param bool $comment Trigger the sending of the "comment" element
888 * @param int $cid Contact ID of the recipient
889 * @param bool $single If set, the entry is created as an XML document with a single "entry" element
891 * @return object XML entry object
892 * @todo Add type-hints
894 private static function entry($doc, $type, $item, $owner, $comment = false, $cid = 0, $single = false)
898 if (!$item['parent']) {
902 if ($item['deleted']) {
903 $attributes = ["ref" => $item['uri'], "when" => DateTimeFormat::utc($item['edited'] . '+00:00', DateTimeFormat::ATOM)];
904 return XML::createElement($doc, "at:deleted-entry", "", $attributes);
908 $entry = $doc->createElement("entry");
910 $entry = $doc->createElementNS(NAMESPACE_ATOM1, 'entry');
911 $doc->appendChild($entry);
913 $entry->setAttribute("xmlns:thr", NAMESPACE_THREAD);
914 $entry->setAttribute("xmlns:at", NAMESPACE_TOMB);
915 $entry->setAttribute("xmlns:media", NAMESPACE_MEDIA);
916 $entry->setAttribute("xmlns:dfrn", NAMESPACE_DFRN);
917 $entry->setAttribute("xmlns:activity", NAMESPACE_ACTIVITY);
918 $entry->setAttribute("xmlns:georss", NAMESPACE_GEORSS);
919 $entry->setAttribute("xmlns:poco", NAMESPACE_POCO);
920 $entry->setAttribute("xmlns:ostatus", NAMESPACE_OSTATUS);
921 $entry->setAttribute("xmlns:statusnet", NAMESPACE_STATUSNET);
924 if ($item['allow_cid'] || $item['allow_gid'] || $item['deny_cid'] || $item['deny_gid']) {
925 $body = Item::fixPrivatePhotos($item['body'], $owner['uid'], $item, $cid);
927 $body = $item['body'];
930 // Remove the abstract element. It is only locally important.
931 $body = BBCode::stripAbstract($body);
934 if ($type == 'html') {
937 if ($item['title'] != "") {
938 $htmlbody = "[b]".$item['title']."[/b]\n\n".$htmlbody;
941 $htmlbody = bbcode($htmlbody, false, false, 7);
944 $author = self::addEntryAuthor($doc, "author", $item["author-link"], $item);
945 $entry->appendChild($author);
947 $dfrnowner = self::addEntryAuthor($doc, "dfrn:owner", $item["owner-link"], $item);
948 $entry->appendChild($dfrnowner);
950 if (($item['parent'] != $item['id']) || ($item['parent-uri'] !== $item['uri']) || (($item['thr-parent'] !== '') && ($item['thr-parent'] !== $item['uri']))) {
951 $parent_item = (($item['thr-parent']) ? $item['thr-parent'] : $item['parent-uri']);
952 $parent = q("SELECT `guid`,`plink` FROM `item` WHERE `uri` = '%s' AND `uid` = %d", dbesc($parent_item), intval($item['uid']));
953 $attributes = ["ref" => $parent_item, "type" => "text/html",
954 "href" => $parent[0]['plink'],
955 "dfrn:diaspora_guid" => $parent[0]['guid']];
956 XML::addElement($doc, $entry, "thr:in-reply-to", "", $attributes);
959 // Add conversation data. This is used for OStatus
960 $conversation_href = System::baseUrl()."/display/".$owner["nick"]."/".$item["parent"];
961 $conversation_uri = $conversation_href;
963 if (isset($parent_item)) {
964 $r = dba::fetch_first("SELECT `conversation-uri`, `conversation-href` FROM `conversation` WHERE `item-uri` = ?", $item['parent-uri']);
965 if (DBM::is_result($r)) {
966 if ($r['conversation-uri'] != '') {
967 $conversation_uri = $r['conversation-uri'];
969 if ($r['conversation-href'] != '') {
970 $conversation_href = $r['conversation-href'];
976 "href" => $conversation_href,
977 "ref" => $conversation_uri];
979 XML::addElement($doc, $entry, "ostatus:conversation", $conversation_uri, $attributes);
981 XML::addElement($doc, $entry, "id", $item["uri"]);
982 XML::addElement($doc, $entry, "title", $item["title"]);
984 XML::addElement($doc, $entry, "published", DateTimeFormat::utc($item["created"] . "+00:00", DateTimeFormat::ATOM));
985 XML::addElement($doc, $entry, "updated", DateTimeFormat::utc($item["edited"] . "+00:00", DateTimeFormat::ATOM));
987 // "dfrn:env" is used to read the content
988 XML::addElement($doc, $entry, "dfrn:env", base64url_encode($body, true));
990 // The "content" field is not read by the receiver. We could remove it when the type is "text"
991 // We keep it at the moment, maybe there is some old version that doesn't read "dfrn:env"
992 XML::addElement($doc, $entry, "content", (($type == 'html') ? $htmlbody : $body), ["type" => $type]);
994 // We save this value in "plink". Maybe we should read it from there as well?
1000 ["rel" => "alternate", "type" => "text/html",
1001 "href" => System::baseUrl() . "/display/" . $item["guid"]]
1004 // "comment-allow" is some old fashioned stuff for old Friendica versions.
1005 // It is included in the rewritten code for completeness
1007 XML::addElement($doc, $entry, "dfrn:comment-allow", 1);
1010 if ($item['location']) {
1011 XML::addElement($doc, $entry, "dfrn:location", $item['location']);
1014 if ($item['coord']) {
1015 XML::addElement($doc, $entry, "georss:point", $item['coord']);
1018 if (($item['private']) || strlen($item['allow_cid']) || strlen($item['allow_gid']) || strlen($item['deny_cid']) || strlen($item['deny_gid'])) {
1019 XML::addElement($doc, $entry, "dfrn:private", (($item['private']) ? $item['private'] : 1));
1022 if ($item['extid']) {
1023 XML::addElement($doc, $entry, "dfrn:extid", $item['extid']);
1026 if ($item['bookmark']) {
1027 XML::addElement($doc, $entry, "dfrn:bookmark", "true");
1031 XML::addElement($doc, $entry, "statusnet:notice_info", "", ["local_id" => $item['id'], "source" => $item['app']]);
1034 XML::addElement($doc, $entry, "dfrn:diaspora_guid", $item["guid"]);
1036 // The signed text contains the content in Markdown, the sender handle and the signatur for the content
1037 // It is needed for relayed comments to Diaspora.
1038 if ($item['signed_text']) {
1039 $sign = base64_encode(json_encode(['signed_text' => $item['signed_text'],'signature' => $item['signature'],'signer' => $item['signer']]));
1040 XML::addElement($doc, $entry, "dfrn:diaspora_signature", $sign);
1043 XML::addElement($doc, $entry, "activity:verb", self::constructVerb($item));
1045 if ($item['object-type'] != "") {
1046 XML::addElement($doc, $entry, "activity:object-type", $item['object-type']);
1047 } elseif ($item['id'] == $item['parent']) {
1048 XML::addElement($doc, $entry, "activity:object-type", ACTIVITY_OBJ_NOTE);
1050 XML::addElement($doc, $entry, "activity:object-type", ACTIVITY_OBJ_COMMENT);
1053 $actobj = self::createActivity($doc, "activity:object", $item['object']);
1055 $entry->appendChild($actobj);
1058 $actarg = self::createActivity($doc, "activity:target", $item['target']);
1060 $entry->appendChild($actarg);
1063 $tags = Item::getFeedTags($item);
1066 foreach ($tags as $t) {
1067 if (($type != 'html') || ($t[0] != "@")) {
1068 XML::addElement($doc, $entry, "category", "", ["scheme" => "X-DFRN:".$t[0].":".$t[1], "term" => $t[2]]);
1074 foreach ($tags as $t) {
1076 $mentioned[$t[1]] = $t[1];
1081 foreach ($mentioned as $mention) {
1083 "SELECT `forum`, `prv` FROM `contact` WHERE `uid` = %d AND `nurl` = '%s'",
1084 intval($owner["uid"]),
1085 dbesc(normalise_link($mention))
1088 if (DBM::is_result($r) && ($r[0]["forum"] || $r[0]["prv"])) {
1094 ["rel" => "mentioned",
1095 "ostatus:object-type" => ACTIVITY_OBJ_GROUP,
1104 ["rel" => "mentioned",
1105 "ostatus:object-type" => ACTIVITY_OBJ_PERSON,
1111 self::getAttachment($doc, $entry, $item);
1117 * @brief encrypts data via AES
1119 * @param string $data The data that is to be encrypted
1120 * @param string $key The AES key
1122 * @return string encrypted data
1124 private static function aesEncrypt($data, $key)
1126 return openssl_encrypt($data, 'aes-128-ecb', $key, OPENSSL_RAW_DATA);
1130 * @brief decrypts data via AES
1132 * @param string $encrypted The encrypted data
1133 * @param string $key The AES key
1135 * @return string decrypted data
1137 public static function aesDecrypt($encrypted, $key)
1139 return openssl_decrypt($encrypted, 'aes-128-ecb', $key, OPENSSL_RAW_DATA);
1143 * @brief Delivers the atom content to the contacts
1145 * @param array $owner Owner record
1146 * @param array $contact Contact record of the receiver
1147 * @param string $atom Content that will be transmitted
1148 * @param bool $dissolve (to be documented)
1150 * @return int Deliver status. -1 means an error.
1151 * @todo Add array type-hint for $owner, $contact
1153 public static function deliver($owner, $contact, $atom, $dissolve = false)
1157 $idtosend = $orig_id = (($contact['dfrn-id']) ? $contact['dfrn-id'] : $contact['issued-id']);
1159 if ($contact['duplex'] && $contact['dfrn-id']) {
1160 $idtosend = '0:' . $orig_id;
1162 if ($contact['duplex'] && $contact['issued-id']) {
1163 $idtosend = '1:' . $orig_id;
1166 $rino = Config::get('system', 'rino_encrypt');
1167 $rino = intval($rino);
1169 logger("Local rino version: ". $rino, LOGGER_DEBUG);
1171 $ssl_val = intval(Config::get('system', 'ssl_policy'));
1175 case SSL_POLICY_FULL:
1176 $ssl_policy = 'full';
1178 case SSL_POLICY_SELFSIGN:
1179 $ssl_policy = 'self';
1181 case SSL_POLICY_NONE:
1183 $ssl_policy = 'none';
1187 $url = $contact['notify'] . '&dfrn_id=' . $idtosend . '&dfrn_version=' . DFRN_PROTOCOL_VERSION . (($rino) ? '&rino='.$rino : '');
1189 logger('dfrn_deliver: ' . $url);
1191 $ret = Network::curl($url);
1193 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
1194 return -2; // timed out
1197 $xml = $ret['body'];
1199 $curl_stat = $a->get_curl_code();
1201 return -3; // timed out
1204 logger('dfrn_deliver: ' . $xml, LOGGER_DATA);
1210 if (strpos($xml, '<?xml') === false) {
1211 logger('dfrn_deliver: no valid XML returned');
1212 logger('dfrn_deliver: returned XML: ' . $xml, LOGGER_DATA);
1216 $res = XML::parseString($xml);
1218 if ((intval($res->status) != 0) || (! strlen($res->challenge)) || (! strlen($res->dfrn_id))) {
1219 return (($res->status) ? $res->status : 3);
1223 $sent_dfrn_id = hex2bin((string) $res->dfrn_id);
1224 $challenge = hex2bin((string) $res->challenge);
1225 $perm = (($res->perm) ? $res->perm : null);
1226 $dfrn_version = (float) (($res->dfrn_version) ? $res->dfrn_version : 2.0);
1227 $rino_remote_version = intval($res->rino);
1228 $page = (($owner['page-flags'] == PAGE_COMMUNITY) ? 1 : 0);
1230 logger("Remote rino version: ".$rino_remote_version." for ".$contact["url"], LOGGER_DEBUG);
1232 if ($owner['page-flags'] == PAGE_PRVGROUP) {
1236 $final_dfrn_id = '';
1239 if ((($perm == 'rw') && (! intval($contact['writable'])))
1240 || (($perm == 'r') && (intval($contact['writable'])))
1243 "update contact set writable = %d where id = %d",
1244 intval(($perm == 'rw') ? 1 : 0),
1245 intval($contact['id'])
1247 $contact['writable'] = (string) 1 - intval($contact['writable']);
1251 if (($contact['duplex'] && strlen($contact['pubkey']))
1252 || ($owner['page-flags'] == PAGE_COMMUNITY && strlen($contact['pubkey']))
1253 || ($contact['rel'] == CONTACT_IS_SHARING && strlen($contact['pubkey']))
1255 openssl_public_decrypt($sent_dfrn_id, $final_dfrn_id, $contact['pubkey']);
1256 openssl_public_decrypt($challenge, $postvars['challenge'], $contact['pubkey']);
1258 openssl_private_decrypt($sent_dfrn_id, $final_dfrn_id, $contact['prvkey']);
1259 openssl_private_decrypt($challenge, $postvars['challenge'], $contact['prvkey']);
1262 $final_dfrn_id = substr($final_dfrn_id, 0, strpos($final_dfrn_id, '.'));
1264 if (strpos($final_dfrn_id, ':') == 1) {
1265 $final_dfrn_id = substr($final_dfrn_id, 2);
1268 if ($final_dfrn_id != $orig_id) {
1269 logger('dfrn_deliver: wrong dfrn_id.');
1270 // did not decode properly - cannot trust this site
1274 $postvars['dfrn_id'] = $idtosend;
1275 $postvars['dfrn_version'] = DFRN_PROTOCOL_VERSION;
1277 $postvars['dissolve'] = '1';
1281 if ((($contact['rel']) && ($contact['rel'] != CONTACT_IS_SHARING) && (! $contact['blocked'])) || ($owner['page-flags'] == PAGE_COMMUNITY)) {
1282 $postvars['data'] = $atom;
1283 $postvars['perm'] = 'rw';
1285 $postvars['data'] = str_replace('<dfrn:comment-allow>1', '<dfrn:comment-allow>0', $atom);
1286 $postvars['perm'] = 'r';
1289 $postvars['ssl_policy'] = $ssl_policy;
1292 $postvars['page'] = $page;
1296 if ($rino > 0 && $rino_remote_version > 0 && (! $dissolve)) {
1297 logger('rino version: '. $rino_remote_version);
1299 switch ($rino_remote_version) {
1301 $key = openssl_random_pseudo_bytes(16);
1302 $data = self::aesEncrypt($postvars['data'], $key);
1305 logger("rino: invalid requested version '$rino_remote_version'");
1309 $postvars['rino'] = $rino_remote_version;
1310 $postvars['data'] = bin2hex($data);
1312 if ($dfrn_version >= 2.1) {
1313 if (($contact['duplex'] && strlen($contact['pubkey']))
1314 || ($owner['page-flags'] == PAGE_COMMUNITY && strlen($contact['pubkey']))
1315 || ($contact['rel'] == CONTACT_IS_SHARING && strlen($contact['pubkey']))
1317 openssl_public_encrypt($key, $postvars['key'], $contact['pubkey']);
1319 openssl_private_encrypt($key, $postvars['key'], $contact['prvkey']);
1322 if (($contact['duplex'] && strlen($contact['prvkey'])) || ($owner['page-flags'] == PAGE_COMMUNITY)) {
1323 openssl_private_encrypt($key, $postvars['key'], $contact['prvkey']);
1325 openssl_public_encrypt($key, $postvars['key'], $contact['pubkey']);
1329 logger('md5 rawkey ' . md5($postvars['key']));
1331 $postvars['key'] = bin2hex($postvars['key']);
1335 logger('dfrn_deliver: ' . "SENDING: " . print_r($postvars, true), LOGGER_DATA);
1337 $xml = Network::post($contact['notify'], $postvars);
1339 logger('dfrn_deliver: ' . "RECEIVED: " . $xml, LOGGER_DATA);
1341 $curl_stat = $a->get_curl_code();
1342 if ((!$curl_stat) || (!strlen($xml))) {
1343 return -9; // timed out
1346 if (($curl_stat == 503) && (stristr($a->get_curl_headers(), 'retry-after'))) {
1350 if (strpos($xml, '<?xml') === false) {
1351 logger('dfrn_deliver: phase 2: no valid XML returned');
1352 logger('dfrn_deliver: phase 2: returned XML: ' . $xml, LOGGER_DATA);
1356 if ($contact['term-date'] > NULL_DATE) {
1357 logger("dfrn_deliver: $url back from the dead - removing mark for death");
1358 Contact::unmarkForArchival($contact);
1361 $res = XML::parseString($xml);
1363 if (!isset($res->status)) {
1367 if (!empty($res->message)) {
1368 logger('Delivery returned status '.$res->status.' - '.$res->message, LOGGER_DEBUG);
1371 return intval($res->status);
1375 * @brief Add new birthday event for this person
1377 * @param array $contact Contact record
1378 * @param string $birthday Birthday of the contact
1380 * @todo Add array type-hint for $contact
1382 private static function birthdayEvent($contact, $birthday)
1384 // Check for duplicates
1386 "SELECT `id` FROM `event` WHERE `uid` = %d AND `cid` = %d AND `start` = '%s' AND `type` = '%s' LIMIT 1",
1387 intval($contact["uid"]),
1388 intval($contact["id"]),
1389 dbesc(DateTimeFormat::utc($birthday)),
1393 if (DBM::is_result($r)) {
1397 logger("updating birthday: ".$birthday." for contact ".$contact["id"]);
1399 $bdtext = L10n::t("%s\'s birthday", $contact["name"]);
1400 $bdtext2 = L10n::t("Happy Birthday %s", " [url=".$contact["url"]."]".$contact["name"]."[/url]");
1403 "INSERT INTO `event` (`uid`,`cid`,`created`,`edited`,`start`,`finish`,`summary`,`desc`,`type`)
1404 VALUES ( %d, %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s') ",
1405 intval($contact["uid"]),
1406 intval($contact["id"]),
1407 dbesc(DateTimeFormat::utcNow()),
1408 dbesc(DateTimeFormat::utcNow()),
1409 dbesc(DateTimeFormat::utc($birthday)),
1410 dbesc(DateTimeFormat::utc($birthday . " + 1 day ")),
1418 * @brief Fetch the author data from head or entry items
1420 * @param object $xpath XPath object
1421 * @param object $context In which context should the data be searched
1422 * @param array $importer Record of the importer user mixed with contact of the content
1423 * @param string $element Element name from which the data is fetched
1424 * @param bool $onlyfetch Should the data only be fetched or should it update the contact record as well
1425 * @param string $xml optional, default empty
1427 * @return array Relevant data of the author
1428 * @todo Find good type-hints for all parameter
1430 private static function fetchauthor($xpath, $context, $importer, $element, $onlyfetch, $xml = "")
1433 $author["name"] = $xpath->evaluate($element."/atom:name/text()", $context)->item(0)->nodeValue;
1434 $author["link"] = $xpath->evaluate($element."/atom:uri/text()", $context)->item(0)->nodeValue;
1436 $contact_old = dba::fetch_first("SELECT `id`, `uid`, `url`, `network`, `avatar-date`, `name-date`, `uri-date`, `addr`,
1437 `name`, `nick`, `about`, `location`, `keywords`, `xmpp`, `bdyear`, `bd`, `hidden`, `contact-type`
1438 FROM `contact` WHERE `uid` = ? AND `nurl` = ? AND `network` != ?",
1440 normalise_link($author["link"]),
1444 if (DBM::is_result($contact_old)) {
1445 $author["contact-id"] = $contact_old["id"];
1446 $author["network"] = $contact_old["network"];
1449 logger("Contact ".$author["link"]." wasn't found for user ".$importer["uid"]." XML: ".$xml, LOGGER_DEBUG);
1452 $author["contact-id"] = $importer["id"];
1453 $author["network"] = $importer["network"];
1457 // Until now we aren't serving different sizes - but maybe later
1459 /// @todo check if "avatar" or "photo" would be the best field in the specification
1460 $avatars = $xpath->query($element."/atom:link[@rel='avatar']", $context);
1461 foreach ($avatars as $avatar) {
1464 foreach ($avatar->attributes as $attributes) {
1465 /// @TODO Rewrite these similar if () to one switch
1466 if ($attributes->name == "href") {
1467 $href = $attributes->textContent;
1469 if ($attributes->name == "width") {
1470 $width = $attributes->textContent;
1472 if ($attributes->name == "updated") {
1473 $contact_old["avatar-date"] = $attributes->textContent;
1476 if (($width > 0) && ($href != "")) {
1477 $avatarlist[$width] = $href;
1480 if (count($avatarlist) > 0) {
1481 krsort($avatarlist);
1482 $author["avatar"] = current($avatarlist);
1485 if (DBM::is_result($contact_old) && !$onlyfetch) {
1486 logger("Check if contact details for contact " . $contact_old["id"] . " (" . $contact_old["nick"] . ") have to be updated.", LOGGER_DEBUG);
1488 $poco = ["url" => $contact_old["url"]];
1490 // When was the last change to name or uri?
1491 $name_element = $xpath->query($element . "/atom:name", $context)->item(0);
1492 foreach ($name_element->attributes as $attributes) {
1493 if ($attributes->name == "updated") {
1494 $poco["name-date"] = $attributes->textContent;
1498 $link_element = $xpath->query($element . "/atom:link", $context)->item(0);
1499 foreach ($link_element->attributes as $attributes) {
1500 if ($attributes->name == "updated") {
1501 $poco["uri-date"] = $attributes->textContent;
1505 // Update contact data
1506 $value = $xpath->evaluate($element . "/dfrn:handle/text()", $context)->item(0)->nodeValue;
1508 $poco["addr"] = $value;
1511 $value = $xpath->evaluate($element . "/poco:displayName/text()", $context)->item(0)->nodeValue;
1513 $poco["name"] = $value;
1516 $value = $xpath->evaluate($element . "/poco:preferredUsername/text()", $context)->item(0)->nodeValue;
1518 $poco["nick"] = $value;
1521 $value = $xpath->evaluate($element . "/poco:note/text()", $context)->item(0)->nodeValue;
1523 $poco["about"] = $value;
1526 $value = $xpath->evaluate($element . "/poco:address/poco:formatted/text()", $context)->item(0)->nodeValue;
1528 $poco["location"] = $value;
1531 /// @todo Only search for elements with "poco:type" = "xmpp"
1532 $value = $xpath->evaluate($element . "/poco:ims/poco:value/text()", $context)->item(0)->nodeValue;
1534 $poco["xmpp"] = $value;
1537 /// @todo Add support for the following fields that we don't support by now in the contact table:
1538 /// - poco:utcOffset
1544 // If the "hide" element is present then the profile isn't searchable.
1545 $hide = intval($xpath->evaluate($element . "/dfrn:hide/text()", $context)->item(0)->nodeValue == "true");
1547 logger("Hidden status for contact " . $contact_old["url"] . ": " . $hide, LOGGER_DEBUG);
1549 // If the contact isn't searchable then set the contact to "hidden".
1550 // Problem: This can be manually overridden by the user.
1552 $contact_old["hidden"] = true;
1555 // Save the keywords into the contact table
1557 $tagelements = $xpath->evaluate($element . "/poco:tags/text()", $context);
1558 foreach ($tagelements as $tag) {
1559 $tags[$tag->nodeValue] = $tag->nodeValue;
1563 $poco["keywords"] = implode(", ", $tags);
1566 // "dfrn:birthday" contains the birthday converted to UTC
1567 $birthday = $xpath->evaluate($element . "/dfrn:birthday/text()", $context)->item(0)->nodeValue;
1569 if (strtotime($birthday) > time()) {
1570 $bd_timestamp = strtotime($birthday);
1572 $poco["bdyear"] = date("Y", $bd_timestamp);
1575 // "poco:birthday" is the birthday in the format "yyyy-mm-dd"
1576 $value = $xpath->evaluate($element . "/poco:birthday/text()", $context)->item(0)->nodeValue;
1578 if (!in_array($value, ["", "0000-00-00", "0001-01-01"])) {
1579 $bdyear = date("Y");
1580 $value = str_replace("0000", $bdyear, $value);
1582 if (strtotime($value) < time()) {
1583 $value = str_replace($bdyear, $bdyear + 1, $value);
1584 $bdyear = $bdyear + 1;
1587 $poco["bd"] = $value;
1590 $contact = array_merge($contact_old, $poco);
1592 if ($contact_old["bdyear"] != $contact["bdyear"]) {
1593 self::birthdayEvent($contact, $birthday);
1596 // Get all field names
1598 foreach ($contact_old as $field => $data) {
1599 $fields[$field] = $data;
1602 unset($fields["id"]);
1603 unset($fields["uid"]);
1604 unset($fields["url"]);
1605 unset($fields["avatar-date"]);
1606 unset($fields["name-date"]);
1607 unset($fields["uri-date"]);
1610 // Update check for this field has to be done differently
1611 $datefields = ["name-date", "uri-date"];
1612 foreach ($datefields as $field) {
1613 if (strtotime($contact[$field]) > strtotime($contact_old[$field])) {
1614 logger("Difference for contact " . $contact["id"] . " in field '" . $field . "'. New value: '" . $contact[$field] . "', old value '" . $contact_old[$field] . "'", LOGGER_DEBUG);
1619 foreach ($fields as $field => $data) {
1620 if ($contact[$field] != $contact_old[$field]) {
1621 logger("Difference for contact " . $contact["id"] . " in field '" . $field . "'. New value: '" . $contact[$field] . "', old value '" . $contact_old[$field] . "'", LOGGER_DEBUG);
1627 logger("Update contact data for contact " . $contact["id"] . " (" . $contact["nick"] . ")", LOGGER_DEBUG);
1630 "UPDATE `contact` SET `name` = '%s', `nick` = '%s', `about` = '%s', `location` = '%s',
1631 `addr` = '%s', `keywords` = '%s', `bdyear` = '%s', `bd` = '%s', `hidden` = %d,
1632 `xmpp` = '%s', `name-date` = '%s', `uri-date` = '%s'
1633 WHERE `id` = %d AND `network` = '%s'",
1634 dbesc($contact["name"]), dbesc($contact["nick"]), dbesc($contact["about"]), dbesc($contact["location"]),
1635 dbesc($contact["addr"]), dbesc($contact["keywords"]), dbesc($contact["bdyear"]),
1636 dbesc($contact["bd"]), intval($contact["hidden"]), dbesc($contact["xmpp"]),
1637 dbesc(DBM::date($contact["name-date"])), dbesc(DBM::date($contact["uri-date"])),
1638 intval($contact["id"]), dbesc($contact["network"])
1642 Contact::updateAvatar(
1646 (strtotime($contact["avatar-date"]) > strtotime($contact_old["avatar-date"]))
1650 * The generation is a sign for the reliability of the provided data.
1651 * It is used in the socgraph.php to prevent that old contact data
1652 * that was relayed over several servers can overwrite contact
1653 * data that we received directly.
1656 $poco["generation"] = 2;
1657 $poco["photo"] = $author["avatar"];
1658 $poco["hide"] = $hide;
1659 $poco["contact-type"] = $contact["contact-type"];
1660 $gcid = GContact::update($poco);
1662 GContact::link($gcid, $importer["uid"], $contact["id"]);
1669 * @brief Transforms activity objects into an XML string
1671 * @param object $xpath XPath object
1672 * @param object $activity Activity object
1673 * @param string $element element name
1675 * @return string XML string
1676 * @todo Find good type-hints for all parameter
1678 private static function transformActivity($xpath, $activity, $element)
1680 if (!is_object($activity)) {
1684 $obj_doc = new DOMDocument("1.0", "utf-8");
1685 $obj_doc->formatOutput = true;
1687 $obj_element = $obj_doc->createElementNS(NAMESPACE_ATOM1, $element);
1689 $activity_type = $xpath->query("activity:object-type/text()", $activity)->item(0)->nodeValue;
1690 XML::addElement($obj_doc, $obj_element, "type", $activity_type);
1692 $id = $xpath->query("atom:id", $activity)->item(0);
1693 if (is_object($id)) {
1694 $obj_element->appendChild($obj_doc->importNode($id, true));
1697 $title = $xpath->query("atom:title", $activity)->item(0);
1698 if (is_object($title)) {
1699 $obj_element->appendChild($obj_doc->importNode($title, true));
1702 $links = $xpath->query("atom:link", $activity);
1703 if (is_object($links)) {
1704 foreach ($links as $link) {
1705 $obj_element->appendChild($obj_doc->importNode($link, true));
1709 $content = $xpath->query("atom:content", $activity)->item(0);
1710 if (is_object($content)) {
1711 $obj_element->appendChild($obj_doc->importNode($content, true));
1714 $obj_doc->appendChild($obj_element);
1716 $objxml = $obj_doc->saveXML($obj_element);
1718 /// @todo This isn't totally clean. We should find a way to transform the namespaces
1719 $objxml = str_replace("<".$element.' xmlns="http://www.w3.org/2005/Atom">', "<".$element.">", $objxml);
1724 * @brief Processes the mail elements
1726 * @param object $xpath XPath object
1727 * @param object $mail mail elements
1728 * @param array $importer Record of the importer user mixed with contact of the content
1730 * @todo Find good type-hints for all parameter
1732 private static function processMail($xpath, $mail, $importer)
1734 logger("Processing mails");
1736 /// @TODO Rewrite this to one statement
1738 $msg["uid"] = $importer["importer_uid"];
1739 $msg["from-name"] = $xpath->query("dfrn:sender/dfrn:name/text()", $mail)->item(0)->nodeValue;
1740 $msg["from-url"] = $xpath->query("dfrn:sender/dfrn:uri/text()", $mail)->item(0)->nodeValue;
1741 $msg["from-photo"] = $xpath->query("dfrn:sender/dfrn:avatar/text()", $mail)->item(0)->nodeValue;
1742 $msg["contact-id"] = $importer["id"];
1743 $msg["uri"] = $xpath->query("dfrn:id/text()", $mail)->item(0)->nodeValue;
1744 $msg["parent-uri"] = $xpath->query("dfrn:in-reply-to/text()", $mail)->item(0)->nodeValue;
1745 $msg["created"] = $xpath->query("dfrn:sentdate/text()", $mail)->item(0)->nodeValue;
1746 $msg["title"] = $xpath->query("dfrn:subject/text()", $mail)->item(0)->nodeValue;
1747 $msg["body"] = $xpath->query("dfrn:content/text()", $mail)->item(0)->nodeValue;
1749 $msg["replied"] = 0;
1751 dba::insert('mail', $msg);
1753 // send notifications.
1754 /// @TODO Arange this mess
1756 "type" => NOTIFY_MAIL,
1757 "notify_flags" => $importer["notify-flags"],
1758 "language" => $importer["language"],
1759 "to_name" => $importer["username"],
1760 "to_email" => $importer["email"],
1761 "uid" => $importer["importer_uid"],
1763 "source_name" => $msg["from-name"],
1764 "source_link" => $importer["url"],
1765 "source_photo" => $importer["thumb"],
1766 "verb" => ACTIVITY_POST,
1770 notification($notif_params);
1772 logger("Mail is processed, notification was sent.");
1776 * @brief Processes the suggestion elements
1778 * @param object $xpath XPath object
1779 * @param object $suggestion suggestion elements
1780 * @param array $importer Record of the importer user mixed with contact of the content
1782 * @todo Find good type-hints for all parameter
1784 private static function processSuggestion($xpath, $suggestion, $importer)
1788 logger("Processing suggestions");
1790 /// @TODO Rewrite this to one statement
1792 $suggest["uid"] = $importer["importer_uid"];
1793 $suggest["cid"] = $importer["id"];
1794 $suggest["url"] = $xpath->query("dfrn:url/text()", $suggestion)->item(0)->nodeValue;
1795 $suggest["name"] = $xpath->query("dfrn:name/text()", $suggestion)->item(0)->nodeValue;
1796 $suggest["photo"] = $xpath->query("dfrn:photo/text()", $suggestion)->item(0)->nodeValue;
1797 $suggest["request"] = $xpath->query("dfrn:request/text()", $suggestion)->item(0)->nodeValue;
1798 $suggest["body"] = $xpath->query("dfrn:note/text()", $suggestion)->item(0)->nodeValue;
1800 // Does our member already have a friend matching this description?
1803 "SELECT `id` FROM `contact` WHERE `name` = '%s' AND `nurl` = '%s' AND `uid` = %d LIMIT 1",
1804 dbesc($suggest["name"]),
1805 dbesc(normalise_link($suggest["url"])),
1806 intval($suggest["uid"])
1810 * The valid result means the friend we're about to send a friend
1811 * suggestion already has them in their contact, which means no further
1812 * action is required.
1814 * @see https://github.com/friendica/friendica/pull/3254#discussion_r107315246
1816 if (DBM::is_result($r)) {
1820 // Do we already have an fcontact record for this person?
1824 "SELECT `id` FROM `fcontact` WHERE `url` = '%s' AND `name` = '%s' AND `request` = '%s' LIMIT 1",
1825 dbesc($suggest["url"]),
1826 dbesc($suggest["name"]),
1827 dbesc($suggest["request"])
1829 if (DBM::is_result($r)) {
1832 // OK, we do. Do we already have an introduction for this person ?
1834 "SELECT `id` FROM `intro` WHERE `uid` = %d AND `fid` = %d LIMIT 1",
1835 intval($suggest["uid"]),
1840 * The valid result means the friend we're about to send a friend
1841 * suggestion already has them in their contact, which means no further
1842 * action is required.
1844 * @see https://github.com/friendica/friendica/pull/3254#discussion_r107315246
1846 if (DBM::is_result($r)) {
1852 "INSERT INTO `fcontact` (`name`,`url`,`photo`,`request`) VALUES ('%s', '%s', '%s', '%s')",
1853 dbesc($suggest["name"]),
1854 dbesc($suggest["url"]),
1855 dbesc($suggest["photo"]),
1856 dbesc($suggest["request"])
1860 "SELECT `id` FROM `fcontact` WHERE `url` = '%s' AND `name` = '%s' AND `request` = '%s' LIMIT 1",
1861 dbesc($suggest["url"]),
1862 dbesc($suggest["name"]),
1863 dbesc($suggest["request"])
1867 * If no record in fcontact is found, below INSERT statement will not
1868 * link an introduction to it.
1870 if (!DBM::is_result($r)) {
1871 // database record did not get created. Quietly give up.
1877 $hash = random_string();
1880 "INSERT INTO `intro` (`uid`, `fid`, `contact-id`, `note`, `hash`, `datetime`, `blocked`)
1881 VALUES(%d, %d, %d, '%s', '%s', '%s', %d)",
1882 intval($suggest["uid"]),
1884 intval($suggest["cid"]),
1885 dbesc($suggest["body"]),
1887 dbesc(DateTimeFormat::utcNow()),
1893 "type" => NOTIFY_SUGGEST,
1894 "notify_flags" => $importer["notify-flags"],
1895 "language" => $importer["language"],
1896 "to_name" => $importer["username"],
1897 "to_email" => $importer["email"],
1898 "uid" => $importer["importer_uid"],
1900 "link" => System::baseUrl()."/notifications/intros",
1901 "source_name" => $importer["name"],
1902 "source_link" => $importer["url"],
1903 "source_photo" => $importer["photo"],
1904 "verb" => ACTIVITY_REQ_FRIEND,
1912 * @brief Processes the relocation elements
1914 * @param object $xpath XPath object
1915 * @param object $relocation relocation elements
1916 * @param array $importer Record of the importer user mixed with contact of the content
1918 * @todo Find good type-hints for all parameter
1920 private static function processRelocation($xpath, $relocation, $importer)
1922 logger("Processing relocations");
1924 /// @TODO Rewrite this to one statement
1926 $relocate["uid"] = $importer["importer_uid"];
1927 $relocate["cid"] = $importer["id"];
1928 $relocate["url"] = $xpath->query("dfrn:url/text()", $relocation)->item(0)->nodeValue;
1929 $relocate["addr"] = $xpath->query("dfrn:addr/text()", $relocation)->item(0)->nodeValue;
1930 $relocate["name"] = $xpath->query("dfrn:name/text()", $relocation)->item(0)->nodeValue;
1931 $relocate["avatar"] = $xpath->query("dfrn:avatar/text()", $relocation)->item(0)->nodeValue;
1932 $relocate["photo"] = $xpath->query("dfrn:photo/text()", $relocation)->item(0)->nodeValue;
1933 $relocate["thumb"] = $xpath->query("dfrn:thumb/text()", $relocation)->item(0)->nodeValue;
1934 $relocate["micro"] = $xpath->query("dfrn:micro/text()", $relocation)->item(0)->nodeValue;
1935 $relocate["request"] = $xpath->query("dfrn:request/text()", $relocation)->item(0)->nodeValue;
1936 $relocate["confirm"] = $xpath->query("dfrn:confirm/text()", $relocation)->item(0)->nodeValue;
1937 $relocate["notify"] = $xpath->query("dfrn:notify/text()", $relocation)->item(0)->nodeValue;
1938 $relocate["poll"] = $xpath->query("dfrn:poll/text()", $relocation)->item(0)->nodeValue;
1939 $relocate["sitepubkey"] = $xpath->query("dfrn:sitepubkey/text()", $relocation)->item(0)->nodeValue;
1941 if (($relocate["avatar"] == "") && ($relocate["photo"] != "")) {
1942 $relocate["avatar"] = $relocate["photo"];
1945 if ($relocate["addr"] == "") {
1946 $relocate["addr"] = preg_replace("=(https?://)(.*)/profile/(.*)=ism", "$3@$2", $relocate["url"]);
1951 "SELECT `photo`, `url` FROM `contact` WHERE `id` = %d AND `uid` = %d;",
1952 intval($importer["id"]),
1953 intval($importer["importer_uid"])
1956 if (!DBM::is_result($r)) {
1957 logger("Query failed to execute, no result returned in " . __FUNCTION__);
1963 // Update the gcontact entry
1964 $relocate["server_url"] = preg_replace("=(https?://)(.*)/profile/(.*)=ism", "$1$2", $relocate["url"]);
1967 "UPDATE `gcontact` SET
1976 WHERE `nurl` = '%s';",
1977 dbesc($relocate["name"]),
1978 dbesc($relocate["avatar"]),
1979 dbesc($relocate["url"]),
1980 dbesc(normalise_link($relocate["url"])),
1981 dbesc($relocate["addr"]),
1982 dbesc($relocate["addr"]),
1983 dbesc($relocate["notify"]),
1984 dbesc($relocate["server_url"]),
1985 dbesc(normalise_link($old["url"]))
1988 // Update the contact table. We try to find every entry.
1990 "UPDATE `contact` SET
2000 `site-pubkey` = '%s'
2001 WHERE (`id` = %d AND `uid` = %d) OR (`nurl` = '%s');",
2002 dbesc($relocate["name"]),
2003 dbesc($relocate["avatar"]),
2004 dbesc($relocate["url"]),
2005 dbesc(normalise_link($relocate["url"])),
2006 dbesc($relocate["addr"]),
2007 dbesc($relocate["request"]),
2008 dbesc($relocate["confirm"]),
2009 dbesc($relocate["notify"]),
2010 dbesc($relocate["poll"]),
2011 dbesc($relocate["sitepubkey"]),
2012 intval($importer["id"]),
2013 intval($importer["importer_uid"]),
2014 dbesc(normalise_link($old["url"]))
2017 Contact::updateAvatar($relocate["avatar"], $importer["importer_uid"], $importer["id"], true);
2024 /// @todo This is an extreme performance killer
2026 'owner-link' => [$old["url"], $relocate["url"]],
2027 'author-link' => [$old["url"], $relocate["url"]],
2028 //'owner-avatar' => array($old["photo"], $relocate["photo"]),
2029 //'author-avatar' => array($old["photo"], $relocate["photo"]),
2031 foreach ($fields as $n => $f) {
2033 "SELECT `id` FROM `item` WHERE `%s` = '%s' AND `uid` = %d LIMIT 1",
2036 intval($importer["importer_uid"])
2039 if (DBM::is_result($r)) {
2041 "UPDATE `item` SET `%s` = '%s' WHERE `%s` = '%s' AND `uid` = %d",
2046 intval($importer["importer_uid"])
2056 /// merge with current record, current contents have priority
2057 /// update record, set url-updated
2058 /// update profile photos
2059 /// schedule a scan?
2064 * @brief Updates an item
2066 * @param array $current the current item record
2067 * @param array $item the new item record
2068 * @param array $importer Record of the importer user mixed with contact of the content
2069 * @param int $entrytype Is it a toplevel entry, a comment or a relayed comment?
2071 * @todo set proper type-hints (array?)
2073 private static function updateContent($current, $item, $importer, $entrytype)
2077 if (self::isEditedTimestampNewer($current, $item)) {
2078 // do not accept (ignore) an earlier edit than one we currently have.
2079 if (DateTimeFormat::utc($item["edited"]) < $current["edited"]) {
2083 $fields = ['title' => $item["title"], 'body' => $item["body"],
2084 'tag' => $item["tag"], 'changed' => DateTimeFormat::utcNow(),
2085 'edited' => DateTimeFormat::utc($item["edited"])];
2087 $condition = ["`uri` = ? AND `uid` IN (0, ?)", $item["uri"], $importer["importer_uid"]];
2088 Item::update($fields, $condition);
2092 if ($entrytype == DFRN_REPLY_RC) {
2093 Worker::add(PRIORITY_HIGH, "Notifier", "comment-import", $current["id"]);
2100 * @brief Detects the entry type of the item
2102 * @param array $importer Record of the importer user mixed with contact of the content
2103 * @param array $item the new item record
2105 * @return int Is it a toplevel entry, a comment or a relayed comment?
2106 * @todo set proper type-hints (array?)
2108 private static function getEntryType($importer, $item)
2110 if ($item["parent-uri"] != $item["uri"]) {
2113 if ($importer["page-flags"] == PAGE_COMMUNITY || $importer["page-flags"] == PAGE_PRVGROUP) {
2116 logger("possible community action");
2118 $sql_extra = " AND `contact`.`self` AND `item`.`wall` ";
2121 // was the top-level post for this action written by somebody on this site?
2122 // Specifically, the recipient?
2124 $is_a_remote_action = false;
2127 "SELECT `item`.`parent-uri` FROM `item`
2128 WHERE `item`.`uri` = '%s'
2130 dbesc($item["parent-uri"])
2132 if (DBM::is_result($r)) {
2134 "SELECT `item`.`forum_mode`, `item`.`wall` FROM `item`
2135 INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
2136 WHERE `item`.`uri` = '%s' AND (`item`.`parent-uri` = '%s' OR `item`.`thr-parent` = '%s')
2137 AND `item`.`uid` = %d
2140 dbesc($r[0]["parent-uri"]),
2141 dbesc($r[0]["parent-uri"]),
2142 dbesc($r[0]["parent-uri"]),
2143 intval($importer["importer_uid"])
2145 if (DBM::is_result($r)) {
2146 $is_a_remote_action = true;
2151 * Does this have the characteristics of a community or private group action?
2152 * If it's an action to a wall post on a community/prvgroup page it's a
2153 * valid community action. Also forum_mode makes it valid for sure.
2154 * If neither, it's not.
2156 if ($is_a_remote_action && $community && (!$r[0]["forum_mode"]) && (!$r[0]["wall"])) {
2157 $is_a_remote_action = false;
2158 logger("not a community action");
2161 if ($is_a_remote_action) {
2162 return DFRN_REPLY_RC;
2167 return DFRN_TOP_LEVEL;
2172 * @brief Send a "poke"
2174 * @param array $item the new item record
2175 * @param array $importer Record of the importer user mixed with contact of the content
2176 * @param int $posted_id The record number of item record that was just posted
2178 * @todo set proper type-hints (array?)
2180 private static function doPoke($item, $importer, $posted_id)
2182 $verb = urldecode(substr($item["verb"], strpos($item["verb"], "#")+1));
2186 $xo = XML::parseString($item["object"], false);
2188 if (($xo->type == ACTIVITY_OBJ_PERSON) && ($xo->id)) {
2189 // somebody was poked/prodded. Was it me?
2190 foreach ($xo->link as $l) {
2191 $atts = $l->attributes();
2192 switch ($atts["rel"]) {
2194 $Blink = $atts["href"];
2201 if ($Blink && link_compare($Blink, System::baseUrl() . "/profile/" . $importer["nickname"])) {
2202 // send a notification
2205 "type" => NOTIFY_POKE,
2206 "notify_flags" => $importer["notify-flags"],
2207 "language" => $importer["language"],
2208 "to_name" => $importer["username"],
2209 "to_email" => $importer["email"],
2210 "uid" => $importer["importer_uid"],
2212 "link" => System::baseUrl()."/display/".urlencode(Item::getGuidById($posted_id)),
2213 "source_name" => stripslashes($item["author-name"]),
2214 "source_link" => $item["author-link"],
2215 "source_photo" => ((link_compare($item["author-link"], $importer["url"]))
2216 ? $importer["thumb"] : $item["author-avatar"]),
2217 "verb" => $item["verb"],
2218 "otype" => "person",
2219 "activity" => $verb,
2220 "parent" => $item["parent"]]
2227 * @brief Processes several actions, depending on the verb
2229 * @param int $entrytype Is it a toplevel entry, a comment or a relayed comment?
2230 * @param array $importer Record of the importer user mixed with contact of the content
2231 * @param array $item the new item record
2232 * @param bool $is_like Is the verb a "like"?
2234 * @return bool Should the processing of the entries be continued?
2235 * @todo set proper type-hints (array?)
2237 private static function processVerbs($entrytype, $importer, &$item, &$is_like)
2239 logger("Process verb ".$item["verb"]." and object-type ".$item["object-type"]." for entrytype ".$entrytype, LOGGER_DEBUG);
2241 if (($entrytype == DFRN_TOP_LEVEL)) {
2242 // The filling of the the "contact" variable is done for legcy reasons
2243 // The functions below are partly used by ostatus.php as well - where we have this variable
2244 $r = q("SELECT * FROM `contact` WHERE `id` = %d", intval($importer["id"]));
2246 $nickname = $contact["nick"];
2248 // Big question: Do we need these functions? They were part of the "consume_feed" function.
2249 // This function once was responsible for DFRN and OStatus.
2250 if (activity_match($item["verb"], ACTIVITY_FOLLOW)) {
2251 logger("New follower");
2252 Contact::addRelationship($importer, $contact, $item, $nickname);
2255 if (activity_match($item["verb"], ACTIVITY_UNFOLLOW)) {
2256 logger("Lost follower");
2257 Contact::removeFollower($importer, $contact, $item);
2260 if (activity_match($item["verb"], ACTIVITY_REQ_FRIEND)) {
2261 logger("New friend request");
2262 Contact::addRelationship($importer, $contact, $item, $nickname, true);
2265 if (activity_match($item["verb"], ACTIVITY_UNFRIEND)) {
2266 logger("Lost sharer");
2267 Contact::removeSharer($importer, $contact, $item);
2271 if (($item["verb"] == ACTIVITY_LIKE)
2272 || ($item["verb"] == ACTIVITY_DISLIKE)
2273 || ($item["verb"] == ACTIVITY_ATTEND)
2274 || ($item["verb"] == ACTIVITY_ATTENDNO)
2275 || ($item["verb"] == ACTIVITY_ATTENDMAYBE)
2278 $item["type"] = "activity";
2279 $item["gravity"] = GRAVITY_LIKE;
2280 // only one like or dislike per person
2281 // splitted into two queries for performance issues
2283 "SELECT `id` FROM `item` WHERE `uid` = %d AND `author-link` = '%s' AND `verb` = '%s' AND `parent-uri` = '%s' AND NOT `deleted` LIMIT 1",
2284 intval($item["uid"]),
2285 dbesc($item["author-link"]),
2286 dbesc($item["verb"]),
2287 dbesc($item["parent-uri"])
2289 if (DBM::is_result($r)) {
2294 "SELECT `id` FROM `item` WHERE `uid` = %d AND `author-link` = '%s' AND `verb` = '%s' AND `thr-parent` = '%s' AND NOT `deleted` LIMIT 1",
2295 intval($item["uid"]),
2296 dbesc($item["author-link"]),
2297 dbesc($item["verb"]),
2298 dbesc($item["parent-uri"])
2300 if (DBM::is_result($r)) {
2307 if (($item["verb"] == ACTIVITY_TAG) && ($item["object-type"] == ACTIVITY_OBJ_TAGTERM)) {
2308 $xo = XML::parseString($item["object"], false);
2309 $xt = XML::parseString($item["target"], false);
2311 if ($xt->type == ACTIVITY_OBJ_NOTE) {
2313 "SELECT `id`, `tag` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2315 intval($importer["importer_uid"])
2318 if (!DBM::is_result($r)) {
2319 logger("Query failed to execute, no result returned in " . __FUNCTION__);
2323 // extract tag, if not duplicate, add to parent item
2325 if (!stristr($r[0]["tag"], trim($xo->content))) {
2326 $tag = $r[0]["tag"] . (strlen($r[0]["tag"]) ? ',' : '') . '#[url=' . $xo->id . ']'. $xo->content . '[/url]';
2327 Item::update(['tag' => $tag], ['id' => $r[0]["id"]]);
2337 * @brief Processes the link elements
2339 * @param object $links link elements
2340 * @param array $item the item record
2342 * @todo set proper type-hints
2344 private static function parseLinks($links, &$item)
2351 foreach ($links as $link) {
2352 foreach ($link->attributes as $attributes) {
2353 switch ($attributes->name) {
2354 case "href" : $href = $attributes->textContent; break;
2355 case "rel" : $rel = $attributes->textContent; break;
2356 case "type" : $type = $attributes->textContent; break;
2357 case "length": $length = $attributes->textContent; break;
2358 case "title" : $title = $attributes->textContent; break;
2361 if (($rel != "") && ($href != "")) {
2364 $item["plink"] = $href;
2368 if (strlen($item["attach"])) {
2369 $item["attach"] .= ",";
2372 $item["attach"] .= '[attach]href="' . $href . '" length="' . $length . '" type="' . $type . '" title="' . $title . '"[/attach]';
2380 * @brief Processes the entry elements which contain the items and comments
2382 * @param array $header Array of the header elements that always stay the same
2383 * @param object $xpath XPath object
2384 * @param object $entry entry elements
2385 * @param array $importer Record of the importer user mixed with contact of the content
2386 * @param object $xml xml
2388 * @todo Add type-hints
2390 private static function processEntry($header, $xpath, $entry, $importer, $xml)
2392 logger("Processing entries");
2396 $item["protocol"] = PROTOCOL_DFRN;
2398 $item["source"] = $xml;
2401 $item["uri"] = $xpath->query("atom:id/text()", $entry)->item(0)->nodeValue;
2403 $item["edited"] = $xpath->query("atom:updated/text()", $entry)->item(0)->nodeValue;
2405 $current = dba::selectFirst('item',
2406 ['id', 'uid', 'edited', 'body'],
2407 ['uri' => $item["uri"], 'uid' => $importer["importer_uid"]]
2409 // Is there an existing item?
2410 if (DBM::is_result($current) && !self::isEditedTimestampNewer($current, $item)) {
2411 logger("Item ".$item["uri"]." (".$item['edited'].") already existed.", LOGGER_DEBUG);
2416 $owner = self::fetchauthor($xpath, $entry, $importer, "dfrn:owner", true);
2418 $item["owner-name"] = $owner["name"];
2419 $item["owner-link"] = $owner["link"];
2420 $item["owner-avatar"] = $owner["avatar"];
2423 $author = self::fetchauthor($xpath, $entry, $importer, "atom:author", true);
2425 $item["author-name"] = $author["name"];
2426 $item["author-link"] = $author["link"];
2427 $item["author-avatar"] = $author["avatar"];
2429 $item["title"] = $xpath->query("atom:title/text()", $entry)->item(0)->nodeValue;
2431 $item["created"] = $xpath->query("atom:published/text()", $entry)->item(0)->nodeValue;
2433 $item["body"] = $xpath->query("dfrn:env/text()", $entry)->item(0)->nodeValue;
2434 $item["body"] = str_replace([' ',"\t","\r","\n"], ['','','',''], $item["body"]);
2435 // make sure nobody is trying to sneak some html tags by us
2436 $item["body"] = notags(base64url_decode($item["body"]));
2438 $item["body"] = BBCode::limitBodySize($item["body"]);
2440 /// @todo Do we really need this check for HTML elements? (It was copied from the old function)
2441 if ((strpos($item['body'], '<') !== false) && (strpos($item['body'], '>') !== false)) {
2442 $base_url = get_app()->get_baseurl();
2443 $item['body'] = reltoabs($item['body'], $base_url);
2445 $item['body'] = html2bb_video($item['body']);
2447 $item['body'] = OEmbed::HTML2BBCode($item['body']);
2449 $config = HTMLPurifier_Config::createDefault();
2450 $config->set('Cache.DefinitionImpl', null);
2452 // we shouldn't need a whitelist, because the bbcode converter
2453 // will strip out any unsupported tags.
2455 $purifier = new HTMLPurifier($config);
2456 $item['body'] = $purifier->purify($item['body']);
2458 $item['body'] = @html2bbcode($item['body']);
2461 /// @todo We should check for a repeated post and if we know the repeated author.
2463 // We don't need the content element since "dfrn:env" is always present
2464 //$item["body"] = $xpath->query("atom:content/text()", $entry)->item(0)->nodeValue;
2466 $item["location"] = $xpath->query("dfrn:location/text()", $entry)->item(0)->nodeValue;
2468 $georsspoint = $xpath->query("georss:point", $entry);
2470 $item["coord"] = $georsspoint->item(0)->nodeValue;
2473 $item["private"] = $xpath->query("dfrn:private/text()", $entry)->item(0)->nodeValue;
2475 $item["extid"] = $xpath->query("dfrn:extid/text()", $entry)->item(0)->nodeValue;
2477 if ($xpath->query("dfrn:bookmark/text()", $entry)->item(0)->nodeValue == "true") {
2478 $item["bookmark"] = true;
2481 $notice_info = $xpath->query("statusnet:notice_info", $entry);
2482 if ($notice_info && ($notice_info->length > 0)) {
2483 foreach ($notice_info->item(0)->attributes as $attributes) {
2484 if ($attributes->name == "source") {
2485 $item["app"] = strip_tags($attributes->textContent);
2490 $item["guid"] = $xpath->query("dfrn:diaspora_guid/text()", $entry)->item(0)->nodeValue;
2492 // We store the data from "dfrn:diaspora_signature" in a different table, this is done in "Item::insert"
2493 $dsprsig = unxmlify($xpath->query("dfrn:diaspora_signature/text()", $entry)->item(0)->nodeValue);
2494 if ($dsprsig != "") {
2495 $item["dsprsig"] = $dsprsig;
2498 $item["verb"] = $xpath->query("activity:verb/text()", $entry)->item(0)->nodeValue;
2500 if ($xpath->query("activity:object-type/text()", $entry)->item(0)->nodeValue != "") {
2501 $item["object-type"] = $xpath->query("activity:object-type/text()", $entry)->item(0)->nodeValue;
2504 $object = $xpath->query("activity:object", $entry)->item(0);
2505 $item["object"] = self::transformActivity($xpath, $object, "object");
2507 if (trim($item["object"]) != "") {
2508 $r = XML::parseString($item["object"], false);
2509 if (isset($r->type)) {
2510 $item["object-type"] = $r->type;
2514 $target = $xpath->query("activity:target", $entry)->item(0);
2515 $item["target"] = self::transformActivity($xpath, $target, "target");
2517 $categories = $xpath->query("atom:category", $entry);
2519 foreach ($categories as $category) {
2522 foreach ($category->attributes as $attributes) {
2523 if ($attributes->name == "term") {
2524 $term = $attributes->textContent;
2527 if ($attributes->name == "scheme") {
2528 $scheme = $attributes->textContent;
2532 if (($term != "") && ($scheme != "")) {
2533 $parts = explode(":", $scheme);
2534 if ((count($parts) >= 4) && (array_shift($parts) == "X-DFRN")) {
2535 $termhash = array_shift($parts);
2536 $termurl = implode(":", $parts);
2538 if (strlen($item["tag"])) {
2539 $item["tag"] .= ",";
2542 $item["tag"] .= $termhash . "[url=" . $termurl . "]" . $term . "[/url]";
2550 $links = $xpath->query("atom:link", $entry);
2552 self::parseLinks($links, $item);
2555 $item['conversation-uri'] = $xpath->query('ostatus:conversation/text()', $entry)->item(0)->nodeValue;
2557 $conv = $xpath->query('ostatus:conversation', $entry);
2558 if (is_object($conv->item(0))) {
2559 foreach ($conv->item(0)->attributes as $attributes) {
2560 if ($attributes->name == "ref") {
2561 $item['conversation-uri'] = $attributes->textContent;
2563 if ($attributes->name == "href") {
2564 $item['conversation-href'] = $attributes->textContent;
2569 // Is it a reply or a top level posting?
2570 $item["parent-uri"] = $item["uri"];
2572 $inreplyto = $xpath->query("thr:in-reply-to", $entry);
2573 if (is_object($inreplyto->item(0))) {
2574 foreach ($inreplyto->item(0)->attributes as $attributes) {
2575 if ($attributes->name == "ref") {
2576 $item["parent-uri"] = $attributes->textContent;
2581 // Get the type of the item (Top level post, reply or remote reply)
2582 $entrytype = self::getEntryType($importer, $item);
2584 // Now assign the rest of the values that depend on the type of the message
2585 if (in_array($entrytype, [DFRN_REPLY, DFRN_REPLY_RC])) {
2586 if (!isset($item["object-type"])) {
2587 $item["object-type"] = ACTIVITY_OBJ_COMMENT;
2590 if ($item["contact-id"] != $owner["contact-id"]) {
2591 $item["contact-id"] = $owner["contact-id"];
2594 if (($item["network"] != $owner["network"]) && ($owner["network"] != "")) {
2595 $item["network"] = $owner["network"];
2598 if ($item["contact-id"] != $author["contact-id"]) {
2599 $item["contact-id"] = $author["contact-id"];
2602 if (($item["network"] != $author["network"]) && ($author["network"] != "")) {
2603 $item["network"] = $author["network"];
2607 if ($entrytype == DFRN_REPLY_RC) {
2608 $item["type"] = "remote-comment";
2610 } elseif ($entrytype == DFRN_TOP_LEVEL) {
2611 if (!isset($item["object-type"])) {
2612 $item["object-type"] = ACTIVITY_OBJ_NOTE;
2616 if ($item["object-type"] == ACTIVITY_OBJ_EVENT) {
2617 logger("Item ".$item["uri"]." seems to contain an event.", LOGGER_DEBUG);
2618 $ev = bbtoevent($item["body"]);
2619 if ((x($ev, "desc") || x($ev, "summary")) && x($ev, "start")) {
2620 logger("Event in item ".$item["uri"]." was found.", LOGGER_DEBUG);
2621 $ev["cid"] = $importer["id"];
2622 $ev["uid"] = $importer["uid"];
2623 $ev["uri"] = $item["uri"];
2624 $ev["edited"] = $item["edited"];
2625 $ev["private"] = $item["private"];
2626 $ev["guid"] = $item["guid"];
2629 "SELECT `id` FROM `event` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2630 dbesc($item["uri"]),
2631 intval($importer["uid"])
2633 if (DBM::is_result($r)) {
2634 $ev["id"] = $r[0]["id"];
2637 $event_id = event_store($ev);
2638 logger("Event ".$event_id." was stored", LOGGER_DEBUG);
2644 if (!self::processVerbs($entrytype, $importer, $item, $is_like)) {
2645 logger("Exiting because 'processVerbs' told us so", LOGGER_DEBUG);
2649 // Update content if 'updated' changes
2650 if (DBM::is_result($current)) {
2651 if (self::updateContent($current, $item, $importer, $entrytype)) {
2652 logger("Item ".$item["uri"]." was updated.", LOGGER_DEBUG);
2654 logger("Item ".$item["uri"]." already existed.", LOGGER_DEBUG);
2659 if (in_array($entrytype, [DFRN_REPLY, DFRN_REPLY_RC])) {
2660 $posted_id = Item::insert($item);
2664 logger("Reply from contact ".$item["contact-id"]." was stored with id ".$posted_id, LOGGER_DEBUG);
2666 $item["id"] = $posted_id;
2669 "SELECT `parent`, `parent-uri` FROM `item` WHERE `id` = %d AND `uid` = %d LIMIT 1",
2671 intval($importer["importer_uid"])
2673 if (DBM::is_result($r)) {
2674 $parent = $r[0]["parent"];
2675 $parent_uri = $r[0]["parent-uri"];
2678 if ($posted_id && $parent && ($entrytype == DFRN_REPLY_RC)) {
2679 logger("Notifying followers about comment ".$posted_id, LOGGER_DEBUG);
2680 Worker::add(PRIORITY_HIGH, "Notifier", "comment-import", $posted_id);
2685 } else { // $entrytype == DFRN_TOP_LEVEL
2686 if (!link_compare($item["owner-link"], $importer["url"])) {
2688 * The item owner info is not our contact. It's OK and is to be expected if this is a tgroup delivery,
2689 * but otherwise there's a possible data mixup on the sender's system.
2690 * the tgroup delivery code called from Item::insert will correct it if it's a forum,
2691 * but we're going to unconditionally correct it here so that the post will always be owned by our contact.
2693 logger('Correcting item owner.', LOGGER_DEBUG);
2694 $item["owner-name"] = $importer["senderName"];
2695 $item["owner-link"] = $importer["url"];
2696 $item["owner-avatar"] = $importer["thumb"];
2699 if (($importer["rel"] == CONTACT_IS_FOLLOWER) && (!self::tgroupCheck($importer["importer_uid"], $item))) {
2700 logger("Contact ".$importer["id"]." is only follower and tgroup check was negative.", LOGGER_DEBUG);
2704 // This is my contact on another system, but it's really me.
2705 // Turn this into a wall post.
2706 $notify = Item::isRemoteSelf($importer, $item);
2708 $posted_id = Item::insert($item, false, $notify);
2710 logger("Item was stored with id ".$posted_id, LOGGER_DEBUG);
2712 if (stristr($item["verb"], ACTIVITY_POKE)) {
2713 self::doPoke($item, $importer, $posted_id);
2719 * @brief Deletes items
2721 * @param object $xpath XPath object
2722 * @param object $deletion deletion elements
2723 * @param array $importer Record of the importer user mixed with contact of the content
2725 * @todo set proper type-hints
2727 private static function processDeletion($xpath, $deletion, $importer)
2729 logger("Processing deletions");
2731 foreach ($deletion->attributes as $attributes) {
2732 if ($attributes->name == "ref") {
2733 $uri = $attributes->textContent;
2737 if (!$uri || !$importer["id"]) {
2741 $condition = ["`uri` = ? AND `uid` = ? AND `contact-id` = ? AND NOT `file` LIKE '%[%'",
2742 $uri, $importer["uid"], $importer["id"]];
2743 $item = dba::selectFirst('item', ['id'], $condition);
2744 if (!DBM::is_result($item)) {
2745 logger("Item with uri " . $uri . " from contact " . $importer["id"] . " for user " . $importer["uid"] . " wasn't found.", LOGGER_DEBUG);
2749 $entrytype = self::getEntryType($importer, $item);
2751 if (!$item["deleted"]) {
2752 logger('deleting item '.$item["id"].' uri='.$uri, LOGGER_DEBUG);
2757 Item::deleteById($item["id"]);
2759 if ($entrytype != DFRN_TOP_LEVEL) {
2760 // if this is a relayed delete, propagate it to other recipients
2761 if ($entrytype == DFRN_REPLY_RC) {
2762 logger("Notifying followers about deletion of post " . $item["id"], LOGGER_DEBUG);
2763 Worker::add(PRIORITY_HIGH, "Notifier", "drop", $item["id"]);
2769 * @brief Imports a DFRN message
2771 * @param string $xml The DFRN message
2772 * @param array $importer Record of the importer user mixed with contact of the content
2773 * @param bool $sort_by_date Is used when feeds are polled
2774 * @return integer Import status
2775 * @todo set proper type-hints
2777 public static function import($xml, $importer, $sort_by_date = false)
2783 $doc = new DOMDocument();
2784 @$doc->loadXML($xml);
2786 $xpath = new DOMXPath($doc);
2787 $xpath->registerNamespace("atom", NAMESPACE_ATOM1);
2788 $xpath->registerNamespace("thr", NAMESPACE_THREAD);
2789 $xpath->registerNamespace("at", NAMESPACE_TOMB);
2790 $xpath->registerNamespace("media", NAMESPACE_MEDIA);
2791 $xpath->registerNamespace("dfrn", NAMESPACE_DFRN);
2792 $xpath->registerNamespace("activity", NAMESPACE_ACTIVITY);
2793 $xpath->registerNamespace("georss", NAMESPACE_GEORSS);
2794 $xpath->registerNamespace("poco", NAMESPACE_POCO);
2795 $xpath->registerNamespace("ostatus", NAMESPACE_OSTATUS);
2796 $xpath->registerNamespace("statusnet", NAMESPACE_STATUSNET);
2799 $header["uid"] = $importer["uid"];
2800 $header["network"] = NETWORK_DFRN;
2801 $header["type"] = "remote";
2802 $header["wall"] = 0;
2803 $header["origin"] = 0;
2804 $header["contact-id"] = $importer["id"];
2806 // Update the contact table if the data has changed
2808 // The "atom:author" is only present in feeds
2809 if ($xpath->query("/atom:feed/atom:author")->length > 0) {
2810 self::fetchauthor($xpath, $doc->firstChild, $importer, "atom:author", false, $xml);
2813 // Only the "dfrn:owner" in the head section contains all data
2814 if ($xpath->query("/atom:feed/dfrn:owner")->length > 0) {
2815 self::fetchauthor($xpath, $doc->firstChild, $importer, "dfrn:owner", false, $xml);
2818 logger("Import DFRN message for user " . $importer["uid"] . " from contact " . $importer["id"], LOGGER_DEBUG);
2820 // The account type is new since 3.5.1
2821 if ($xpath->query("/atom:feed/dfrn:account_type")->length > 0) {
2822 $accounttype = intval($xpath->evaluate("/atom:feed/dfrn:account_type/text()")->item(0)->nodeValue);
2824 if ($accounttype != $importer["contact-type"]) {
2825 dba::update('contact', ['contact-type' => $accounttype], ['id' => $importer["id"]]);
2829 // is it a public forum? Private forums aren't supported with this method
2830 // This is deprecated since 3.5.1
2831 $forum = intval($xpath->evaluate("/atom:feed/dfrn:community/text()")->item(0)->nodeValue);
2833 if ($forum != $importer["forum"]) {
2834 $condition = ['`forum` != ? AND `id` = ?', $forum, $importer["id"]];
2835 dba::update('contact', ['forum' => $forum], $condition);
2838 // We are processing relocations even if we are ignoring a contact
2839 $relocations = $xpath->query("/atom:feed/dfrn:relocate");
2840 foreach ($relocations as $relocation) {
2841 self::processRelocation($xpath, $relocation, $importer);
2844 if ($importer["readonly"]) {
2845 // We aren't receiving stuff from this person. But we will quietly ignore them
2846 // rather than a blatant "go away" message.
2847 logger('ignoring contact '.$importer["id"]);
2851 $mails = $xpath->query("/atom:feed/dfrn:mail");
2852 foreach ($mails as $mail) {
2853 self::processMail($xpath, $mail, $importer);
2856 $suggestions = $xpath->query("/atom:feed/dfrn:suggest");
2857 foreach ($suggestions as $suggestion) {
2858 self::processSuggestion($xpath, $suggestion, $importer);
2861 $deletions = $xpath->query("/atom:feed/at:deleted-entry");
2862 foreach ($deletions as $deletion) {
2863 self::processDeletion($xpath, $deletion, $importer);
2866 if (!$sort_by_date) {
2867 $entries = $xpath->query("/atom:feed/atom:entry");
2868 foreach ($entries as $entry) {
2869 self::processEntry($header, $xpath, $entry, $importer, $xml);
2873 $entries = $xpath->query("/atom:feed/atom:entry");
2874 foreach ($entries as $entry) {
2875 $created = $xpath->query("atom:published/text()", $entry)->item(0)->nodeValue;
2876 $newentries[strtotime($created)] = $entry;
2879 // Now sort after the publishing date
2882 foreach ($newentries as $entry) {
2883 self::processEntry($header, $xpath, $entry, $importer, $xml);
2886 logger("Import done for user " . $importer["uid"] . " from contact " . $importer["id"], LOGGER_DEBUG);
2892 * @param string $contact_nick contact nickname
2894 public static function autoRedir(App $a, $contact_nick)
2897 if (x($_REQUEST, 'redir') && intval($_REQUEST['redir'])) {
2901 if ((! $contact_nick) || ($contact_nick === $a->user['nickname'])) {
2906 // We need to find out if $contact_nick is a user on this hub, and if so, if I
2907 // am a contact of that user. However, that user may have other contacts with the
2908 // same nickname as me on other hubs or other networks. Exclude these by requiring
2909 // that the contact have a local URL. I will be the only person with my nickname at
2910 // this URL, so if a result is found, then I am a contact of the $contact_nick user.
2912 // We also have to make sure that I'm a legitimate contact--I'm not blocked or pending.
2914 $baseurl = System::baseUrl();
2915 $domain_st = strpos($baseurl, "://");
2916 if ($domain_st === false) {
2919 $baseurl = substr($baseurl, $domain_st + 3);
2920 $nurl = normalise_link($baseurl);
2922 /// @todo Why is there a query for "url" *and* "nurl"? Especially this normalising is strange.
2923 $r = q("SELECT `id` FROM `contact` WHERE `uid` = (SELECT `uid` FROM `user` WHERE `nickname` = '%s' LIMIT 1)
2924 AND `nick` = '%s' AND NOT `self` AND (`url` LIKE '%%%s%%' OR `nurl` LIKE '%%%s%%') AND NOT `blocked` AND NOT `pending` LIMIT 1",
2925 dbesc($contact_nick),
2926 dbesc($a->user['nickname']),
2930 if ((! DBM::is_result($r)) || $r[0]['id'] == remote_user()) {
2934 $r = q("SELECT * FROM contact WHERE nick = '%s'
2935 AND network = '%s' AND uid = %d AND url LIKE '%%%s%%' LIMIT 1",
2936 dbesc($contact_nick),
2937 dbesc(NETWORK_DFRN),
2938 intval(local_user()),
2941 if (! DBM::is_result($r)) {
2947 $dfrn_id = (($r[0]['issued-id']) ? $r[0]['issued-id'] : $r[0]['dfrn-id']);
2949 if ($r[0]['duplex'] && $r[0]['issued-id']) {
2950 $orig_id = $r[0]['issued-id'];
2951 $dfrn_id = '1:' . $orig_id;
2953 if ($r[0]['duplex'] && $r[0]['dfrn-id']) {
2954 $orig_id = $r[0]['dfrn-id'];
2955 $dfrn_id = '0:' . $orig_id;
2958 // ensure that we've got a valid ID. There may be some edge cases with forums and non-duplex mode
2959 // that may have triggered some of the "went to {profile/intro} and got an RSS feed" issues
2961 if (strlen($dfrn_id) < 3) {
2965 $sec = random_string();
2967 dba::insert('profile_check', ['uid' => local_user(), 'cid' => $cid, 'dfrn_id' => $dfrn_id, 'sec' => $sec, 'expire' => time() + 45]);
2969 $url = curPageURL();
2971 logger('auto_redir: ' . $r[0]['name'] . ' ' . $sec, LOGGER_DEBUG);
2972 $dest = (($url) ? '&destination_url=' . $url : '');
2973 goaway($r[0]['poll'] . '?dfrn_id=' . $dfrn_id
2974 . '&dfrn_version=' . DFRN_PROTOCOL_VERSION . '&type=profile&sec=' . $sec . $dest);
2981 * @brief Returns the activity verb
2983 * @param array $item Item array
2985 * @return string activity verb
2987 private static function constructVerb(array $item)
2989 if ($item['verb']) {
2990 return $item['verb'];
2992 return ACTIVITY_POST;
2995 private static function tgroupCheck($uid, $item)
2999 // check that the message originated elsewhere and is a top-level post
3001 if ($item['wall'] || $item['origin'] || ($item['uri'] != $item['parent-uri'])) {
3005 $u = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1",
3008 if (!DBM::is_result($u)) {
3012 $community_page = ($u[0]['page-flags'] == PAGE_COMMUNITY);
3013 $prvgroup = ($u[0]['page-flags'] == PAGE_PRVGROUP);
3015 $link = normalise_link(System::baseUrl() . '/profile/' . $u[0]['nickname']);
3018 * Diaspora uses their own hardwired link URL in @-tags
3019 * instead of the one we supply with webfinger
3021 $dlink = normalise_link(System::baseUrl() . '/u/' . $u[0]['nickname']);
3023 $cnt = preg_match_all('/[\@\!]\[url\=(.*?)\](.*?)\[\/url\]/ism', $item['body'], $matches, PREG_SET_ORDER);
3025 foreach ($matches as $mtch) {
3026 if (link_compare($link, $mtch[1]) || link_compare($dlink, $mtch[1])) {
3028 logger('mention found: ' . $mtch[2]);
3037 return $community_page || $prvgroup;
3041 * This function returns true if $update has an edited timestamp newer
3042 * than $existing, i.e. $update contains new data which should override
3043 * what's already there. If there is no timestamp yet, the update is
3044 * assumed to be newer. If the update has no timestamp, the existing
3045 * item is assumed to be up-to-date. If the timestamps are equal it
3046 * assumes the update has been seen before and should be ignored.
3049 private static function isEditedTimestampNewer($existing, $update)
3051 if (!x($existing, 'edited') || !$existing['edited']) {
3054 if (!x($update, 'edited') || !$update['edited']) {
3058 $existing_edited = DateTimeFormat::utc($existing['edited']);
3059 $update_edited = DateTimeFormat::utc($update['edited']);
3061 return (strcmp($existing_edited, $update_edited) < 0);