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
100 public static function feed($dfrn_id, $owner_nick, $last_update, $direction = 0, $onlyheader = false)
104 $sitefeed = ((strlen($owner_nick)) ? false : true); // not yet implemented, need to rewrite huge chunks of following logic
105 $public_feed = (($dfrn_id) ? false : true);
106 $starred = false; // not yet implemented, possible security issues
109 if ($public_feed && $a->argc > 2) {
110 for ($x = 2; $x < $a->argc; $x++) {
111 if ($a->argv[$x] == 'converse') {
114 if ($a->argv[$x] == 'starred') {
117 if ($a->argv[$x] == 'category' && $a->argc > ($x + 1) && strlen($a->argv[$x+1])) {
118 $category = $a->argv[$x+1];
123 // default permissions - anonymous user
125 $sql_extra = " AND `item`.`allow_cid` = '' AND `item`.`allow_gid` = '' AND `item`.`deny_cid` = '' AND `item`.`deny_gid` = '' ";
128 "SELECT `contact`.*, `user`.`nickname`, `user`.`timezone`, `user`.`page-flags`, `user`.`account-type`
129 FROM `contact` INNER JOIN `user` ON `user`.`uid` = `contact`.`uid`
130 WHERE `contact`.`self` AND `user`.`nickname` = '%s' LIMIT 1",
134 if (! DBM::is_result($r)) {
135 logger(sprintf('No contact found for nickname=%d', $owner_nick), LOGGER_WARNING);
140 $owner_id = $owner['uid'];
141 $owner_nick = $owner['nickname'];
143 $sql_post_table = "";
145 if (! $public_feed) {
147 switch ($direction) {
149 $sql_extra = sprintf(" AND `issued-id` = '%s' ", dbesc($dfrn_id));
153 $sql_extra = sprintf(" AND `issued-id` = '%s' AND `duplex` = 1 ", dbesc($dfrn_id));
154 $my_id = '1:' . $dfrn_id;
157 $sql_extra = sprintf(" AND `dfrn-id` = '%s' AND `duplex` = 1 ", dbesc($dfrn_id));
158 $my_id = '0:' . $dfrn_id;
166 "SELECT * FROM `contact` WHERE NOT `blocked` AND `contact`.`uid` = %d $sql_extra LIMIT 1",
170 if (! DBM::is_result($r)) {
171 logger(sprintf('No contact found for uid=%d', $owner_id), LOGGER_WARNING);
176 include_once 'include/security.php';
177 $groups = Group::getIdsByContactId($contact['id']);
179 if (count($groups)) {
180 for ($x = 0; $x < count($groups); $x ++) {
181 $groups[$x] = '<' . intval($groups[$x]) . '>' ;
184 $gs = implode('|', $groups);
186 $gs = '<<>>' ; // Impossible to match
189 $sql_extra = sprintf(
191 AND ( `allow_cid` = '' OR `allow_cid` REGEXP '<%d>' )
192 AND ( `deny_cid` = '' OR NOT `deny_cid` REGEXP '<%d>' )
193 AND ( `allow_gid` = '' OR `allow_gid` REGEXP '%s' )
194 AND ( `deny_gid` = '' OR NOT `deny_gid` REGEXP '%s')
196 intval($contact['id']),
197 intval($contact['id']),
209 if (! strlen($last_update)) {
210 $last_update = 'now -30 days';
213 if (isset($category)) {
214 $sql_post_table = sprintf(
215 "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` ",
216 dbesc(protect_sprintf($category)),
217 intval(TERM_OBJ_POST),
218 intval(TERM_CATEGORY),
221 //$sql_extra .= file_tag_file_query('item',$category,'category');
224 if ($public_feed && ! $converse) {
225 $sql_extra .= " AND `contact`.`self` = 1 ";
228 $check_date = DateTimeFormat::utc($last_update);
231 "SELECT `item`.*, `item`.`id` AS `item_id`,
232 `contact`.`name`, `contact`.`network`, `contact`.`photo`, `contact`.`url`,
233 `contact`.`name-date`, `contact`.`uri-date`, `contact`.`avatar-date`,
234 `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
235 `sign`.`signed_text`, `sign`.`signature`, `sign`.`signer`
236 FROM `item` USE INDEX (`uid_wall_changed`) $sql_post_table
237 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
238 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
239 LEFT JOIN `sign` ON `sign`.`iid` = `item`.`id`
240 WHERE `item`.`uid` = %d AND `item`.`visible` AND NOT `item`.`moderated` AND `item`.`parent` != 0
241 AND `item`.`wall` AND `item`.`changed` > '%s'
243 ORDER BY `item`.`parent` ".$sort.", `item`.`created` ASC LIMIT 0, 300",
250 * Will check further below if this actually returned results.
251 * We will provide an empty feed if that is the case.
256 $doc = new DOMDocument('1.0', 'utf-8');
257 $doc->formatOutput = true;
259 $alternatelink = $owner['url'];
261 if (isset($category)) {
262 $alternatelink .= "/category/".$category;
266 $author = "dfrn:owner";
271 $root = self::addHeader($doc, $owner, $author, $alternatelink, true);
273 /// @TODO This hook can't work anymore
274 // Addon::callHooks('atom_feed', $atom);
276 if (!DBM::is_result($items) || $onlyheader) {
277 $atom = trim($doc->saveXML());
279 Addon::callHooks('atom_feed_end', $atom);
284 foreach ($items as $item) {
285 // prevent private email from leaking.
286 if ($item['network'] == NETWORK_MAIL) {
290 // public feeds get html, our own nodes use bbcode
294 // catch any email that's in a public conversation and make sure it doesn't leak
295 if ($item['private']) {
302 $entry = self::entry($doc, $type, $item, $owner, true);
303 $root->appendChild($entry);
306 $atom = trim($doc->saveXML());
308 Addon::callHooks('atom_feed_end', $atom);
314 * @brief Generate an atom entry for a given item id
316 * @param int $item_id The item id
317 * @param boolean $conversation Show the conversation. If false show the single post.
319 * @return string DFRN feed entry
321 public static function itemFeed($item_id, $conversation = false)
324 $condition = '`item`.`parent`';
326 $condition = '`item`.`id`';
330 "SELECT `item`.*, `item`.`id` AS `item_id`,
331 `contact`.`name`, `contact`.`network`, `contact`.`photo`, `contact`.`url`,
332 `contact`.`name-date`, `contact`.`uri-date`, `contact`.`avatar-date`,
333 `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
334 `sign`.`signed_text`, `sign`.`signature`, `sign`.`signer`
336 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
337 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
338 LEFT JOIN `sign` ON `sign`.`iid` = `item`.`id`
339 WHERE %s = %d AND `item`.`visible` AND NOT `item`.`moderated` AND `item`.`parent` != 0
340 AND NOT `item`.`private`",
345 if (!DBM::is_result($r)) {
352 if ($item['uid'] != 0) {
353 $owner = User::getOwnerDataById($item['uid']);
358 $owner = ['uid' => 0, 'nick' => 'feed-item'];
361 $doc = new DOMDocument('1.0', 'utf-8');
362 $doc->formatOutput = true;
366 $root = $doc->createElementNS(NAMESPACE_ATOM1, 'feed');
367 $doc->appendChild($root);
369 $root->setAttribute("xmlns:thr", NAMESPACE_THREAD);
370 $root->setAttribute("xmlns:at", NAMESPACE_TOMB);
371 $root->setAttribute("xmlns:media", NAMESPACE_MEDIA);
372 $root->setAttribute("xmlns:dfrn", NAMESPACE_DFRN);
373 $root->setAttribute("xmlns:activity", NAMESPACE_ACTIVITY);
374 $root->setAttribute("xmlns:georss", NAMESPACE_GEORSS);
375 $root->setAttribute("xmlns:poco", NAMESPACE_POCO);
376 $root->setAttribute("xmlns:ostatus", NAMESPACE_OSTATUS);
377 $root->setAttribute("xmlns:statusnet", NAMESPACE_STATUSNET);
379 //$root = self::addHeader($doc, $owner, "dfrn:owner", "", false);
381 foreach ($items as $item) {
382 $entry = self::entry($doc, $type, $item, $owner, true, 0);
383 $root->appendChild($entry);
386 $root = self::entry($doc, $type, $item, $owner, true, 0, true);
389 $atom = trim($doc->saveXML());
394 * @brief Create XML text for DFRN mails
396 * @param array $item message elements
397 * @param array $owner Owner record
399 * @return string DFRN mail
400 * @todo Find proper type-hints
402 public static function mail($item, $owner)
404 $doc = new DOMDocument('1.0', 'utf-8');
405 $doc->formatOutput = true;
407 $root = self::addHeader($doc, $owner, "dfrn:owner", "", false);
409 $mail = $doc->createElement("dfrn:mail");
410 $sender = $doc->createElement("dfrn:sender");
412 XML::addElement($doc, $sender, "dfrn:name", $owner['name']);
413 XML::addElement($doc, $sender, "dfrn:uri", $owner['url']);
414 XML::addElement($doc, $sender, "dfrn:avatar", $owner['thumb']);
416 $mail->appendChild($sender);
418 XML::addElement($doc, $mail, "dfrn:id", $item['uri']);
419 XML::addElement($doc, $mail, "dfrn:in-reply-to", $item['parent-uri']);
420 XML::addElement($doc, $mail, "dfrn:sentdate", DateTimeFormat::utc($item['created'] . '+00:00', DateTimeFormat::ATOM));
421 XML::addElement($doc, $mail, "dfrn:subject", $item['title']);
422 XML::addElement($doc, $mail, "dfrn:content", $item['body']);
424 $root->appendChild($mail);
426 return trim($doc->saveXML());
430 * @brief Create XML text for DFRN friend suggestions
432 * @param array $item suggestion elements
433 * @param array $owner Owner record
435 * @return string DFRN suggestions
436 * @todo Find proper type-hints
438 public static function fsuggest($item, $owner)
440 $doc = new DOMDocument('1.0', 'utf-8');
441 $doc->formatOutput = true;
443 $root = self::addHeader($doc, $owner, "dfrn:owner", "", false);
445 $suggest = $doc->createElement("dfrn:suggest");
447 XML::addElement($doc, $suggest, "dfrn:url", $item['url']);
448 XML::addElement($doc, $suggest, "dfrn:name", $item['name']);
449 XML::addElement($doc, $suggest, "dfrn:photo", $item['photo']);
450 XML::addElement($doc, $suggest, "dfrn:request", $item['request']);
451 XML::addElement($doc, $suggest, "dfrn:note", $item['note']);
453 $root->appendChild($suggest);
455 return trim($doc->saveXML());
459 * @brief Create XML text for DFRN relocations
461 * @param array $owner Owner record
462 * @param int $uid User ID
464 * @return string DFRN relocations
465 * @todo Find proper type-hints
467 public static function relocate($owner, $uid)
470 /* get site pubkey. this could be a new installation with no site keys*/
471 $pubkey = Config::get('system', 'site_pubkey');
473 $res = Crypto::newKeypair(1024);
474 Config::set('system', 'site_prvkey', $res['prvkey']);
475 Config::set('system', 'site_pubkey', $res['pubkey']);
479 "SELECT `resource-id` , `scale`, type FROM `photo`
480 WHERE `profile` = 1 AND `uid` = %d ORDER BY scale;",
484 $ext = Image::supportedTypes();
486 foreach ($rp as $p) {
487 $photos[$p['scale']] = System::baseUrl().'/photo/'.$p['resource-id'].'-'.$p['scale'].'.'.$ext[$p['type']];
491 $doc = new DOMDocument('1.0', 'utf-8');
492 $doc->formatOutput = true;
494 $root = self::addHeader($doc, $owner, "dfrn:owner", "", false);
496 $relocate = $doc->createElement("dfrn:relocate");
498 XML::addElement($doc, $relocate, "dfrn:url", $owner['url']);
499 XML::addElement($doc, $relocate, "dfrn:name", $owner['name']);
500 XML::addElement($doc, $relocate, "dfrn:addr", $owner['addr']);
501 XML::addElement($doc, $relocate, "dfrn:avatar", $owner['avatar']);
502 XML::addElement($doc, $relocate, "dfrn:photo", $photos[4]);
503 XML::addElement($doc, $relocate, "dfrn:thumb", $photos[5]);
504 XML::addElement($doc, $relocate, "dfrn:micro", $photos[6]);
505 XML::addElement($doc, $relocate, "dfrn:request", $owner['request']);
506 XML::addElement($doc, $relocate, "dfrn:confirm", $owner['confirm']);
507 XML::addElement($doc, $relocate, "dfrn:notify", $owner['notify']);
508 XML::addElement($doc, $relocate, "dfrn:poll", $owner['poll']);
509 XML::addElement($doc, $relocate, "dfrn:sitepubkey", Config::get('system', 'site_pubkey'));
511 $root->appendChild($relocate);
513 return trim($doc->saveXML());
517 * @brief Adds the header elements for the DFRN protocol
519 * @param object $doc XML document
520 * @param array $owner Owner record
521 * @param string $authorelement Element name for the author
522 * @param string $alternatelink link to profile or category
523 * @param bool $public Is it a header for public posts?
525 * @return object XML root object
526 * @todo Find proper type-hints
528 private static function addHeader($doc, $owner, $authorelement, $alternatelink = "", $public = false)
531 if ($alternatelink == "") {
532 $alternatelink = $owner['url'];
535 $root = $doc->createElementNS(NAMESPACE_ATOM1, 'feed');
536 $doc->appendChild($root);
538 $root->setAttribute("xmlns:thr", NAMESPACE_THREAD);
539 $root->setAttribute("xmlns:at", NAMESPACE_TOMB);
540 $root->setAttribute("xmlns:media", NAMESPACE_MEDIA);
541 $root->setAttribute("xmlns:dfrn", NAMESPACE_DFRN);
542 $root->setAttribute("xmlns:activity", NAMESPACE_ACTIVITY);
543 $root->setAttribute("xmlns:georss", NAMESPACE_GEORSS);
544 $root->setAttribute("xmlns:poco", NAMESPACE_POCO);
545 $root->setAttribute("xmlns:ostatus", NAMESPACE_OSTATUS);
546 $root->setAttribute("xmlns:statusnet", NAMESPACE_STATUSNET);
548 XML::addElement($doc, $root, "id", System::baseUrl()."/profile/".$owner["nick"]);
549 XML::addElement($doc, $root, "title", $owner["name"]);
551 $attributes = ["uri" => "https://friendi.ca", "version" => FRIENDICA_VERSION."-".DB_UPDATE_VERSION];
552 XML::addElement($doc, $root, "generator", FRIENDICA_PLATFORM, $attributes);
554 $attributes = ["rel" => "license", "href" => "http://creativecommons.org/licenses/by/3.0/"];
555 XML::addElement($doc, $root, "link", "", $attributes);
557 $attributes = ["rel" => "alternate", "type" => "text/html", "href" => $alternatelink];
558 XML::addElement($doc, $root, "link", "", $attributes);
562 // DFRN itself doesn't uses this. But maybe someone else wants to subscribe to the public feed.
563 OStatus::hublinks($doc, $root, $owner["nick"]);
565 $attributes = ["rel" => "salmon", "href" => System::baseUrl()."/salmon/".$owner["nick"]];
566 XML::addElement($doc, $root, "link", "", $attributes);
568 $attributes = ["rel" => "http://salmon-protocol.org/ns/salmon-replies", "href" => System::baseUrl()."/salmon/".$owner["nick"]];
569 XML::addElement($doc, $root, "link", "", $attributes);
571 $attributes = ["rel" => "http://salmon-protocol.org/ns/salmon-mention", "href" => System::baseUrl()."/salmon/".$owner["nick"]];
572 XML::addElement($doc, $root, "link", "", $attributes);
575 // For backward compatibility we keep this element
576 if ($owner['page-flags'] == PAGE_COMMUNITY) {
577 XML::addElement($doc, $root, "dfrn:community", 1);
580 // The former element is replaced by this one
581 XML::addElement($doc, $root, "dfrn:account_type", $owner["account-type"]);
583 /// @todo We need a way to transmit the different page flags like "PAGE_PRVGROUP"
585 XML::addElement($doc, $root, "updated", DateTimeFormat::utcNow(DateTimeFormat::ATOM));
587 $author = self::addAuthor($doc, $owner, $authorelement, $public);
588 $root->appendChild($author);
594 * @brief Adds the author element in the header for the DFRN protocol
596 * @param object $doc XML document
597 * @param array $owner Owner record
598 * @param string $authorelement Element name for the author
599 * @param boolean $public boolean
601 * @return object XML author object
602 * @todo Find proper type-hints
604 private static function addAuthor($doc, $owner, $authorelement, $public)
606 // Is the profile hidden or shouldn't be published in the net? Then add the "hide" element
608 "SELECT `id` FROM `profile` INNER JOIN `user` ON `user`.`uid` = `profile`.`uid`
609 WHERE (`hidewall` OR NOT `net-publish`) AND `user`.`uid` = %d",
610 intval($owner['uid'])
612 if (DBM::is_result($r)) {
618 $author = $doc->createElement($authorelement);
620 $namdate = DateTimeFormat::utc($owner['name-date'].'+00:00', DateTimeFormat::ATOM);
621 $uridate = DateTimeFormat::utc($owner['uri-date'].'+00:00', DateTimeFormat::ATOM);
622 $picdate = DateTimeFormat::utc($owner['avatar-date'].'+00:00', DateTimeFormat::ATOM);
626 if (!$public || !$hidewall) {
627 $attributes = ["dfrn:updated" => $namdate];
630 XML::addElement($doc, $author, "name", $owner["name"], $attributes);
631 XML::addElement($doc, $author, "uri", System::baseUrl().'/profile/'.$owner["nickname"], $attributes);
632 XML::addElement($doc, $author, "dfrn:handle", $owner["addr"], $attributes);
634 $attributes = ["rel" => "photo", "type" => "image/jpeg",
635 "media:width" => 175, "media:height" => 175, "href" => $owner['photo']];
637 if (!$public || !$hidewall) {
638 $attributes["dfrn:updated"] = $picdate;
641 XML::addElement($doc, $author, "link", "", $attributes);
643 $attributes["rel"] = "avatar";
644 XML::addElement($doc, $author, "link", "", $attributes);
647 XML::addElement($doc, $author, "dfrn:hide", "true");
650 // The following fields will only be generated if the data isn't meant for a public feed
655 $birthday = feed_birthday($owner['uid'], $owner['timezone']);
658 XML::addElement($doc, $author, "dfrn:birthday", $birthday);
661 // Only show contact details when we are allowed to
663 "SELECT `profile`.`about`, `profile`.`name`, `profile`.`homepage`, `user`.`nickname`,
664 `user`.`timezone`, `profile`.`locality`, `profile`.`region`, `profile`.`country-name`,
665 `profile`.`pub_keywords`, `profile`.`xmpp`, `profile`.`dob`
667 INNER JOIN `user` ON `user`.`uid` = `profile`.`uid`
668 WHERE `profile`.`is-default` AND NOT `user`.`hidewall` AND `user`.`uid` = %d",
669 intval($owner['uid'])
671 if (DBM::is_result($r)) {
674 XML::addElement($doc, $author, "poco:displayName", $profile["name"]);
675 XML::addElement($doc, $author, "poco:updated", $namdate);
677 if (trim($profile["dob"]) > '0001-01-01') {
678 XML::addElement($doc, $author, "poco:birthday", "0000-".date("m-d", strtotime($profile["dob"])));
681 XML::addElement($doc, $author, "poco:note", $profile["about"]);
682 XML::addElement($doc, $author, "poco:preferredUsername", $profile["nickname"]);
684 $savetz = date_default_timezone_get();
685 date_default_timezone_set($profile["timezone"]);
686 XML::addElement($doc, $author, "poco:utcOffset", date("P"));
687 date_default_timezone_set($savetz);
689 if (trim($profile["homepage"]) != "") {
690 $urls = $doc->createElement("poco:urls");
691 XML::addElement($doc, $urls, "poco:type", "homepage");
692 XML::addElement($doc, $urls, "poco:value", $profile["homepage"]);
693 XML::addElement($doc, $urls, "poco:primary", "true");
694 $author->appendChild($urls);
697 if (trim($profile["pub_keywords"]) != "") {
698 $keywords = explode(",", $profile["pub_keywords"]);
700 foreach ($keywords as $keyword) {
701 XML::addElement($doc, $author, "poco:tags", trim($keyword));
705 if (trim($profile["xmpp"]) != "") {
706 $ims = $doc->createElement("poco:ims");
707 XML::addElement($doc, $ims, "poco:type", "xmpp");
708 XML::addElement($doc, $ims, "poco:value", $profile["xmpp"]);
709 XML::addElement($doc, $ims, "poco:primary", "true");
710 $author->appendChild($ims);
713 if (trim($profile["locality"].$profile["region"].$profile["country-name"]) != "") {
714 $element = $doc->createElement("poco:address");
716 XML::addElement($doc, $element, "poco:formatted", Profile::formatLocation($profile));
718 if (trim($profile["locality"]) != "") {
719 XML::addElement($doc, $element, "poco:locality", $profile["locality"]);
722 if (trim($profile["region"]) != "") {
723 XML::addElement($doc, $element, "poco:region", $profile["region"]);
726 if (trim($profile["country-name"]) != "") {
727 XML::addElement($doc, $element, "poco:country", $profile["country-name"]);
730 $author->appendChild($element);
738 * @brief Adds the author elements in the "entry" elements of the DFRN protocol
740 * @param object $doc XML document
741 * @param string $element Element name for the author
742 * @param string $contact_url Link of the contact
743 * @param array $item Item elements
745 * @return object XML author object
746 * @todo Find proper type-hints
748 private static function addEntryAuthor($doc, $element, $contact_url, $item)
750 $contact = Contact::getDetailsByURL($contact_url, $item["uid"]);
752 $author = $doc->createElement($element);
753 XML::addElement($doc, $author, "name", $contact["name"]);
754 XML::addElement($doc, $author, "uri", $contact["url"]);
755 XML::addElement($doc, $author, "dfrn:handle", $contact["addr"]);
758 /// - Check real image type and image size
759 /// - Check which of these boths elements we should use
762 "type" => "image/jpeg",
764 "media:height" => 80,
765 "href" => $contact["photo"]];
766 XML::addElement($doc, $author, "link", "", $attributes);
770 "type" => "image/jpeg",
772 "media:height" => 80,
773 "href" => $contact["photo"]];
774 XML::addElement($doc, $author, "link", "", $attributes);
780 * @brief Adds the activity elements
782 * @param object $doc XML document
783 * @param string $element Element name for the activity
784 * @param string $activity activity value
786 * @return object XML activity object
787 * @todo Find proper type-hints
789 private static function createActivity($doc, $element, $activity)
792 $entry = $doc->createElement($element);
794 $r = XML::parseString($activity, false);
800 XML::addElement($doc, $entry, "activity:object-type", $r->type);
804 XML::addElement($doc, $entry, "id", $r->id);
808 XML::addElement($doc, $entry, "title", $r->title);
812 if (substr($r->link, 0, 1) == '<') {
813 if (strstr($r->link, '&') && (! strstr($r->link, '&'))) {
814 $r->link = str_replace('&', '&', $r->link);
817 $r->link = preg_replace('/\<link(.*?)\"\>/', '<link$1"/>', $r->link);
819 // XML does need a single element as root element so we add a dummy element here
820 $data = XML::parseString("<dummy>" . $r->link . "</dummy>", false);
821 if (is_object($data)) {
822 foreach ($data->link as $link) {
824 foreach ($link->attributes() as $parameter => $value) {
825 $attributes[$parameter] = $value;
827 XML::addElement($doc, $entry, "link", "", $attributes);
831 $attributes = ["rel" => "alternate", "type" => "text/html", "href" => $r->link];
832 XML::addElement($doc, $entry, "link", "", $attributes);
836 XML::addElement($doc, $entry, "content", BBCode::convert($r->content), ["type" => "html"]);
846 * @brief Adds the elements for attachments
848 * @param object $doc XML document
849 * @param object $root XML root
850 * @param array $item Item element
852 * @return object XML attachment object
853 * @todo Find proper type-hints
855 private static function getAttachment($doc, $root, $item)
857 $arr = explode('[/attach],', $item['attach']);
859 foreach ($arr as $r) {
861 $cnt = preg_match('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\" title=\"(.*?)\"|', $r, $matches);
863 $attributes = ["rel" => "enclosure",
864 "href" => $matches[1],
865 "type" => $matches[3]];
867 if (intval($matches[2])) {
868 $attributes["length"] = intval($matches[2]);
871 if (trim($matches[4]) != "") {
872 $attributes["title"] = trim($matches[4]);
875 XML::addElement($doc, $root, "link", "", $attributes);
882 * @brief Adds the "entry" elements for the DFRN protocol
884 * @param object $doc XML document
885 * @param string $type "text" or "html"
886 * @param array $item Item element
887 * @param array $owner Owner record
888 * @param bool $comment Trigger the sending of the "comment" element
889 * @param int $cid Contact ID of the recipient
890 * @param bool $single If set, the entry is created as an XML document with a single "entry" element
892 * @return object XML entry object
893 * @todo Find proper type-hints
895 private static function entry($doc, $type, $item, $owner, $comment = false, $cid = 0, $single = false)
899 if (!$item['parent']) {
903 if ($item['deleted']) {
904 $attributes = ["ref" => $item['uri'], "when" => DateTimeFormat::utc($item['edited'] . '+00:00', DateTimeFormat::ATOM)];
905 return XML::createElement($doc, "at:deleted-entry", "", $attributes);
909 $entry = $doc->createElement("entry");
911 $entry = $doc->createElementNS(NAMESPACE_ATOM1, 'entry');
912 $doc->appendChild($entry);
914 $entry->setAttribute("xmlns:thr", NAMESPACE_THREAD);
915 $entry->setAttribute("xmlns:at", NAMESPACE_TOMB);
916 $entry->setAttribute("xmlns:media", NAMESPACE_MEDIA);
917 $entry->setAttribute("xmlns:dfrn", NAMESPACE_DFRN);
918 $entry->setAttribute("xmlns:activity", NAMESPACE_ACTIVITY);
919 $entry->setAttribute("xmlns:georss", NAMESPACE_GEORSS);
920 $entry->setAttribute("xmlns:poco", NAMESPACE_POCO);
921 $entry->setAttribute("xmlns:ostatus", NAMESPACE_OSTATUS);
922 $entry->setAttribute("xmlns:statusnet", NAMESPACE_STATUSNET);
925 if ($item['allow_cid'] || $item['allow_gid'] || $item['deny_cid'] || $item['deny_gid']) {
926 $body = Item::fixPrivatePhotos($item['body'], $owner['uid'], $item, $cid);
928 $body = $item['body'];
931 // Remove the abstract element. It is only locally important.
932 $body = BBCode::stripAbstract($body);
935 if ($type == 'html') {
938 if ($item['title'] != "") {
939 $htmlbody = "[b]" . $item['title'] . "[/b]\n\n" . $htmlbody;
942 $htmlbody = BBCode::convert($htmlbody, false, 7);
945 $author = self::addEntryAuthor($doc, "author", $item["author-link"], $item);
946 $entry->appendChild($author);
948 $dfrnowner = self::addEntryAuthor($doc, "dfrn:owner", $item["owner-link"], $item);
949 $entry->appendChild($dfrnowner);
951 if (($item['parent'] != $item['id']) || ($item['parent-uri'] !== $item['uri']) || (($item['thr-parent'] !== '') && ($item['thr-parent'] !== $item['uri']))) {
952 $parent_item = (($item['thr-parent']) ? $item['thr-parent'] : $item['parent-uri']);
953 $parent = q("SELECT `guid`,`plink` FROM `item` WHERE `uri` = '%s' AND `uid` = %d", dbesc($parent_item), intval($item['uid']));
954 $attributes = ["ref" => $parent_item, "type" => "text/html",
955 "href" => $parent[0]['plink'],
956 "dfrn:diaspora_guid" => $parent[0]['guid']];
957 XML::addElement($doc, $entry, "thr:in-reply-to", "", $attributes);
960 // Add conversation data. This is used for OStatus
961 $conversation_href = System::baseUrl()."/display/".$owner["nick"]."/".$item["parent"];
962 $conversation_uri = $conversation_href;
964 if (isset($parent_item)) {
965 $r = dba::fetch_first("SELECT `conversation-uri`, `conversation-href` FROM `conversation` WHERE `item-uri` = ?", $item['parent-uri']);
966 if (DBM::is_result($r)) {
967 if ($r['conversation-uri'] != '') {
968 $conversation_uri = $r['conversation-uri'];
970 if ($r['conversation-href'] != '') {
971 $conversation_href = $r['conversation-href'];
977 "href" => $conversation_href,
978 "ref" => $conversation_uri];
980 XML::addElement($doc, $entry, "ostatus:conversation", $conversation_uri, $attributes);
982 XML::addElement($doc, $entry, "id", $item["uri"]);
983 XML::addElement($doc, $entry, "title", $item["title"]);
985 XML::addElement($doc, $entry, "published", DateTimeFormat::utc($item["created"] . "+00:00", DateTimeFormat::ATOM));
986 XML::addElement($doc, $entry, "updated", DateTimeFormat::utc($item["edited"] . "+00:00", DateTimeFormat::ATOM));
988 // "dfrn:env" is used to read the content
989 XML::addElement($doc, $entry, "dfrn:env", base64url_encode($body, true));
991 // The "content" field is not read by the receiver. We could remove it when the type is "text"
992 // We keep it at the moment, maybe there is some old version that doesn't read "dfrn:env"
993 XML::addElement($doc, $entry, "content", (($type == 'html') ? $htmlbody : $body), ["type" => $type]);
995 // We save this value in "plink". Maybe we should read it from there as well?
1001 ["rel" => "alternate", "type" => "text/html",
1002 "href" => System::baseUrl() . "/display/" . $item["guid"]]
1005 // "comment-allow" is some old fashioned stuff for old Friendica versions.
1006 // It is included in the rewritten code for completeness
1008 XML::addElement($doc, $entry, "dfrn:comment-allow", 1);
1011 if ($item['location']) {
1012 XML::addElement($doc, $entry, "dfrn:location", $item['location']);
1015 if ($item['coord']) {
1016 XML::addElement($doc, $entry, "georss:point", $item['coord']);
1019 if (($item['private']) || strlen($item['allow_cid']) || strlen($item['allow_gid']) || strlen($item['deny_cid']) || strlen($item['deny_gid'])) {
1020 XML::addElement($doc, $entry, "dfrn:private", (($item['private']) ? $item['private'] : 1));
1023 if ($item['extid']) {
1024 XML::addElement($doc, $entry, "dfrn:extid", $item['extid']);
1027 if ($item['bookmark']) {
1028 XML::addElement($doc, $entry, "dfrn:bookmark", "true");
1032 XML::addElement($doc, $entry, "statusnet:notice_info", "", ["local_id" => $item['id'], "source" => $item['app']]);
1035 XML::addElement($doc, $entry, "dfrn:diaspora_guid", $item["guid"]);
1037 // The signed text contains the content in Markdown, the sender handle and the signatur for the content
1038 // It is needed for relayed comments to Diaspora.
1039 if ($item['signed_text']) {
1040 $sign = base64_encode(json_encode(['signed_text' => $item['signed_text'],'signature' => $item['signature'],'signer' => $item['signer']]));
1041 XML::addElement($doc, $entry, "dfrn:diaspora_signature", $sign);
1044 XML::addElement($doc, $entry, "activity:verb", self::constructVerb($item));
1046 if ($item['object-type'] != "") {
1047 XML::addElement($doc, $entry, "activity:object-type", $item['object-type']);
1048 } elseif ($item['id'] == $item['parent']) {
1049 XML::addElement($doc, $entry, "activity:object-type", ACTIVITY_OBJ_NOTE);
1051 XML::addElement($doc, $entry, "activity:object-type", ACTIVITY_OBJ_COMMENT);
1054 $actobj = self::createActivity($doc, "activity:object", $item['object']);
1056 $entry->appendChild($actobj);
1059 $actarg = self::createActivity($doc, "activity:target", $item['target']);
1061 $entry->appendChild($actarg);
1064 $tags = Item::getFeedTags($item);
1066 /// @TODO Combine this with similar below if() block?
1068 foreach ($tags as $t) {
1069 if (($type != 'html') || ($t[0] != "@")) {
1070 XML::addElement($doc, $entry, "category", "", ["scheme" => "X-DFRN:".$t[0].":".$t[1], "term" => $t[2]]);
1076 foreach ($tags as $t) {
1078 $mentioned[$t[1]] = $t[1];
1083 foreach ($mentioned as $mention) {
1085 "SELECT `forum`, `prv` FROM `contact` WHERE `uid` = %d AND `nurl` = '%s'",
1086 intval($owner["uid"]),
1087 dbesc(normalise_link($mention))
1090 if (DBM::is_result($r) && ($r[0]["forum"] || $r[0]["prv"])) {
1096 ["rel" => "mentioned",
1097 "ostatus:object-type" => ACTIVITY_OBJ_GROUP,
1106 ["rel" => "mentioned",
1107 "ostatus:object-type" => ACTIVITY_OBJ_PERSON,
1113 self::getAttachment($doc, $entry, $item);
1119 * @brief encrypts data via AES
1121 * @param string $data The data that is to be encrypted
1122 * @param string $key The AES key
1124 * @return string encrypted data
1126 private static function aesEncrypt($data, $key)
1128 return openssl_encrypt($data, 'aes-128-ecb', $key, OPENSSL_RAW_DATA);
1132 * @brief decrypts data via AES
1134 * @param string $encrypted The encrypted data
1135 * @param string $key The AES key
1137 * @return string decrypted data
1139 public static function aesDecrypt($encrypted, $key)
1141 return openssl_decrypt($encrypted, 'aes-128-ecb', $key, OPENSSL_RAW_DATA);
1145 * @brief Delivers the atom content to the contacts
1147 * @param array $owner Owner record
1148 * @param array $contact Contact record of the receiver
1149 * @param string $atom Content that will be transmitted
1150 * @param bool $dissolve (to be documented)
1152 * @return int Deliver status. Negative values mean an error.
1153 * @todo Add array type-hint for $owner, $contact
1155 public static function deliver($owner, $contact, $atom, $dissolve = false)
1159 // At first try the Diaspora transport layer
1160 $ret = self::transmit($owner, $contact, $atom);
1162 logger('Delivery via Diaspora transport layer was successful with status ' . $ret);
1166 $idtosend = $orig_id = (($contact['dfrn-id']) ? $contact['dfrn-id'] : $contact['issued-id']);
1168 if ($contact['duplex'] && $contact['dfrn-id']) {
1169 $idtosend = '0:' . $orig_id;
1171 if ($contact['duplex'] && $contact['issued-id']) {
1172 $idtosend = '1:' . $orig_id;
1175 $rino = Config::get('system', 'rino_encrypt');
1176 $rino = intval($rino);
1178 logger("Local rino version: ". $rino, LOGGER_DEBUG);
1180 $ssl_val = intval(Config::get('system', 'ssl_policy'));
1184 case SSL_POLICY_FULL:
1185 $ssl_policy = 'full';
1187 case SSL_POLICY_SELFSIGN:
1188 $ssl_policy = 'self';
1190 case SSL_POLICY_NONE:
1192 $ssl_policy = 'none';
1196 $url = $contact['notify'] . '&dfrn_id=' . $idtosend . '&dfrn_version=' . DFRN_PROTOCOL_VERSION . (($rino) ? '&rino='.$rino : '');
1198 logger('dfrn_deliver: ' . $url);
1200 $ret = Network::curl($url);
1202 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
1203 Contact::markForArchival($contact);
1204 return -2; // timed out
1207 $xml = $ret['body'];
1209 $curl_stat = $a->get_curl_code();
1210 if (empty($curl_stat)) {
1211 Contact::markForArchival($contact);
1212 return -3; // timed out
1215 logger('dfrn_deliver: ' . $xml, LOGGER_DATA);
1218 Contact::markForArchival($contact);
1222 if (strpos($xml, '<?xml') === false) {
1223 logger('dfrn_deliver: no valid XML returned');
1224 logger('dfrn_deliver: returned XML: ' . $xml, LOGGER_DATA);
1225 Contact::markForArchival($contact);
1229 $res = XML::parseString($xml);
1231 if ((intval($res->status) != 0) || !strlen($res->challenge) || !strlen($res->dfrn_id)) {
1232 Contact::markForArchival($contact);
1233 return ($res->status ? $res->status : 3);
1237 $sent_dfrn_id = hex2bin((string) $res->dfrn_id);
1238 $challenge = hex2bin((string) $res->challenge);
1239 $perm = (($res->perm) ? $res->perm : null);
1240 $dfrn_version = (float) (($res->dfrn_version) ? $res->dfrn_version : 2.0);
1241 $rino_remote_version = intval($res->rino);
1242 $page = (($owner['page-flags'] == PAGE_COMMUNITY) ? 1 : 0);
1244 logger("Remote rino version: ".$rino_remote_version." for ".$contact["url"], LOGGER_DEBUG);
1246 if ($owner['page-flags'] == PAGE_PRVGROUP) {
1250 $final_dfrn_id = '';
1253 if ((($perm == 'rw') && (! intval($contact['writable'])))
1254 || (($perm == 'r') && (intval($contact['writable'])))
1257 "update contact set writable = %d where id = %d",
1258 intval(($perm == 'rw') ? 1 : 0),
1259 intval($contact['id'])
1261 $contact['writable'] = (string) 1 - intval($contact['writable']);
1265 if (($contact['duplex'] && strlen($contact['pubkey']))
1266 || ($owner['page-flags'] == PAGE_COMMUNITY && strlen($contact['pubkey']))
1267 || ($contact['rel'] == CONTACT_IS_SHARING && strlen($contact['pubkey']))
1269 openssl_public_decrypt($sent_dfrn_id, $final_dfrn_id, $contact['pubkey']);
1270 openssl_public_decrypt($challenge, $postvars['challenge'], $contact['pubkey']);
1272 openssl_private_decrypt($sent_dfrn_id, $final_dfrn_id, $contact['prvkey']);
1273 openssl_private_decrypt($challenge, $postvars['challenge'], $contact['prvkey']);
1276 $final_dfrn_id = substr($final_dfrn_id, 0, strpos($final_dfrn_id, '.'));
1278 if (strpos($final_dfrn_id, ':') == 1) {
1279 $final_dfrn_id = substr($final_dfrn_id, 2);
1282 if ($final_dfrn_id != $orig_id) {
1283 logger('dfrn_deliver: wrong dfrn_id.');
1284 // did not decode properly - cannot trust this site
1285 Contact::markForArchival($contact);
1289 $postvars['dfrn_id'] = $idtosend;
1290 $postvars['dfrn_version'] = DFRN_PROTOCOL_VERSION;
1292 $postvars['dissolve'] = '1';
1295 if ((($contact['rel']) && ($contact['rel'] != CONTACT_IS_SHARING) && (! $contact['blocked'])) || ($owner['page-flags'] == PAGE_COMMUNITY)) {
1296 $postvars['data'] = $atom;
1297 $postvars['perm'] = 'rw';
1299 $postvars['data'] = str_replace('<dfrn:comment-allow>1', '<dfrn:comment-allow>0', $atom);
1300 $postvars['perm'] = 'r';
1303 $postvars['ssl_policy'] = $ssl_policy;
1306 $postvars['page'] = $page;
1310 if ($rino > 0 && $rino_remote_version > 0 && (! $dissolve)) {
1311 logger('rino version: '. $rino_remote_version);
1313 switch ($rino_remote_version) {
1315 $key = openssl_random_pseudo_bytes(16);
1316 $data = self::aesEncrypt($postvars['data'], $key);
1319 logger("rino: invalid requested version '$rino_remote_version'");
1320 Contact::markForArchival($contact);
1324 $postvars['rino'] = $rino_remote_version;
1325 $postvars['data'] = bin2hex($data);
1327 if ($dfrn_version >= 2.1) {
1328 if (($contact['duplex'] && strlen($contact['pubkey']))
1329 || ($owner['page-flags'] == PAGE_COMMUNITY && strlen($contact['pubkey']))
1330 || ($contact['rel'] == CONTACT_IS_SHARING && strlen($contact['pubkey']))
1332 openssl_public_encrypt($key, $postvars['key'], $contact['pubkey']);
1334 openssl_private_encrypt($key, $postvars['key'], $contact['prvkey']);
1337 if (($contact['duplex'] && strlen($contact['prvkey'])) || ($owner['page-flags'] == PAGE_COMMUNITY)) {
1338 openssl_private_encrypt($key, $postvars['key'], $contact['prvkey']);
1340 openssl_public_encrypt($key, $postvars['key'], $contact['pubkey']);
1344 logger('md5 rawkey ' . md5($postvars['key']));
1346 $postvars['key'] = bin2hex($postvars['key']);
1350 logger('dfrn_deliver: ' . "SENDING: " . print_r($postvars, true), LOGGER_DATA);
1352 $xml = Network::post($contact['notify'], $postvars);
1354 logger('dfrn_deliver: ' . "RECEIVED: " . $xml, LOGGER_DATA);
1356 $curl_stat = $a->get_curl_code();
1357 if (empty($curl_stat) || empty($xml)) {
1358 Contact::markForArchival($contact);
1359 return -9; // timed out
1362 if (($curl_stat == 503) && stristr($a->get_curl_headers(), 'retry-after')) {
1363 Contact::markForArchival($contact);
1367 if (strpos($xml, '<?xml') === false) {
1368 logger('dfrn_deliver: phase 2: no valid XML returned');
1369 logger('dfrn_deliver: phase 2: returned XML: ' . $xml, LOGGER_DATA);
1370 Contact::markForArchival($contact);
1374 $res = XML::parseString($xml);
1376 if (!isset($res->status)) {
1377 Contact::markForArchival($contact);
1381 // Possibly old servers had returned an empty value when everything was okay
1382 if (empty($res->status)) {
1386 if (!empty($res->message)) {
1387 logger('Delivery returned status '.$res->status.' - '.$res->message, LOGGER_DEBUG);
1390 if (($res->status >= 200) && ($res->status <= 299)) {
1391 Contact::unmarkForArchival($contact);
1394 return intval($res->status);
1398 * @brief Transmits atom content to the contacts via the Diaspora transport layer
1400 * @param array $owner Owner record
1401 * @param array $contact Contact record of the receiver
1402 * @param string $atom Content that will be transmitted
1404 * @return int Deliver status. Negative values mean an error.
1406 public static function transmit($owner, $contact, $atom, $public_batch = false)
1410 if (!$public_batch) {
1411 if (empty($contact['addr'])) {
1412 logger('Empty contact handle for ' . $contact['id'] . ' - ' . $contact['url'] . ' - trying to update it.');
1413 if (Contact::updateFromProbe($contact['id'])) {
1414 $new_contact = dba::selectFirst('contact', ['addr'], ['id' => $contact['id']]);
1415 $contact['addr'] = $new_contact['addr'];
1418 if (empty($contact['addr'])) {
1419 logger('Unable to find contact handle for ' . $contact['id'] . ' - ' . $contact['url']);
1420 Contact::markForArchival($contact);
1425 $fcontact = Diaspora::personByHandle($contact['addr']);
1426 if (empty($fcontact)) {
1427 logger('Unable to find contact details for ' . $contact['id'] . ' - ' . $contact['addr']);
1428 Contact::markForArchival($contact);
1431 $pubkey = $fcontact['pubkey'];
1436 $envelope = Diaspora::buildMessage($atom, $owner, $contact, $owner['uprvkey'], $pubkey, $public_batch);
1438 // Create the endpoint for public posts. This is some WIP and should later be added to the probing
1439 if ($public_batch && empty($contact["batch"])) {
1440 $parts = parse_url($contact["notify"]);
1441 $path_parts = explode('/', $parts['path']);
1442 array_pop($path_parts);
1443 $parts['path'] = implode('/', $path_parts);
1444 $contact["batch"] = Network::unparseURL($parts);
1447 $dest_url = ($public_batch ? $contact["batch"] : $contact["notify"]);
1449 $content_type = ($public_batch ? "application/magic-envelope+xml" : "application/json");
1451 $xml = Network::post($dest_url, $envelope, ["Content-Type: ".$content_type]);
1453 $curl_stat = $a->get_curl_code();
1454 if (empty($curl_stat) || empty($xml)) {
1455 logger('Empty answer from ' . $contact['id'] . ' - ' . $dest_url);
1456 Contact::markForArchival($contact);
1457 return -9; // timed out
1460 if (($curl_stat == 503) && (stristr($a->get_curl_headers(), 'retry-after'))) {
1461 Contact::markForArchival($contact);
1465 if (strpos($xml, '<?xml') === false) {
1466 logger('No valid XML returned from ' . $contact['id'] . ' - ' . $dest_url);
1467 logger('Returned XML: ' . $xml, LOGGER_DATA);
1468 Contact::markForArchival($contact);
1472 $res = XML::parseString($xml);
1474 if (empty($res->status)) {
1475 Contact::markForArchival($contact);
1479 if (!empty($res->message)) {
1480 logger('Transmit to ' . $dest_url . ' returned status '.$res->status.' - '.$res->message, LOGGER_DEBUG);
1483 if (($res->status >= 200) && ($res->status <= 299)) {
1484 Contact::unmarkForArchival($contact);
1487 return intval($res->status);
1491 * @brief Add new birthday event for this person
1493 * @param array $contact Contact record
1494 * @param string $birthday Birthday of the contact
1496 * @todo Add array type-hint for $contact
1498 private static function birthdayEvent($contact, $birthday)
1500 // Check for duplicates
1502 "SELECT `id` FROM `event` WHERE `uid` = %d AND `cid` = %d AND `start` = '%s' AND `type` = '%s' LIMIT 1",
1503 intval($contact['uid']),
1504 intval($contact['id']),
1505 dbesc(DateTimeFormat::utc($birthday)),
1509 if (DBM::is_result($r)) {
1513 logger('updating birthday: ' . $birthday . ' for contact ' . $contact['id']);
1515 $bdtext = L10n::t('%s\'s birthday', $contact['name']);
1516 $bdtext2 = L10n::t('Happy Birthday %s', ' [url=' . $contact['url'] . ']' . $contact['name'] . '[/url]');
1519 "INSERT INTO `event` (`uid`,`cid`,`created`,`edited`,`start`,`finish`,`summary`,`desc`,`type`)
1520 VALUES ( %d, %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s') ",
1521 intval($contact['uid']),
1522 intval($contact['id']),
1523 dbesc(DateTimeFormat::utcNow()),
1524 dbesc(DateTimeFormat::utcNow()),
1525 dbesc(DateTimeFormat::utc($birthday)),
1526 dbesc(DateTimeFormat::utc($birthday . ' + 1 day ')),
1534 * @brief Fetch the author data from head or entry items
1536 * @param object $xpath XPath object
1537 * @param object $context In which context should the data be searched
1538 * @param array $importer Record of the importer user mixed with contact of the content
1539 * @param string $element Element name from which the data is fetched
1540 * @param bool $onlyfetch Should the data only be fetched or should it update the contact record as well
1541 * @param string $xml optional, default empty
1543 * @return array Relevant data of the author
1544 * @todo Find good type-hints for all parameter
1546 private static function fetchauthor($xpath, $context, $importer, $element, $onlyfetch, $xml = "")
1549 $author["name"] = $xpath->evaluate($element."/atom:name/text()", $context)->item(0)->nodeValue;
1550 $author["link"] = $xpath->evaluate($element."/atom:uri/text()", $context)->item(0)->nodeValue;
1552 $contact_old = dba::fetch_first("SELECT `id`, `uid`, `url`, `network`, `avatar-date`, `avatar`, `name-date`, `uri-date`, `addr`,
1553 `name`, `nick`, `about`, `location`, `keywords`, `xmpp`, `bdyear`, `bd`, `hidden`, `contact-type`
1554 FROM `contact` WHERE `uid` = ? AND `nurl` = ? AND `network` != ?",
1555 $importer["importer_uid"],
1556 normalise_link($author["link"]),
1560 if (DBM::is_result($contact_old)) {
1561 $author["contact-id"] = $contact_old["id"];
1562 $author["network"] = $contact_old["network"];
1565 logger("Contact ".$author["link"]." wasn't found for user ".$importer["importer_uid"]." XML: ".$xml, LOGGER_DEBUG);
1568 $author["contact-id"] = $importer["id"];
1569 $author["network"] = $importer["network"];
1573 // Until now we aren't serving different sizes - but maybe later
1575 /// @todo check if "avatar" or "photo" would be the best field in the specification
1576 $avatars = $xpath->query($element . "/atom:link[@rel='avatar']", $context);
1577 foreach ($avatars as $avatar) {
1580 foreach ($avatar->attributes as $attributes) {
1581 /// @TODO Rewrite these similar if() to one switch
1582 if ($attributes->name == "href") {
1583 $href = $attributes->textContent;
1585 if ($attributes->name == "width") {
1586 $width = $attributes->textContent;
1588 if ($attributes->name == "updated") {
1589 $author["avatar-date"] = $attributes->textContent;
1592 if (($width > 0) && ($href != "")) {
1593 $avatarlist[$width] = $href;
1597 if (count($avatarlist) > 0) {
1598 krsort($avatarlist);
1599 $author["avatar"] = current($avatarlist);
1602 if (DBM::is_result($contact_old) && !$onlyfetch) {
1603 logger("Check if contact details for contact " . $contact_old["id"] . " (" . $contact_old["nick"] . ") have to be updated.", LOGGER_DEBUG);
1605 $poco = ["url" => $contact_old["url"]];
1607 // When was the last change to name or uri?
1608 $name_element = $xpath->query($element . "/atom:name", $context)->item(0);
1609 foreach ($name_element->attributes as $attributes) {
1610 if ($attributes->name == "updated") {
1611 $poco["name-date"] = $attributes->textContent;
1615 $link_element = $xpath->query($element . "/atom:link", $context)->item(0);
1616 foreach ($link_element->attributes as $attributes) {
1617 if ($attributes->name == "updated") {
1618 $poco["uri-date"] = $attributes->textContent;
1622 // Update contact data
1623 $value = $xpath->evaluate($element . "/dfrn:handle/text()", $context)->item(0)->nodeValue;
1625 $poco["addr"] = $value;
1628 $value = $xpath->evaluate($element . "/poco:displayName/text()", $context)->item(0)->nodeValue;
1630 $poco["name"] = $value;
1633 $value = $xpath->evaluate($element . "/poco:preferredUsername/text()", $context)->item(0)->nodeValue;
1635 $poco["nick"] = $value;
1638 $value = $xpath->evaluate($element . "/poco:note/text()", $context)->item(0)->nodeValue;
1640 $poco["about"] = $value;
1643 $value = $xpath->evaluate($element . "/poco:address/poco:formatted/text()", $context)->item(0)->nodeValue;
1645 $poco["location"] = $value;
1648 /// @todo Only search for elements with "poco:type" = "xmpp"
1649 $value = $xpath->evaluate($element . "/poco:ims/poco:value/text()", $context)->item(0)->nodeValue;
1651 $poco["xmpp"] = $value;
1654 /// @todo Add support for the following fields that we don't support by now in the contact table:
1655 /// - poco:utcOffset
1661 // If the "hide" element is present then the profile isn't searchable.
1662 $hide = intval($xpath->evaluate($element . "/dfrn:hide/text()", $context)->item(0)->nodeValue == "true");
1664 logger("Hidden status for contact " . $contact_old["url"] . ": " . $hide, LOGGER_DEBUG);
1666 // If the contact isn't searchable then set the contact to "hidden".
1667 // Problem: This can be manually overridden by the user.
1669 $contact_old["hidden"] = true;
1672 // Save the keywords into the contact table
1674 $tagelements = $xpath->evaluate($element . "/poco:tags/text()", $context);
1675 foreach ($tagelements as $tag) {
1676 $tags[$tag->nodeValue] = $tag->nodeValue;
1680 $poco["keywords"] = implode(", ", $tags);
1683 // "dfrn:birthday" contains the birthday converted to UTC
1684 $birthday = $xpath->evaluate($element . "/dfrn:birthday/text()", $context)->item(0)->nodeValue;
1686 if (strtotime($birthday) > time()) {
1687 $bd_timestamp = strtotime($birthday);
1689 $poco["bdyear"] = date("Y", $bd_timestamp);
1692 // "poco:birthday" is the birthday in the format "yyyy-mm-dd"
1693 $value = $xpath->evaluate($element . "/poco:birthday/text()", $context)->item(0)->nodeValue;
1695 if (!in_array($value, ["", "0000-00-00", "0001-01-01"])) {
1696 $bdyear = date("Y");
1697 $value = str_replace("0000", $bdyear, $value);
1699 if (strtotime($value) < time()) {
1700 $value = str_replace($bdyear, $bdyear + 1, $value);
1701 $bdyear = $bdyear + 1;
1704 $poco["bd"] = $value;
1707 $contact = array_merge($contact_old, $poco);
1709 if ($contact_old["bdyear"] != $contact["bdyear"]) {
1710 self::birthdayEvent($contact, $birthday);
1713 // Get all field names
1715 foreach ($contact_old as $field => $data) {
1716 $fields[$field] = $data;
1719 unset($fields["id"]);
1720 unset($fields["uid"]);
1721 unset($fields["url"]);
1722 unset($fields["avatar-date"]);
1723 unset($fields["avatar"]);
1724 unset($fields["name-date"]);
1725 unset($fields["uri-date"]);
1728 // Update check for this field has to be done differently
1729 $datefields = ["name-date", "uri-date"];
1730 foreach ($datefields as $field) {
1731 if (strtotime($contact[$field]) > strtotime($contact_old[$field])) {
1732 logger("Difference for contact " . $contact["id"] . " in field '" . $field . "'. New value: '" . $contact[$field] . "', old value '" . $contact_old[$field] . "'", LOGGER_DEBUG);
1737 foreach ($fields as $field => $data) {
1738 if ($contact[$field] != $contact_old[$field]) {
1739 logger("Difference for contact " . $contact["id"] . " in field '" . $field . "'. New value: '" . $contact[$field] . "', old value '" . $contact_old[$field] . "'", LOGGER_DEBUG);
1745 logger("Update contact data for contact " . $contact["id"] . " (" . $contact["nick"] . ")", LOGGER_DEBUG);
1748 "UPDATE `contact` SET `name` = '%s', `nick` = '%s', `about` = '%s', `location` = '%s',
1749 `addr` = '%s', `keywords` = '%s', `bdyear` = '%s', `bd` = '%s', `hidden` = %d,
1750 `xmpp` = '%s', `name-date` = '%s', `uri-date` = '%s'
1751 WHERE `id` = %d AND `network` = '%s'",
1752 dbesc($contact["name"]), dbesc($contact["nick"]), dbesc($contact["about"]), dbesc($contact["location"]),
1753 dbesc($contact["addr"]), dbesc($contact["keywords"]), dbesc($contact["bdyear"]),
1754 dbesc($contact["bd"]), intval($contact["hidden"]), dbesc($contact["xmpp"]),
1755 dbesc(DBM::date($contact["name-date"])), dbesc(DBM::date($contact["uri-date"])),
1756 intval($contact["id"]), dbesc($contact["network"])
1760 Contact::updateAvatar(
1762 $importer['importer_uid'],
1764 (strtotime($contact['avatar-date']) > strtotime($contact_old['avatar-date']) || ($author['avatar'] != $contact_old['avatar']))
1768 * The generation is a sign for the reliability of the provided data.
1769 * It is used in the socgraph.php to prevent that old contact data
1770 * that was relayed over several servers can overwrite contact
1771 * data that we received directly.
1774 $poco["generation"] = 2;
1775 $poco["photo"] = $author["avatar"];
1776 $poco["hide"] = $hide;
1777 $poco["contact-type"] = $contact["contact-type"];
1778 $gcid = GContact::update($poco);
1780 GContact::link($gcid, $importer["importer_uid"], $contact["id"]);
1787 * @brief Transforms activity objects into an XML string
1789 * @param object $xpath XPath object
1790 * @param object $activity Activity object
1791 * @param string $element element name
1793 * @return string XML string
1794 * @todo Find good type-hints for all parameter
1796 private static function transformActivity($xpath, $activity, $element)
1798 if (!is_object($activity)) {
1802 $obj_doc = new DOMDocument("1.0", "utf-8");
1803 $obj_doc->formatOutput = true;
1805 $obj_element = $obj_doc->createElementNS(NAMESPACE_ATOM1, $element);
1807 $activity_type = $xpath->query("activity:object-type/text()", $activity)->item(0)->nodeValue;
1808 XML::addElement($obj_doc, $obj_element, "type", $activity_type);
1810 $id = $xpath->query("atom:id", $activity)->item(0);
1811 if (is_object($id)) {
1812 $obj_element->appendChild($obj_doc->importNode($id, true));
1815 $title = $xpath->query("atom:title", $activity)->item(0);
1816 if (is_object($title)) {
1817 $obj_element->appendChild($obj_doc->importNode($title, true));
1820 $links = $xpath->query("atom:link", $activity);
1821 if (is_object($links)) {
1822 foreach ($links as $link) {
1823 $obj_element->appendChild($obj_doc->importNode($link, true));
1827 $content = $xpath->query("atom:content", $activity)->item(0);
1828 if (is_object($content)) {
1829 $obj_element->appendChild($obj_doc->importNode($content, true));
1832 $obj_doc->appendChild($obj_element);
1834 $objxml = $obj_doc->saveXML($obj_element);
1836 /// @todo This isn't totally clean. We should find a way to transform the namespaces
1837 $objxml = str_replace("<".$element.' xmlns="http://www.w3.org/2005/Atom">', "<".$element.">", $objxml);
1842 * @brief Processes the mail elements
1844 * @param object $xpath XPath object
1845 * @param object $mail mail elements
1846 * @param array $importer Record of the importer user mixed with contact of the content
1848 * @todo Find good type-hints for all parameter
1850 private static function processMail($xpath, $mail, $importer)
1852 logger("Processing mails");
1854 /// @TODO Rewrite this to one statement
1856 $msg["uid"] = $importer["importer_uid"];
1857 $msg["from-name"] = $xpath->query("dfrn:sender/dfrn:name/text()", $mail)->item(0)->nodeValue;
1858 $msg["from-url"] = $xpath->query("dfrn:sender/dfrn:uri/text()", $mail)->item(0)->nodeValue;
1859 $msg["from-photo"] = $xpath->query("dfrn:sender/dfrn:avatar/text()", $mail)->item(0)->nodeValue;
1860 $msg["contact-id"] = $importer["id"];
1861 $msg["uri"] = $xpath->query("dfrn:id/text()", $mail)->item(0)->nodeValue;
1862 $msg["parent-uri"] = $xpath->query("dfrn:in-reply-to/text()", $mail)->item(0)->nodeValue;
1863 $msg["created"] = DateTimeFormat::utc($xpath->query("dfrn:sentdate/text()", $mail)->item(0)->nodeValue);
1864 $msg["title"] = $xpath->query("dfrn:subject/text()", $mail)->item(0)->nodeValue;
1865 $msg["body"] = $xpath->query("dfrn:content/text()", $mail)->item(0)->nodeValue;
1867 $msg["replied"] = 0;
1869 dba::insert('mail', $msg);
1871 // send notifications.
1872 /// @TODO Arange this mess
1874 "type" => NOTIFY_MAIL,
1875 "notify_flags" => $importer["notify-flags"],
1876 "language" => $importer["language"],
1877 "to_name" => $importer["username"],
1878 "to_email" => $importer["email"],
1879 "uid" => $importer["importer_uid"],
1881 "source_name" => $msg["from-name"],
1882 "source_link" => $importer["url"],
1883 "source_photo" => $importer["thumb"],
1884 "verb" => ACTIVITY_POST,
1888 notification($notif_params);
1890 logger("Mail is processed, notification was sent.");
1894 * @brief Processes the suggestion elements
1896 * @param object $xpath XPath object
1897 * @param object $suggestion suggestion elements
1898 * @param array $importer Record of the importer user mixed with contact of the content
1900 * @todo Find good type-hints for all parameter
1902 private static function processSuggestion($xpath, $suggestion, $importer)
1906 logger("Processing suggestions");
1908 /// @TODO Rewrite this to one statement
1910 $suggest["uid"] = $importer["importer_uid"];
1911 $suggest["cid"] = $importer["id"];
1912 $suggest["url"] = $xpath->query("dfrn:url/text()", $suggestion)->item(0)->nodeValue;
1913 $suggest["name"] = $xpath->query("dfrn:name/text()", $suggestion)->item(0)->nodeValue;
1914 $suggest["photo"] = $xpath->query("dfrn:photo/text()", $suggestion)->item(0)->nodeValue;
1915 $suggest["request"] = $xpath->query("dfrn:request/text()", $suggestion)->item(0)->nodeValue;
1916 $suggest["body"] = $xpath->query("dfrn:note/text()", $suggestion)->item(0)->nodeValue;
1918 // Does our member already have a friend matching this description?
1921 "SELECT `id` FROM `contact` WHERE `name` = '%s' AND `nurl` = '%s' AND `uid` = %d LIMIT 1",
1922 dbesc($suggest["name"]),
1923 dbesc(normalise_link($suggest["url"])),
1924 intval($suggest["uid"])
1928 * The valid result means the friend we're about to send a friend
1929 * suggestion already has them in their contact, which means no further
1930 * action is required.
1932 * @see https://github.com/friendica/friendica/pull/3254#discussion_r107315246
1934 if (DBM::is_result($r)) {
1938 // Do we already have an fcontact record for this person?
1942 "SELECT `id` FROM `fcontact` WHERE `url` = '%s' AND `name` = '%s' AND `request` = '%s' LIMIT 1",
1943 dbesc($suggest["url"]),
1944 dbesc($suggest["name"]),
1945 dbesc($suggest["request"])
1947 if (DBM::is_result($r)) {
1950 // OK, we do. Do we already have an introduction for this person ?
1952 "SELECT `id` FROM `intro` WHERE `uid` = %d AND `fid` = %d LIMIT 1",
1953 intval($suggest["uid"]),
1958 * The valid result means the friend we're about to send a friend
1959 * suggestion already has them in their contact, which means no further
1960 * action is required.
1962 * @see https://github.com/friendica/friendica/pull/3254#discussion_r107315246
1964 if (DBM::is_result($r)) {
1970 "INSERT INTO `fcontact` (`name`,`url`,`photo`,`request`) VALUES ('%s', '%s', '%s', '%s')",
1971 dbesc($suggest["name"]),
1972 dbesc($suggest["url"]),
1973 dbesc($suggest["photo"]),
1974 dbesc($suggest["request"])
1978 "SELECT `id` FROM `fcontact` WHERE `url` = '%s' AND `name` = '%s' AND `request` = '%s' LIMIT 1",
1979 dbesc($suggest["url"]),
1980 dbesc($suggest["name"]),
1981 dbesc($suggest["request"])
1985 * If no record in fcontact is found, below INSERT statement will not
1986 * link an introduction to it.
1988 if (!DBM::is_result($r)) {
1989 // database record did not get created. Quietly give up.
1995 $hash = random_string();
1998 "INSERT INTO `intro` (`uid`, `fid`, `contact-id`, `note`, `hash`, `datetime`, `blocked`)
1999 VALUES(%d, %d, %d, '%s', '%s', '%s', %d)",
2000 intval($suggest["uid"]),
2002 intval($suggest["cid"]),
2003 dbesc($suggest["body"]),
2005 dbesc(DateTimeFormat::utcNow()),
2011 "type" => NOTIFY_SUGGEST,
2012 "notify_flags" => $importer["notify-flags"],
2013 "language" => $importer["language"],
2014 "to_name" => $importer["username"],
2015 "to_email" => $importer["email"],
2016 "uid" => $importer["importer_uid"],
2018 "link" => System::baseUrl()."/notifications/intros",
2019 "source_name" => $importer["name"],
2020 "source_link" => $importer["url"],
2021 "source_photo" => $importer["photo"],
2022 "verb" => ACTIVITY_REQ_FRIEND,
2030 * @brief Processes the relocation elements
2032 * @param object $xpath XPath object
2033 * @param object $relocation relocation elements
2034 * @param array $importer Record of the importer user mixed with contact of the content
2036 * @todo Find good type-hints for all parameter
2038 private static function processRelocation($xpath, $relocation, $importer)
2040 logger("Processing relocations");
2042 /// @TODO Rewrite this to one statement
2044 $relocate["uid"] = $importer["importer_uid"];
2045 $relocate["cid"] = $importer["id"];
2046 $relocate["url"] = $xpath->query("dfrn:url/text()", $relocation)->item(0)->nodeValue;
2047 $relocate["addr"] = $xpath->query("dfrn:addr/text()", $relocation)->item(0)->nodeValue;
2048 $relocate["name"] = $xpath->query("dfrn:name/text()", $relocation)->item(0)->nodeValue;
2049 $relocate["avatar"] = $xpath->query("dfrn:avatar/text()", $relocation)->item(0)->nodeValue;
2050 $relocate["photo"] = $xpath->query("dfrn:photo/text()", $relocation)->item(0)->nodeValue;
2051 $relocate["thumb"] = $xpath->query("dfrn:thumb/text()", $relocation)->item(0)->nodeValue;
2052 $relocate["micro"] = $xpath->query("dfrn:micro/text()", $relocation)->item(0)->nodeValue;
2053 $relocate["request"] = $xpath->query("dfrn:request/text()", $relocation)->item(0)->nodeValue;
2054 $relocate["confirm"] = $xpath->query("dfrn:confirm/text()", $relocation)->item(0)->nodeValue;
2055 $relocate["notify"] = $xpath->query("dfrn:notify/text()", $relocation)->item(0)->nodeValue;
2056 $relocate["poll"] = $xpath->query("dfrn:poll/text()", $relocation)->item(0)->nodeValue;
2057 $relocate["sitepubkey"] = $xpath->query("dfrn:sitepubkey/text()", $relocation)->item(0)->nodeValue;
2059 if (($relocate["avatar"] == "") && ($relocate["photo"] != "")) {
2060 $relocate["avatar"] = $relocate["photo"];
2063 if ($relocate["addr"] == "") {
2064 $relocate["addr"] = preg_replace("=(https?://)(.*)/profile/(.*)=ism", "$3@$2", $relocate["url"]);
2069 "SELECT `photo`, `url` FROM `contact` WHERE `id` = %d AND `uid` = %d;",
2070 intval($importer["id"]),
2071 intval($importer["importer_uid"])
2074 if (!DBM::is_result($r)) {
2075 logger("Query failed to execute, no result returned in " . __FUNCTION__);
2081 // Update the gcontact entry
2082 $relocate["server_url"] = preg_replace("=(https?://)(.*)/profile/(.*)=ism", "$1$2", $relocate["url"]);
2084 $fields = ['name' => $relocate["name"], 'photo' => $relocate["avatar"],
2085 'url' => $relocate["url"], 'nurl' => normalise_link($relocate["url"]),
2086 'addr' => $relocate["addr"], 'connect' => $relocate["addr"],
2087 'notify' => $relocate["notify"], 'server_url' => $relocate["server_url"]];
2088 dba::update('gcontact', $fields, ['nurl' => normalise_link($old["url"])]);
2090 // Update the contact table. We try to find every entry.
2091 $fields = ['name' => $relocate["name"], 'avatar' => $relocate["avatar"],
2092 'url' => $relocate["url"], 'nurl' => normalise_link($relocate["url"]),
2093 'addr' => $relocate["addr"], 'request' => $relocate["request"],
2094 'confirm' => $relocate["confirm"], 'notify' => $relocate["notify"],
2095 'poll' => $relocate["poll"], 'site-pubkey' => $relocate["sitepubkey"]];
2096 $condition = ["(`id` = ?) OR (`nurl` = ?)", $importer["id"], normalise_link($old["url"])];
2097 dba::update('contact', $fields, $condition);
2099 // @TODO No dba:update here?
2100 dba::update('contact', $fields, $condition);
2102 Contact::updateAvatar($relocate["avatar"], $importer["importer_uid"], $importer["id"], true);
2104 logger('Contacts are updated.');
2107 // This is an extreme performance killer
2108 Item::update(['owner-link' => $relocate["url"]], ['owner-link' => $old["url"], 'uid' => $importer["importer_uid"]]);
2109 Item::update(['author-link' => $relocate["url"]], ['author-link' => $old["url"], 'uid' => $importer["importer_uid"]]);
2111 logger('Items are updated.');
2114 /// merge with current record, current contents have priority
2115 /// update record, set url-updated
2116 /// update profile photos
2117 /// schedule a scan?
2122 * @brief Updates an item
2124 * @param array $current the current item record
2125 * @param array $item the new item record
2126 * @param array $importer Record of the importer user mixed with contact of the content
2127 * @param int $entrytype Is it a toplevel entry, a comment or a relayed comment?
2129 * @todo set proper type-hints (array?)
2131 private static function updateContent($current, $item, $importer, $entrytype)
2135 if (self::isEditedTimestampNewer($current, $item)) {
2136 // do not accept (ignore) an earlier edit than one we currently have.
2137 if (DateTimeFormat::utc($item["edited"]) < $current["edited"]) {
2141 $fields = ['title' => defaults($item, 'title', ''), 'body' => defaults($item, 'body', ''),
2142 'tag' => defaults($item, 'tag', ''), 'changed' => DateTimeFormat::utcNow(),
2143 'edited' => DateTimeFormat::utc($item["edited"])];
2145 $condition = ["`uri` = ? AND `uid` IN (0, ?)", $item["uri"], $importer["importer_uid"]];
2146 Item::update($fields, $condition);
2150 if ($entrytype == DFRN_REPLY_RC) {
2151 Worker::add(PRIORITY_HIGH, "Notifier", "comment-import", $current["id"]);
2158 * @brief Detects the entry type of the item
2160 * @param array $importer Record of the importer user mixed with contact of the content
2161 * @param array $item the new item record
2163 * @return int Is it a toplevel entry, a comment or a relayed comment?
2164 * @todo set proper type-hints (array?)
2166 private static function getEntryType($importer, $item)
2168 if ($item["parent-uri"] != $item["uri"]) {
2171 if ($importer["page-flags"] == PAGE_COMMUNITY || $importer["page-flags"] == PAGE_PRVGROUP) {
2174 logger("possible community action");
2176 $sql_extra = " AND `contact`.`self` AND `item`.`wall` ";
2179 // was the top-level post for this action written by somebody on this site?
2180 // Specifically, the recipient?
2182 $is_a_remote_action = false;
2185 "SELECT `item`.`parent-uri` FROM `item`
2186 WHERE `item`.`uri` = '%s'
2188 dbesc($item["parent-uri"])
2190 if (DBM::is_result($r)) {
2192 "SELECT `item`.`forum_mode`, `item`.`wall` FROM `item`
2193 INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
2194 WHERE `item`.`uri` = '%s' AND (`item`.`parent-uri` = '%s' OR `item`.`thr-parent` = '%s')
2195 AND `item`.`uid` = %d
2198 dbesc($r[0]["parent-uri"]),
2199 dbesc($r[0]["parent-uri"]),
2200 dbesc($r[0]["parent-uri"]),
2201 intval($importer["importer_uid"])
2203 if (DBM::is_result($r)) {
2204 $is_a_remote_action = true;
2209 * Does this have the characteristics of a community or private group action?
2210 * If it's an action to a wall post on a community/prvgroup page it's a
2211 * valid community action. Also forum_mode makes it valid for sure.
2212 * If neither, it's not.
2214 if ($is_a_remote_action && $community && (!$r[0]["forum_mode"]) && (!$r[0]["wall"])) {
2215 $is_a_remote_action = false;
2216 logger("not a community action");
2219 if ($is_a_remote_action) {
2220 return DFRN_REPLY_RC;
2225 return DFRN_TOP_LEVEL;
2230 * @brief Send a "poke"
2232 * @param array $item the new item record
2233 * @param array $importer Record of the importer user mixed with contact of the content
2234 * @param int $posted_id The record number of item record that was just posted
2236 * @todo set proper type-hints (array?)
2238 private static function doPoke($item, $importer, $posted_id)
2240 $verb = urldecode(substr($item["verb"], strpos($item["verb"], "#")+1));
2244 $xo = XML::parseString($item["object"], false);
2246 if (($xo->type == ACTIVITY_OBJ_PERSON) && ($xo->id)) {
2247 // somebody was poked/prodded. Was it me?
2248 foreach ($xo->link as $l) {
2249 $atts = $l->attributes();
2250 switch ($atts["rel"]) {
2252 $Blink = $atts["href"];
2259 if ($Blink && link_compare($Blink, System::baseUrl() . "/profile/" . $importer["nickname"])) {
2260 // send a notification
2263 "type" => NOTIFY_POKE,
2264 "notify_flags" => $importer["notify-flags"],
2265 "language" => $importer["language"],
2266 "to_name" => $importer["username"],
2267 "to_email" => $importer["email"],
2268 "uid" => $importer["importer_uid"],
2270 "link" => System::baseUrl()."/display/".urlencode(Item::getGuidById($posted_id)),
2271 "source_name" => stripslashes($item["author-name"]),
2272 "source_link" => $item["author-link"],
2273 "source_photo" => ((link_compare($item["author-link"], $importer["url"]))
2274 ? $importer["thumb"] : $item["author-avatar"]),
2275 "verb" => $item["verb"],
2276 "otype" => "person",
2277 "activity" => $verb,
2278 "parent" => $item["parent"]]
2285 * @brief Processes several actions, depending on the verb
2287 * @param int $entrytype Is it a toplevel entry, a comment or a relayed comment?
2288 * @param array $importer Record of the importer user mixed with contact of the content
2289 * @param array $item the new item record
2290 * @param bool $is_like Is the verb a "like"?
2292 * @return bool Should the processing of the entries be continued?
2293 * @todo set proper type-hints (array?)
2295 private static function processVerbs($entrytype, $importer, &$item, &$is_like)
2297 logger("Process verb ".$item["verb"]." and object-type ".$item["object-type"]." for entrytype ".$entrytype, LOGGER_DEBUG);
2299 if (($entrytype == DFRN_TOP_LEVEL)) {
2300 // The filling of the the "contact" variable is done for legcy reasons
2301 // The functions below are partly used by ostatus.php as well - where we have this variable
2302 $r = q("SELECT * FROM `contact` WHERE `id` = %d", intval($importer["id"]));
2304 $nickname = $contact["nick"];
2306 // Big question: Do we need these functions? They were part of the "consume_feed" function.
2307 // This function once was responsible for DFRN and OStatus.
2308 if (activity_match($item["verb"], ACTIVITY_FOLLOW)) {
2309 logger("New follower");
2310 Contact::addRelationship($importer, $contact, $item, $nickname);
2313 if (activity_match($item["verb"], ACTIVITY_UNFOLLOW)) {
2314 logger("Lost follower");
2315 Contact::removeFollower($importer, $contact, $item);
2318 if (activity_match($item["verb"], ACTIVITY_REQ_FRIEND)) {
2319 logger("New friend request");
2320 Contact::addRelationship($importer, $contact, $item, $nickname, true);
2323 if (activity_match($item["verb"], ACTIVITY_UNFRIEND)) {
2324 logger("Lost sharer");
2325 Contact::removeSharer($importer, $contact, $item);
2329 if (($item["verb"] == ACTIVITY_LIKE)
2330 || ($item["verb"] == ACTIVITY_DISLIKE)
2331 || ($item["verb"] == ACTIVITY_ATTEND)
2332 || ($item["verb"] == ACTIVITY_ATTENDNO)
2333 || ($item["verb"] == ACTIVITY_ATTENDMAYBE)
2336 $item["type"] = "activity";
2337 $item["gravity"] = GRAVITY_LIKE;
2338 // only one like or dislike per person
2339 // splitted into two queries for performance issues
2341 "SELECT `id` FROM `item` WHERE `uid` = %d AND `author-link` = '%s' AND `verb` = '%s' AND `parent-uri` = '%s' AND NOT `deleted` LIMIT 1",
2342 intval($item["uid"]),
2343 dbesc($item["author-link"]),
2344 dbesc($item["verb"]),
2345 dbesc($item["parent-uri"])
2347 if (DBM::is_result($r)) {
2352 "SELECT `id` FROM `item` WHERE `uid` = %d AND `author-link` = '%s' AND `verb` = '%s' AND `thr-parent` = '%s' AND NOT `deleted` LIMIT 1",
2353 intval($item["uid"]),
2354 dbesc($item["author-link"]),
2355 dbesc($item["verb"]),
2356 dbesc($item["parent-uri"])
2358 if (DBM::is_result($r)) {
2365 if (($item["verb"] == ACTIVITY_TAG) && ($item["object-type"] == ACTIVITY_OBJ_TAGTERM)) {
2366 $xo = XML::parseString($item["object"], false);
2367 $xt = XML::parseString($item["target"], false);
2369 if ($xt->type == ACTIVITY_OBJ_NOTE) {
2371 "SELECT `id`, `tag` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2373 intval($importer["importer_uid"])
2376 if (!DBM::is_result($r)) {
2377 logger("Query failed to execute, no result returned in " . __FUNCTION__);
2381 // extract tag, if not duplicate, add to parent item
2383 if (!stristr($r[0]["tag"], trim($xo->content))) {
2384 $tag = $r[0]["tag"] . (strlen($r[0]["tag"]) ? ',' : '') . '#[url=' . $xo->id . ']'. $xo->content . '[/url]';
2385 Item::update(['tag' => $tag], ['id' => $r[0]["id"]]);
2395 * @brief Processes the link elements
2397 * @param object $links link elements
2398 * @param array $item the item record
2400 * @todo set proper type-hints
2402 private static function parseLinks($links, &$item)
2409 foreach ($links as $link) {
2410 foreach ($link->attributes as $attributes) {
2411 switch ($attributes->name) {
2412 case "href" : $href = $attributes->textContent; break;
2413 case "rel" : $rel = $attributes->textContent; break;
2414 case "type" : $type = $attributes->textContent; break;
2415 case "length": $length = $attributes->textContent; break;
2416 case "title" : $title = $attributes->textContent; break;
2419 if (($rel != "") && ($href != "")) {
2422 $item["plink"] = $href;
2426 if (strlen($item["attach"])) {
2427 $item["attach"] .= ",";
2430 $item["attach"] .= '[attach]href="' . $href . '" length="' . $length . '" type="' . $type . '" title="' . $title . '"[/attach]';
2438 * @brief Processes the entry elements which contain the items and comments
2440 * @param array $header Array of the header elements that always stay the same
2441 * @param object $xpath XPath object
2442 * @param object $entry entry elements
2443 * @param array $importer Record of the importer user mixed with contact of the content
2444 * @param object $xml xml
2446 * @todo Add type-hints
2448 private static function processEntry($header, $xpath, $entry, $importer, $xml)
2450 logger("Processing entries");
2454 $item["protocol"] = PROTOCOL_DFRN;
2456 $item["source"] = $xml;
2459 $item["uri"] = $xpath->query("atom:id/text()", $entry)->item(0)->nodeValue;
2461 $item["edited"] = $xpath->query("atom:updated/text()", $entry)->item(0)->nodeValue;
2463 $current = dba::selectFirst('item',
2464 ['id', 'uid', 'edited', 'body'],
2465 ['uri' => $item["uri"], 'uid' => $importer["importer_uid"]]
2467 // Is there an existing item?
2468 if (DBM::is_result($current) && !self::isEditedTimestampNewer($current, $item)) {
2469 logger("Item ".$item["uri"]." (".$item['edited'].") already existed.", LOGGER_DEBUG);
2474 $owner = self::fetchauthor($xpath, $entry, $importer, "dfrn:owner", true);
2476 $item["owner-name"] = $owner["name"];
2477 $item["owner-link"] = $owner["link"];
2478 $item["owner-avatar"] = $owner["avatar"];
2481 $author = self::fetchauthor($xpath, $entry, $importer, "atom:author", true);
2483 $item["author-name"] = $author["name"];
2484 $item["author-link"] = $author["link"];
2485 $item["author-avatar"] = $author["avatar"];
2487 $item["title"] = $xpath->query("atom:title/text()", $entry)->item(0)->nodeValue;
2489 $item["created"] = $xpath->query("atom:published/text()", $entry)->item(0)->nodeValue;
2491 $item["body"] = $xpath->query("dfrn:env/text()", $entry)->item(0)->nodeValue;
2492 $item["body"] = str_replace([' ',"\t","\r","\n"], ['','','',''], $item["body"]);
2493 // make sure nobody is trying to sneak some html tags by us
2494 $item["body"] = notags(base64url_decode($item["body"]));
2496 $item["body"] = BBCode::limitBodySize($item["body"]);
2498 /// @todo Do we really need this check for HTML elements? (It was copied from the old function)
2499 if ((strpos($item['body'], '<') !== false) && (strpos($item['body'], '>') !== false)) {
2500 $base_url = get_app()->get_baseurl();
2501 $item['body'] = reltoabs($item['body'], $base_url);
2503 $item['body'] = html2bb_video($item['body']);
2505 $item['body'] = OEmbed::HTML2BBCode($item['body']);
2507 $config = HTMLPurifier_Config::createDefault();
2508 $config->set('Cache.DefinitionImpl', null);
2510 // we shouldn't need a whitelist, because the bbcode converter
2511 // will strip out any unsupported tags.
2513 $purifier = new HTMLPurifier($config);
2514 $item['body'] = $purifier->purify($item['body']);
2516 $item['body'] = @HTML::toBBCode($item['body']);
2519 /// @todo We should check for a repeated post and if we know the repeated author.
2521 // We don't need the content element since "dfrn:env" is always present
2522 //$item["body"] = $xpath->query("atom:content/text()", $entry)->item(0)->nodeValue;
2524 $item["location"] = $xpath->query("dfrn:location/text()", $entry)->item(0)->nodeValue;
2526 $georsspoint = $xpath->query("georss:point", $entry);
2528 $item["coord"] = $georsspoint->item(0)->nodeValue;
2531 $item["private"] = $xpath->query("dfrn:private/text()", $entry)->item(0)->nodeValue;
2533 $item["extid"] = $xpath->query("dfrn:extid/text()", $entry)->item(0)->nodeValue;
2535 if ($xpath->query("dfrn:bookmark/text()", $entry)->item(0)->nodeValue == "true") {
2536 $item["bookmark"] = true;
2539 $notice_info = $xpath->query("statusnet:notice_info", $entry);
2540 if ($notice_info && ($notice_info->length > 0)) {
2541 foreach ($notice_info->item(0)->attributes as $attributes) {
2542 if ($attributes->name == "source") {
2543 $item["app"] = strip_tags($attributes->textContent);
2548 $item["guid"] = $xpath->query("dfrn:diaspora_guid/text()", $entry)->item(0)->nodeValue;
2550 // We store the data from "dfrn:diaspora_signature" in a different table, this is done in "Item::insert"
2551 $dsprsig = unxmlify($xpath->query("dfrn:diaspora_signature/text()", $entry)->item(0)->nodeValue);
2552 if ($dsprsig != "") {
2553 $item["dsprsig"] = $dsprsig;
2556 $item["verb"] = $xpath->query("activity:verb/text()", $entry)->item(0)->nodeValue;
2558 if ($xpath->query("activity:object-type/text()", $entry)->item(0)->nodeValue != "") {
2559 $item["object-type"] = $xpath->query("activity:object-type/text()", $entry)->item(0)->nodeValue;
2562 $object = $xpath->query("activity:object", $entry)->item(0);
2563 $item["object"] = self::transformActivity($xpath, $object, "object");
2565 if (trim($item["object"]) != "") {
2566 $r = XML::parseString($item["object"], false);
2567 if (isset($r->type)) {
2568 $item["object-type"] = $r->type;
2572 $target = $xpath->query("activity:target", $entry)->item(0);
2573 $item["target"] = self::transformActivity($xpath, $target, "target");
2575 $categories = $xpath->query("atom:category", $entry);
2577 foreach ($categories as $category) {
2580 foreach ($category->attributes as $attributes) {
2581 if ($attributes->name == "term") {
2582 $term = $attributes->textContent;
2585 if ($attributes->name == "scheme") {
2586 $scheme = $attributes->textContent;
2590 if (($term != "") && ($scheme != "")) {
2591 $parts = explode(":", $scheme);
2592 if ((count($parts) >= 4) && (array_shift($parts) == "X-DFRN")) {
2593 $termhash = array_shift($parts);
2594 $termurl = implode(":", $parts);
2596 if (strlen($item["tag"])) {
2597 $item["tag"] .= ",";
2600 $item["tag"] .= $termhash . "[url=" . $termurl . "]" . $term . "[/url]";
2608 $links = $xpath->query("atom:link", $entry);
2610 self::parseLinks($links, $item);
2613 $item['conversation-uri'] = $xpath->query('ostatus:conversation/text()', $entry)->item(0)->nodeValue;
2615 $conv = $xpath->query('ostatus:conversation', $entry);
2616 if (is_object($conv->item(0))) {
2617 foreach ($conv->item(0)->attributes as $attributes) {
2618 if ($attributes->name == "ref") {
2619 $item['conversation-uri'] = $attributes->textContent;
2621 if ($attributes->name == "href") {
2622 $item['conversation-href'] = $attributes->textContent;
2627 // Is it a reply or a top level posting?
2628 $item["parent-uri"] = $item["uri"];
2630 $inreplyto = $xpath->query("thr:in-reply-to", $entry);
2631 if (is_object($inreplyto->item(0))) {
2632 foreach ($inreplyto->item(0)->attributes as $attributes) {
2633 if ($attributes->name == "ref") {
2634 $item["parent-uri"] = $attributes->textContent;
2639 // Get the type of the item (Top level post, reply or remote reply)
2640 $entrytype = self::getEntryType($importer, $item);
2642 // Now assign the rest of the values that depend on the type of the message
2643 if (in_array($entrytype, [DFRN_REPLY, DFRN_REPLY_RC])) {
2644 if (!isset($item["object-type"])) {
2645 $item["object-type"] = ACTIVITY_OBJ_COMMENT;
2648 if ($item["contact-id"] != $owner["contact-id"]) {
2649 $item["contact-id"] = $owner["contact-id"];
2652 if (($item["network"] != $owner["network"]) && ($owner["network"] != "")) {
2653 $item["network"] = $owner["network"];
2656 if ($item["contact-id"] != $author["contact-id"]) {
2657 $item["contact-id"] = $author["contact-id"];
2660 if (($item["network"] != $author["network"]) && ($author["network"] != "")) {
2661 $item["network"] = $author["network"];
2665 if ($entrytype == DFRN_REPLY_RC) {
2666 $item["type"] = "remote-comment";
2668 } elseif ($entrytype == DFRN_TOP_LEVEL) {
2669 if (!isset($item["object-type"])) {
2670 $item["object-type"] = ACTIVITY_OBJ_NOTE;
2674 if ($item["object-type"] == ACTIVITY_OBJ_EVENT) {
2675 logger("Item ".$item["uri"]." seems to contain an event.", LOGGER_DEBUG);
2676 $ev = Event::fromBBCode($item["body"]);
2677 if ((x($ev, "desc") || x($ev, "summary")) && x($ev, "start")) {
2678 logger("Event in item ".$item["uri"]." was found.", LOGGER_DEBUG);
2679 $ev["cid"] = $importer["id"];
2680 $ev["uid"] = $importer["importer_uid"];
2681 $ev["uri"] = $item["uri"];
2682 $ev["edited"] = $item["edited"];
2683 $ev["private"] = $item["private"];
2684 $ev["guid"] = $item["guid"];
2687 "SELECT `id` FROM `event` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2688 dbesc($item["uri"]),
2689 intval($importer["importer_uid"])
2691 if (DBM::is_result($r)) {
2692 $ev["id"] = $r[0]["id"];
2695 $event_id = Event::store($ev);
2696 logger("Event ".$event_id." was stored", LOGGER_DEBUG);
2702 if (!self::processVerbs($entrytype, $importer, $item, $is_like)) {
2703 logger("Exiting because 'processVerbs' told us so", LOGGER_DEBUG);
2707 // Update content if 'updated' changes
2708 if (DBM::is_result($current)) {
2709 if (self::updateContent($current, $item, $importer, $entrytype)) {
2710 logger("Item ".$item["uri"]." was updated.", LOGGER_DEBUG);
2712 logger("Item " . $item["uri"] . " already existed.", LOGGER_DEBUG);
2717 if (in_array($entrytype, [DFRN_REPLY, DFRN_REPLY_RC])) {
2718 $posted_id = Item::insert($item);
2722 logger("Reply from contact ".$item["contact-id"]." was stored with id ".$posted_id, LOGGER_DEBUG);
2724 if ($item['uid'] == 0) {
2725 Item::distribute($posted_id);
2728 $item["id"] = $posted_id;
2731 "SELECT `parent`, `parent-uri` FROM `item` WHERE `id` = %d AND `uid` = %d LIMIT 1",
2733 intval($importer["importer_uid"])
2735 if (DBM::is_result($r)) {
2736 $parent = $r[0]["parent"];
2737 $parent_uri = $r[0]["parent-uri"];
2740 if ($posted_id && $parent && ($entrytype == DFRN_REPLY_RC)) {
2741 logger("Notifying followers about comment ".$posted_id, LOGGER_DEBUG);
2742 Worker::add(PRIORITY_HIGH, "Notifier", "comment-import", $posted_id);
2747 } else { // $entrytype == DFRN_TOP_LEVEL
2748 if (($importer["uid"] == 0) && ($importer["importer_uid"] != 0)) {
2749 logger("Contact ".$importer["id"]." isn't known to user ".$importer["importer_uid"].". The post will be ignored.", LOGGER_DEBUG);
2752 if (!link_compare($item["owner-link"], $importer["url"])) {
2754 * The item owner info is not our contact. It's OK and is to be expected if this is a tgroup delivery,
2755 * but otherwise there's a possible data mixup on the sender's system.
2756 * the tgroup delivery code called from Item::insert will correct it if it's a forum,
2757 * but we're going to unconditionally correct it here so that the post will always be owned by our contact.
2759 logger('Correcting item owner.', LOGGER_DEBUG);
2760 $item["owner-name"] = $importer["senderName"];
2761 $item["owner-link"] = $importer["url"];
2762 $item["owner-avatar"] = $importer["thumb"];
2765 if (($importer["rel"] == CONTACT_IS_FOLLOWER) && (!self::tgroupCheck($importer["importer_uid"], $item))) {
2766 logger("Contact ".$importer["id"]." is only follower and tgroup check was negative.", LOGGER_DEBUG);
2770 // This is my contact on another system, but it's really me.
2771 // Turn this into a wall post.
2772 $notify = Item::isRemoteSelf($importer, $item);
2774 $posted_id = Item::insert($item, false, $notify);
2777 $posted_id = $notify;
2780 logger("Item was stored with id ".$posted_id, LOGGER_DEBUG);
2782 if ($item['uid'] == 0) {
2783 Item::distribute($posted_id);
2786 if (stristr($item["verb"], ACTIVITY_POKE)) {
2787 self::doPoke($item, $importer, $posted_id);
2793 * @brief Deletes items
2795 * @param object $xpath XPath object
2796 * @param object $deletion deletion elements
2797 * @param array $importer Record of the importer user mixed with contact of the content
2799 * @todo set proper type-hints
2801 private static function processDeletion($xpath, $deletion, $importer)
2803 logger("Processing deletions");
2806 foreach ($deletion->attributes as $attributes) {
2807 if ($attributes->name == "ref") {
2808 $uri = $attributes->textContent;
2812 if (!$uri || !$importer["id"]) {
2816 $condition = ["`uri` = ? AND `uid` = ? AND NOT `file` LIKE '%[%'", $uri, $importer["importer_uid"]];
2817 $item = dba::selectFirst('item', ['id', 'parent', 'contact-id'], $condition);
2818 if (!DBM::is_result($item)) {
2819 logger("Item with uri " . $uri . " for user " . $importer["importer_uid"] . " wasn't found.", LOGGER_DEBUG);
2823 // When it is a starting post it has to belong to the person that wants to delete it
2824 if (($item['id'] == $item['parent']) && ($item['contact-id'] != $importer["id"])) {
2825 logger("Item with uri " . $uri . " don't belong to contact " . $importer["id"] . " - ignoring deletion.", LOGGER_DEBUG);
2829 // Comments can be deleted by the thread owner or comment owner
2830 if (($item['id'] != $item['parent']) && ($item['contact-id'] != $importer["id"])) {
2831 $condition = ['id' => $item['parent'], 'contact-id' => $importer["id"]];
2832 if (!dba::exists('item', $condition)) {
2833 logger("Item with uri " . $uri . " wasn't found or mustn't be deleted by contact " . $importer["id"] . " - ignoring deletion.", LOGGER_DEBUG);
2838 $entrytype = self::getEntryType($importer, $item);
2840 if (!$item["deleted"]) {
2841 logger('deleting item '.$item["id"].' uri='.$uri, LOGGER_DEBUG);
2846 Item::deleteById($item["id"]);
2848 if ($entrytype != DFRN_TOP_LEVEL) {
2849 // if this is a relayed delete, propagate it to other recipients
2850 if ($entrytype == DFRN_REPLY_RC) {
2851 logger("Notifying followers about deletion of post " . $item["id"], LOGGER_DEBUG);
2852 Worker::add(PRIORITY_HIGH, "Notifier", "drop", $item["id"]);
2858 * @brief Imports a DFRN message
2860 * @param string $xml The DFRN message
2861 * @param array $importer Record of the importer user mixed with contact of the content
2862 * @param bool $sort_by_date Is used when feeds are polled
2863 * @return integer Import status
2864 * @todo set proper type-hints
2866 public static function import($xml, $importer, $sort_by_date = false)
2872 $doc = new DOMDocument();
2873 @$doc->loadXML($xml);
2875 $xpath = new DOMXPath($doc);
2876 $xpath->registerNamespace("atom", NAMESPACE_ATOM1);
2877 $xpath->registerNamespace("thr", NAMESPACE_THREAD);
2878 $xpath->registerNamespace("at", NAMESPACE_TOMB);
2879 $xpath->registerNamespace("media", NAMESPACE_MEDIA);
2880 $xpath->registerNamespace("dfrn", NAMESPACE_DFRN);
2881 $xpath->registerNamespace("activity", NAMESPACE_ACTIVITY);
2882 $xpath->registerNamespace("georss", NAMESPACE_GEORSS);
2883 $xpath->registerNamespace("poco", NAMESPACE_POCO);
2884 $xpath->registerNamespace("ostatus", NAMESPACE_OSTATUS);
2885 $xpath->registerNamespace("statusnet", NAMESPACE_STATUSNET);
2888 $header["uid"] = $importer["importer_uid"];
2889 $header["network"] = NETWORK_DFRN;
2890 $header["type"] = "remote";
2891 $header["wall"] = 0;
2892 $header["origin"] = 0;
2893 $header["contact-id"] = $importer["id"];
2895 // Update the contact table if the data has changed
2897 // The "atom:author" is only present in feeds
2898 if ($xpath->query("/atom:feed/atom:author")->length > 0) {
2899 self::fetchauthor($xpath, $doc->firstChild, $importer, "atom:author", false, $xml);
2902 // Only the "dfrn:owner" in the head section contains all data
2903 if ($xpath->query("/atom:feed/dfrn:owner")->length > 0) {
2904 self::fetchauthor($xpath, $doc->firstChild, $importer, "dfrn:owner", false, $xml);
2907 logger("Import DFRN message for user " . $importer["importer_uid"] . " from contact " . $importer["id"], LOGGER_DEBUG);
2909 // is it a public forum? Private forums aren't exposed with this method
2910 $forum = intval($xpath->evaluate("/atom:feed/dfrn:community/text()")->item(0)->nodeValue);
2912 // The account type is new since 3.5.1
2913 if ($xpath->query("/atom:feed/dfrn:account_type")->length > 0) {
2914 $accounttype = intval($xpath->evaluate("/atom:feed/dfrn:account_type/text()")->item(0)->nodeValue);
2916 if ($accounttype != $importer["contact-type"]) {
2917 dba::update('contact', ['contact-type' => $accounttype], ['id' => $importer["id"]]);
2919 // A forum contact can either have set "forum" or "prv" - but not both
2920 if (($accounttype == ACCOUNT_TYPE_COMMUNITY) && (($forum != $importer["forum"]) || ($forum == $importer["prv"]))) {
2921 $condition = ['(`forum` != ? OR `prv` != ?) AND `id` = ?', $forum, !$forum, $importer["id"]];
2922 dba::update('contact', ['forum' => $forum, 'prv' => !$forum], $condition);
2924 } elseif ($forum != $importer["forum"]) { // Deprecated since 3.5.1
2925 $condition = ['`forum` != ? AND `id` = ?', $forum, $importer["id"]];
2926 dba::update('contact', ['forum' => $forum], $condition);
2930 // We are processing relocations even if we are ignoring a contact
2931 $relocations = $xpath->query("/atom:feed/dfrn:relocate");
2932 foreach ($relocations as $relocation) {
2933 self::processRelocation($xpath, $relocation, $importer);
2936 if (($importer["uid"] != 0) && !$importer["readonly"]) {
2937 $mails = $xpath->query("/atom:feed/dfrn:mail");
2938 foreach ($mails as $mail) {
2939 self::processMail($xpath, $mail, $importer);
2942 $suggestions = $xpath->query("/atom:feed/dfrn:suggest");
2943 foreach ($suggestions as $suggestion) {
2944 self::processSuggestion($xpath, $suggestion, $importer);
2948 $deletions = $xpath->query("/atom:feed/at:deleted-entry");
2949 foreach ($deletions as $deletion) {
2950 self::processDeletion($xpath, $deletion, $importer);
2953 if (!$sort_by_date) {
2954 $entries = $xpath->query("/atom:feed/atom:entry");
2955 foreach ($entries as $entry) {
2956 self::processEntry($header, $xpath, $entry, $importer, $xml);
2960 $entries = $xpath->query("/atom:feed/atom:entry");
2961 foreach ($entries as $entry) {
2962 $created = $xpath->query("atom:published/text()", $entry)->item(0)->nodeValue;
2963 $newentries[strtotime($created)] = $entry;
2966 // Now sort after the publishing date
2969 foreach ($newentries as $entry) {
2970 self::processEntry($header, $xpath, $entry, $importer, $xml);
2973 logger("Import done for user " . $importer["importer_uid"] . " from contact " . $importer["id"], LOGGER_DEBUG);
2979 * @param string $contact_nick contact nickname
2981 public static function autoRedir(App $a, $contact_nick)
2984 if (x($_REQUEST, 'redir') && intval($_REQUEST['redir'])) {
2988 if ((! $contact_nick) || ($contact_nick === $a->user['nickname'])) {
2993 // We need to find out if $contact_nick is a user on this hub, and if so, if I
2994 // am a contact of that user. However, that user may have other contacts with the
2995 // same nickname as me on other hubs or other networks. Exclude these by requiring
2996 // that the contact have a local URL. I will be the only person with my nickname at
2997 // this URL, so if a result is found, then I am a contact of the $contact_nick user.
2999 // We also have to make sure that I'm a legitimate contact--I'm not blocked or pending.
3001 $baseurl = System::baseUrl();
3002 $domain_st = strpos($baseurl, "://");
3003 if ($domain_st === false) {
3006 $baseurl = substr($baseurl, $domain_st + 3);
3007 $nurl = normalise_link($baseurl);
3009 /// @todo Why is there a query for "url" *and* "nurl"? Especially this normalising is strange.
3010 $r = q("SELECT `id` FROM `contact` WHERE `uid` = (SELECT `uid` FROM `user` WHERE `nickname` = '%s' LIMIT 1)
3011 AND `nick` = '%s' AND NOT `self` AND (`url` LIKE '%%%s%%' OR `nurl` LIKE '%%%s%%') AND NOT `blocked` AND NOT `pending` LIMIT 1",
3012 dbesc($contact_nick),
3013 dbesc($a->user['nickname']),
3017 if ((! DBM::is_result($r)) || $r[0]['id'] == remote_user()) {
3021 $r = q("SELECT * FROM contact WHERE nick = '%s'
3022 AND network = '%s' AND uid = %d AND url LIKE '%%%s%%' LIMIT 1",
3023 dbesc($contact_nick),
3024 dbesc(NETWORK_DFRN),
3025 intval(local_user()),
3028 if (! DBM::is_result($r)) {
3034 $dfrn_id = (($r[0]['issued-id']) ? $r[0]['issued-id'] : $r[0]['dfrn-id']);
3036 if ($r[0]['duplex'] && $r[0]['issued-id']) {
3037 $orig_id = $r[0]['issued-id'];
3038 $dfrn_id = '1:' . $orig_id;
3040 if ($r[0]['duplex'] && $r[0]['dfrn-id']) {
3041 $orig_id = $r[0]['dfrn-id'];
3042 $dfrn_id = '0:' . $orig_id;
3045 // ensure that we've got a valid ID. There may be some edge cases with forums and non-duplex mode
3046 // that may have triggered some of the "went to {profile/intro} and got an RSS feed" issues
3048 if (strlen($dfrn_id) < 3) {
3052 $sec = random_string();
3054 dba::insert('profile_check', ['uid' => local_user(), 'cid' => $cid, 'dfrn_id' => $dfrn_id, 'sec' => $sec, 'expire' => time() + 45]);
3056 $url = curPageURL();
3058 logger('auto_redir: ' . $r[0]['name'] . ' ' . $sec, LOGGER_DEBUG);
3059 $dest = (($url) ? '&destination_url=' . $url : '');
3060 goaway($r[0]['poll'] . '?dfrn_id=' . $dfrn_id
3061 . '&dfrn_version=' . DFRN_PROTOCOL_VERSION . '&type=profile&sec=' . $sec . $dest);
3068 * @brief Returns the activity verb
3070 * @param array $item Item array
3072 * @return string activity verb
3074 private static function constructVerb(array $item)
3076 if ($item['verb']) {
3077 return $item['verb'];
3079 return ACTIVITY_POST;
3082 private static function tgroupCheck($uid, $item)
3086 // check that the message originated elsewhere and is a top-level post
3088 if ($item['wall'] || $item['origin'] || ($item['uri'] != $item['parent-uri'])) {
3092 $u = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1",
3095 if (!DBM::is_result($u)) {
3099 $community_page = ($u[0]['page-flags'] == PAGE_COMMUNITY);
3100 $prvgroup = ($u[0]['page-flags'] == PAGE_PRVGROUP);
3102 $link = normalise_link(System::baseUrl() . '/profile/' . $u[0]['nickname']);
3105 * Diaspora uses their own hardwired link URL in @-tags
3106 * instead of the one we supply with webfinger
3108 $dlink = normalise_link(System::baseUrl() . '/u/' . $u[0]['nickname']);
3110 $cnt = preg_match_all('/[\@\!]\[url\=(.*?)\](.*?)\[\/url\]/ism', $item['body'], $matches, PREG_SET_ORDER);
3112 foreach ($matches as $mtch) {
3113 if (link_compare($link, $mtch[1]) || link_compare($dlink, $mtch[1])) {
3115 logger('mention found: ' . $mtch[2]);
3124 return $community_page || $prvgroup;
3128 * This function returns true if $update has an edited timestamp newer
3129 * than $existing, i.e. $update contains new data which should override
3130 * what's already there. If there is no timestamp yet, the update is
3131 * assumed to be newer. If the update has no timestamp, the existing
3132 * item is assumed to be up-to-date. If the timestamps are equal it
3133 * assumes the update has been seen before and should be ignored.
3136 private static function isEditedTimestampNewer($existing, $update)
3138 if (!x($existing, 'edited') || !$existing['edited']) {
3141 if (!x($update, 'edited') || !$update['edited']) {
3145 $existing_edited = DateTimeFormat::utc($existing['edited']);
3146 $update_edited = DateTimeFormat::utc($update['edited']);
3148 return (strcmp($existing_edited, $update_edited) < 0);