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;
14 use Friendica\Content\OEmbed;
15 use Friendica\Content\Text\BBCode;
16 use Friendica\Content\Text\HTML;
17 use Friendica\Core\Addon;
18 use Friendica\Core\Config;
19 use Friendica\Core\L10n;
20 use Friendica\Core\Protocol;
21 use Friendica\Core\System;
22 use Friendica\Database\DBA;
23 use Friendica\Model\Contact;
24 use Friendica\Model\Conversation;
25 use Friendica\Model\Event;
26 use Friendica\Model\GContact;
27 use Friendica\Model\Item;
28 use Friendica\Model\PermissionSet;
29 use Friendica\Model\Profile;
30 use Friendica\Model\User;
31 use Friendica\Object\Image;
32 use Friendica\Util\Crypto;
33 use Friendica\Util\DateTimeFormat;
34 use Friendica\Util\Network;
35 use Friendica\Util\XML;
37 use HTMLPurifier_Config;
39 require_once 'boot.php';
40 require_once 'include/dba.php';
41 require_once "include/enotify.php";
42 require_once "include/items.php";
43 require_once "include/text.php";
46 * @brief This class contain functions to create and send DFRN XML files
51 const TOP_LEVEL = 0; // Top level posting
52 const REPLY = 1; // Regular reply that is stored locally
53 const REPLY_RC = 2; // Reply that will be relayed
56 * @brief Generates the atom entries for delivery.php
58 * This function is used whenever content is transmitted via DFRN.
60 * @param array $items Item elements
61 * @param array $owner Owner record
63 * @return string DFRN entries
64 * @todo Find proper type-hints
66 public static function entries($items, $owner)
68 $doc = new DOMDocument('1.0', 'utf-8');
69 $doc->formatOutput = true;
71 $root = self::addHeader($doc, $owner, "dfrn:owner", "", false);
73 if (! count($items)) {
74 return trim($doc->saveXML());
77 foreach ($items as $item) {
78 // These values aren't sent when sending from the queue.
79 /// @todo Check if we can set these values from the queue or if they are needed at all.
80 $item["entry:comment-allow"] = defaults($item, "entry:comment-allow", true);
81 $item["entry:cid"] = defaults($item, "entry:cid", 0);
83 $entry = self::entry($doc, "text", $item, $owner, $item["entry:comment-allow"], $item["entry:cid"]);
84 $root->appendChild($entry);
87 return trim($doc->saveXML());
91 * @brief Generate an atom feed for the given user
93 * This function is called when another server is pulling data from the user feed.
95 * @param string $dfrn_id DFRN ID from the requesting party
96 * @param string $owner_nick Owner nick name
97 * @param string $last_update Date of the last update
98 * @param int $direction Can be -1, 0 or 1.
99 * @param boolean $onlyheader Output only the header without content? (Default is "no")
101 * @return string DFRN feed entries
103 public static function feed($dfrn_id, $owner_nick, $last_update, $direction = 0, $onlyheader = false)
107 $sitefeed = ((strlen($owner_nick)) ? false : true); // not yet implemented, need to rewrite huge chunks of following logic
108 $public_feed = (($dfrn_id) ? false : true);
109 $starred = false; // not yet implemented, possible security issues
112 if ($public_feed && $a->argc > 2) {
113 for ($x = 2; $x < $a->argc; $x++) {
114 if ($a->argv[$x] == 'converse') {
117 if ($a->argv[$x] == 'starred') {
120 if ($a->argv[$x] == 'category' && $a->argc > ($x + 1) && strlen($a->argv[$x+1])) {
121 $category = $a->argv[$x+1];
126 // default permissions - anonymous user
128 $sql_extra = " AND NOT `item`.`private` ";
131 "SELECT `contact`.*, `user`.`nickname`, `user`.`timezone`, `user`.`page-flags`, `user`.`account-type`
132 FROM `contact` INNER JOIN `user` ON `user`.`uid` = `contact`.`uid`
133 WHERE `contact`.`self` AND `user`.`nickname` = '%s' LIMIT 1",
134 DBA::escape($owner_nick)
137 if (! DBA::isResult($r)) {
138 logger(sprintf('No contact found for nickname=%d', $owner_nick), LOGGER_WARNING);
143 $owner_id = $owner['uid'];
144 $owner_nick = $owner['nickname'];
146 $sql_post_table = "";
148 if (! $public_feed) {
150 switch ($direction) {
152 $sql_extra = sprintf(" AND `issued-id` = '%s' ", DBA::escape($dfrn_id));
156 $sql_extra = sprintf(" AND `issued-id` = '%s' AND `duplex` = 1 ", DBA::escape($dfrn_id));
157 $my_id = '1:' . $dfrn_id;
160 $sql_extra = sprintf(" AND `dfrn-id` = '%s' AND `duplex` = 1 ", DBA::escape($dfrn_id));
161 $my_id = '0:' . $dfrn_id;
169 "SELECT * FROM `contact` WHERE NOT `blocked` AND `contact`.`uid` = %d $sql_extra LIMIT 1",
173 if (! DBA::isResult($r)) {
174 logger(sprintf('No contact found for uid=%d', $owner_id), LOGGER_WARNING);
179 include_once 'include/security.php';
181 $set = PermissionSet::get($owner_id, $contact['id']);
184 $sql_extra = " AND `item`.`psid` IN (" . implode(',', $set) .")";
186 $sql_extra = " AND NOT `item`.`private`";
196 if (! strlen($last_update)) {
197 $last_update = 'now -30 days';
200 if (isset($category)) {
201 $sql_post_table = sprintf(
202 "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` ",
203 DBA::escape(protect_sprintf($category)),
204 intval(TERM_OBJ_POST),
205 intval(TERM_CATEGORY),
208 //$sql_extra .= file_tag_file_query('item',$category,'category');
211 if ($public_feed && ! $converse) {
212 $sql_extra .= " AND `contact`.`self` = 1 ";
215 $check_date = DateTimeFormat::utc($last_update);
219 FROM `item` USE INDEX (`uid_wall_changed`) $sql_post_table
220 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
221 WHERE `item`.`uid` = %d AND `item`.`wall` AND `item`.`changed` > '%s'
223 ORDER BY `item`.`parent` ".$sort.", `item`.`created` ASC LIMIT 0, 300",
225 DBA::escape($check_date),
230 foreach ($r as $item) {
231 $ids[] = $item['id'];
235 $ret = Item::select(Item::DELIVER_FIELDLIST, ['id' => $ids]);
236 $items = Item::inArray($ret);
242 * Will check further below if this actually returned results.
243 * We will provide an empty feed if that is the case.
246 $doc = new DOMDocument('1.0', 'utf-8');
247 $doc->formatOutput = true;
249 $alternatelink = $owner['url'];
251 if (isset($category)) {
252 $alternatelink .= "/category/".$category;
256 $author = "dfrn:owner";
261 $root = self::addHeader($doc, $owner, $author, $alternatelink, true);
263 /// @TODO This hook can't work anymore
264 // Addon::callHooks('atom_feed', $atom);
266 if (!DBA::isResult($items) || $onlyheader) {
267 $atom = trim($doc->saveXML());
269 Addon::callHooks('atom_feed_end', $atom);
274 foreach ($items as $item) {
275 // prevent private email from leaking.
276 if ($item['network'] == Protocol::MAIL) {
280 // public feeds get html, our own nodes use bbcode
284 // catch any email that's in a public conversation and make sure it doesn't leak
285 if ($item['private']) {
292 $entry = self::entry($doc, $type, $item, $owner, true);
293 $root->appendChild($entry);
296 $atom = trim($doc->saveXML());
298 Addon::callHooks('atom_feed_end', $atom);
304 * @brief Generate an atom entry for a given item id
306 * @param int $item_id The item id
307 * @param boolean $conversation Show the conversation. If false show the single post.
309 * @return string DFRN feed entry
311 public static function itemFeed($item_id, $conversation = false)
314 $condition = ['parent' => $item_id];
316 $condition = ['id' => $item_id];
319 $ret = Item::select(Item::DELIVER_FIELDLIST, $condition);
320 $items = Item::inArray($ret);
321 if (!DBA::isResult($items)) {
327 if ($item['uid'] != 0) {
328 $owner = User::getOwnerDataById($item['uid']);
333 $owner = ['uid' => 0, 'nick' => 'feed-item'];
336 $doc = new DOMDocument('1.0', 'utf-8');
337 $doc->formatOutput = true;
341 $root = $doc->createElementNS(NAMESPACE_ATOM1, 'feed');
342 $doc->appendChild($root);
344 $root->setAttribute("xmlns:thr", NAMESPACE_THREAD);
345 $root->setAttribute("xmlns:at", NAMESPACE_TOMB);
346 $root->setAttribute("xmlns:media", NAMESPACE_MEDIA);
347 $root->setAttribute("xmlns:dfrn", NAMESPACE_DFRN);
348 $root->setAttribute("xmlns:activity", NAMESPACE_ACTIVITY);
349 $root->setAttribute("xmlns:georss", NAMESPACE_GEORSS);
350 $root->setAttribute("xmlns:poco", NAMESPACE_POCO);
351 $root->setAttribute("xmlns:ostatus", NAMESPACE_OSTATUS);
352 $root->setAttribute("xmlns:statusnet", NAMESPACE_STATUSNET);
354 //$root = self::addHeader($doc, $owner, "dfrn:owner", "", false);
356 foreach ($items as $item) {
357 $entry = self::entry($doc, $type, $item, $owner, true, 0);
358 $root->appendChild($entry);
361 $root = self::entry($doc, $type, $item, $owner, true, 0, true);
364 $atom = trim($doc->saveXML());
369 * @brief Create XML text for DFRN mails
371 * @param array $item message elements
372 * @param array $owner Owner record
374 * @return string DFRN mail
375 * @todo Find proper type-hints
377 public static function mail($item, $owner)
379 $doc = new DOMDocument('1.0', 'utf-8');
380 $doc->formatOutput = true;
382 $root = self::addHeader($doc, $owner, "dfrn:owner", "", false);
384 $mail = $doc->createElement("dfrn:mail");
385 $sender = $doc->createElement("dfrn:sender");
387 XML::addElement($doc, $sender, "dfrn:name", $owner['name']);
388 XML::addElement($doc, $sender, "dfrn:uri", $owner['url']);
389 XML::addElement($doc, $sender, "dfrn:avatar", $owner['thumb']);
391 $mail->appendChild($sender);
393 XML::addElement($doc, $mail, "dfrn:id", $item['uri']);
394 XML::addElement($doc, $mail, "dfrn:in-reply-to", $item['parent-uri']);
395 XML::addElement($doc, $mail, "dfrn:sentdate", DateTimeFormat::utc($item['created'] . '+00:00', DateTimeFormat::ATOM));
396 XML::addElement($doc, $mail, "dfrn:subject", $item['title']);
397 XML::addElement($doc, $mail, "dfrn:content", $item['body']);
399 $root->appendChild($mail);
401 return trim($doc->saveXML());
405 * @brief Create XML text for DFRN friend suggestions
407 * @param array $item suggestion elements
408 * @param array $owner Owner record
410 * @return string DFRN suggestions
411 * @todo Find proper type-hints
413 public static function fsuggest($item, $owner)
415 $doc = new DOMDocument('1.0', 'utf-8');
416 $doc->formatOutput = true;
418 $root = self::addHeader($doc, $owner, "dfrn:owner", "", false);
420 $suggest = $doc->createElement("dfrn:suggest");
422 XML::addElement($doc, $suggest, "dfrn:url", $item['url']);
423 XML::addElement($doc, $suggest, "dfrn:name", $item['name']);
424 XML::addElement($doc, $suggest, "dfrn:photo", $item['photo']);
425 XML::addElement($doc, $suggest, "dfrn:request", $item['request']);
426 XML::addElement($doc, $suggest, "dfrn:note", $item['note']);
428 $root->appendChild($suggest);
430 return trim($doc->saveXML());
434 * @brief Create XML text for DFRN relocations
436 * @param array $owner Owner record
437 * @param int $uid User ID
439 * @return string DFRN relocations
440 * @todo Find proper type-hints
442 public static function relocate($owner, $uid)
445 /* get site pubkey. this could be a new installation with no site keys*/
446 $pubkey = Config::get('system', 'site_pubkey');
448 $res = Crypto::newKeypair(1024);
449 Config::set('system', 'site_prvkey', $res['prvkey']);
450 Config::set('system', 'site_pubkey', $res['pubkey']);
454 "SELECT `resource-id` , `scale`, type FROM `photo`
455 WHERE `profile` = 1 AND `uid` = %d ORDER BY scale;",
459 $ext = Image::supportedTypes();
461 foreach ($rp as $p) {
462 $photos[$p['scale']] = System::baseUrl().'/photo/'.$p['resource-id'].'-'.$p['scale'].'.'.$ext[$p['type']];
466 $doc = new DOMDocument('1.0', 'utf-8');
467 $doc->formatOutput = true;
469 $root = self::addHeader($doc, $owner, "dfrn:owner", "", false);
471 $relocate = $doc->createElement("dfrn:relocate");
473 XML::addElement($doc, $relocate, "dfrn:url", $owner['url']);
474 XML::addElement($doc, $relocate, "dfrn:name", $owner['name']);
475 XML::addElement($doc, $relocate, "dfrn:addr", $owner['addr']);
476 XML::addElement($doc, $relocate, "dfrn:avatar", $owner['avatar']);
477 XML::addElement($doc, $relocate, "dfrn:photo", $photos[4]);
478 XML::addElement($doc, $relocate, "dfrn:thumb", $photos[5]);
479 XML::addElement($doc, $relocate, "dfrn:micro", $photos[6]);
480 XML::addElement($doc, $relocate, "dfrn:request", $owner['request']);
481 XML::addElement($doc, $relocate, "dfrn:confirm", $owner['confirm']);
482 XML::addElement($doc, $relocate, "dfrn:notify", $owner['notify']);
483 XML::addElement($doc, $relocate, "dfrn:poll", $owner['poll']);
484 XML::addElement($doc, $relocate, "dfrn:sitepubkey", Config::get('system', 'site_pubkey'));
486 $root->appendChild($relocate);
488 return trim($doc->saveXML());
492 * @brief Adds the header elements for the DFRN protocol
494 * @param object $doc XML document
495 * @param array $owner Owner record
496 * @param string $authorelement Element name for the author
497 * @param string $alternatelink link to profile or category
498 * @param bool $public Is it a header for public posts?
500 * @return object XML root object
501 * @todo Find proper type-hints
503 private static function addHeader($doc, $owner, $authorelement, $alternatelink = "", $public = false)
506 if ($alternatelink == "") {
507 $alternatelink = $owner['url'];
510 $root = $doc->createElementNS(NAMESPACE_ATOM1, 'feed');
511 $doc->appendChild($root);
513 $root->setAttribute("xmlns:thr", NAMESPACE_THREAD);
514 $root->setAttribute("xmlns:at", NAMESPACE_TOMB);
515 $root->setAttribute("xmlns:media", NAMESPACE_MEDIA);
516 $root->setAttribute("xmlns:dfrn", NAMESPACE_DFRN);
517 $root->setAttribute("xmlns:activity", NAMESPACE_ACTIVITY);
518 $root->setAttribute("xmlns:georss", NAMESPACE_GEORSS);
519 $root->setAttribute("xmlns:poco", NAMESPACE_POCO);
520 $root->setAttribute("xmlns:ostatus", NAMESPACE_OSTATUS);
521 $root->setAttribute("xmlns:statusnet", NAMESPACE_STATUSNET);
523 XML::addElement($doc, $root, "id", System::baseUrl()."/profile/".$owner["nick"]);
524 XML::addElement($doc, $root, "title", $owner["name"]);
526 $attributes = ["uri" => "https://friendi.ca", "version" => FRIENDICA_VERSION."-".DB_UPDATE_VERSION];
527 XML::addElement($doc, $root, "generator", FRIENDICA_PLATFORM, $attributes);
529 $attributes = ["rel" => "license", "href" => "http://creativecommons.org/licenses/by/3.0/"];
530 XML::addElement($doc, $root, "link", "", $attributes);
532 $attributes = ["rel" => "alternate", "type" => "text/html", "href" => $alternatelink];
533 XML::addElement($doc, $root, "link", "", $attributes);
537 // DFRN itself doesn't uses this. But maybe someone else wants to subscribe to the public feed.
538 OStatus::hublinks($doc, $root, $owner["nick"]);
540 $attributes = ["rel" => "salmon", "href" => System::baseUrl()."/salmon/".$owner["nick"]];
541 XML::addElement($doc, $root, "link", "", $attributes);
543 $attributes = ["rel" => "http://salmon-protocol.org/ns/salmon-replies", "href" => System::baseUrl()."/salmon/".$owner["nick"]];
544 XML::addElement($doc, $root, "link", "", $attributes);
546 $attributes = ["rel" => "http://salmon-protocol.org/ns/salmon-mention", "href" => System::baseUrl()."/salmon/".$owner["nick"]];
547 XML::addElement($doc, $root, "link", "", $attributes);
550 // For backward compatibility we keep this element
551 if ($owner['page-flags'] == Contact::PAGE_COMMUNITY) {
552 XML::addElement($doc, $root, "dfrn:community", 1);
555 // The former element is replaced by this one
556 XML::addElement($doc, $root, "dfrn:account_type", $owner["account-type"]);
558 /// @todo We need a way to transmit the different page flags like "Contact::PAGE_PRVGROUP"
560 XML::addElement($doc, $root, "updated", DateTimeFormat::utcNow(DateTimeFormat::ATOM));
562 $author = self::addAuthor($doc, $owner, $authorelement, $public);
563 $root->appendChild($author);
569 * @brief Adds the author element in the header for the DFRN protocol
571 * @param object $doc XML document
572 * @param array $owner Owner record
573 * @param string $authorelement Element name for the author
574 * @param boolean $public boolean
576 * @return object XML author object
577 * @todo Find proper type-hints
579 private static function addAuthor($doc, $owner, $authorelement, $public)
581 // Is the profile hidden or shouldn't be published in the net? Then add the "hide" element
583 "SELECT `id` FROM `profile` INNER JOIN `user` ON `user`.`uid` = `profile`.`uid`
584 WHERE (`hidewall` OR NOT `net-publish`) AND `user`.`uid` = %d",
585 intval($owner['uid'])
587 if (DBA::isResult($r)) {
593 $author = $doc->createElement($authorelement);
595 $namdate = DateTimeFormat::utc($owner['name-date'].'+00:00', DateTimeFormat::ATOM);
596 $uridate = DateTimeFormat::utc($owner['uri-date'].'+00:00', DateTimeFormat::ATOM);
597 $picdate = DateTimeFormat::utc($owner['avatar-date'].'+00:00', DateTimeFormat::ATOM);
601 if (!$public || !$hidewall) {
602 $attributes = ["dfrn:updated" => $namdate];
605 XML::addElement($doc, $author, "name", $owner["name"], $attributes);
606 XML::addElement($doc, $author, "uri", System::baseUrl().'/profile/'.$owner["nickname"], $attributes);
607 XML::addElement($doc, $author, "dfrn:handle", $owner["addr"], $attributes);
609 $attributes = ["rel" => "photo", "type" => "image/jpeg",
610 "media:width" => 175, "media:height" => 175, "href" => $owner['photo']];
612 if (!$public || !$hidewall) {
613 $attributes["dfrn:updated"] = $picdate;
616 XML::addElement($doc, $author, "link", "", $attributes);
618 $attributes["rel"] = "avatar";
619 XML::addElement($doc, $author, "link", "", $attributes);
622 XML::addElement($doc, $author, "dfrn:hide", "true");
625 // The following fields will only be generated if the data isn't meant for a public feed
630 $birthday = feed_birthday($owner['uid'], $owner['timezone']);
633 XML::addElement($doc, $author, "dfrn:birthday", $birthday);
636 // Only show contact details when we are allowed to
638 "SELECT `profile`.`about`, `profile`.`name`, `profile`.`homepage`, `user`.`nickname`,
639 `user`.`timezone`, `profile`.`locality`, `profile`.`region`, `profile`.`country-name`,
640 `profile`.`pub_keywords`, `profile`.`xmpp`, `profile`.`dob`
642 INNER JOIN `user` ON `user`.`uid` = `profile`.`uid`
643 WHERE `profile`.`is-default` AND NOT `user`.`hidewall` AND `user`.`uid` = %d",
644 intval($owner['uid'])
646 if (DBA::isResult($r)) {
649 XML::addElement($doc, $author, "poco:displayName", $profile["name"]);
650 XML::addElement($doc, $author, "poco:updated", $namdate);
652 if (trim($profile["dob"]) > '0001-01-01') {
653 XML::addElement($doc, $author, "poco:birthday", "0000-".date("m-d", strtotime($profile["dob"])));
656 XML::addElement($doc, $author, "poco:note", $profile["about"]);
657 XML::addElement($doc, $author, "poco:preferredUsername", $profile["nickname"]);
659 $savetz = date_default_timezone_get();
660 date_default_timezone_set($profile["timezone"]);
661 XML::addElement($doc, $author, "poco:utcOffset", date("P"));
662 date_default_timezone_set($savetz);
664 if (trim($profile["homepage"]) != "") {
665 $urls = $doc->createElement("poco:urls");
666 XML::addElement($doc, $urls, "poco:type", "homepage");
667 XML::addElement($doc, $urls, "poco:value", $profile["homepage"]);
668 XML::addElement($doc, $urls, "poco:primary", "true");
669 $author->appendChild($urls);
672 if (trim($profile["pub_keywords"]) != "") {
673 $keywords = explode(",", $profile["pub_keywords"]);
675 foreach ($keywords as $keyword) {
676 XML::addElement($doc, $author, "poco:tags", trim($keyword));
680 if (trim($profile["xmpp"]) != "") {
681 $ims = $doc->createElement("poco:ims");
682 XML::addElement($doc, $ims, "poco:type", "xmpp");
683 XML::addElement($doc, $ims, "poco:value", $profile["xmpp"]);
684 XML::addElement($doc, $ims, "poco:primary", "true");
685 $author->appendChild($ims);
688 if (trim($profile["locality"].$profile["region"].$profile["country-name"]) != "") {
689 $element = $doc->createElement("poco:address");
691 XML::addElement($doc, $element, "poco:formatted", Profile::formatLocation($profile));
693 if (trim($profile["locality"]) != "") {
694 XML::addElement($doc, $element, "poco:locality", $profile["locality"]);
697 if (trim($profile["region"]) != "") {
698 XML::addElement($doc, $element, "poco:region", $profile["region"]);
701 if (trim($profile["country-name"]) != "") {
702 XML::addElement($doc, $element, "poco:country", $profile["country-name"]);
705 $author->appendChild($element);
713 * @brief Adds the author elements in the "entry" elements of the DFRN protocol
715 * @param object $doc XML document
716 * @param string $element Element name for the author
717 * @param string $contact_url Link of the contact
718 * @param array $item Item elements
720 * @return object XML author object
721 * @todo Find proper type-hints
723 private static function addEntryAuthor($doc, $element, $contact_url, $item)
725 $contact = Contact::getDetailsByURL($contact_url, $item["uid"]);
727 $author = $doc->createElement($element);
728 XML::addElement($doc, $author, "name", $contact["name"]);
729 XML::addElement($doc, $author, "uri", $contact["url"]);
730 XML::addElement($doc, $author, "dfrn:handle", $contact["addr"]);
733 /// - Check real image type and image size
734 /// - Check which of these boths elements we should use
737 "type" => "image/jpeg",
739 "media:height" => 80,
740 "href" => $contact["photo"]];
741 XML::addElement($doc, $author, "link", "", $attributes);
745 "type" => "image/jpeg",
747 "media:height" => 80,
748 "href" => $contact["photo"]];
749 XML::addElement($doc, $author, "link", "", $attributes);
755 * @brief Adds the activity elements
757 * @param object $doc XML document
758 * @param string $element Element name for the activity
759 * @param string $activity activity value
761 * @return object XML activity object
762 * @todo Find proper type-hints
764 private static function createActivity($doc, $element, $activity)
767 $entry = $doc->createElement($element);
769 $r = XML::parseString($activity, false);
775 XML::addElement($doc, $entry, "activity:object-type", $r->type);
779 XML::addElement($doc, $entry, "id", $r->id);
783 XML::addElement($doc, $entry, "title", $r->title);
787 if (substr($r->link, 0, 1) == '<') {
788 if (strstr($r->link, '&') && (! strstr($r->link, '&'))) {
789 $r->link = str_replace('&', '&', $r->link);
792 $r->link = preg_replace('/\<link(.*?)\"\>/', '<link$1"/>', $r->link);
794 // XML does need a single element as root element so we add a dummy element here
795 $data = XML::parseString("<dummy>" . $r->link . "</dummy>", false);
796 if (is_object($data)) {
797 foreach ($data->link as $link) {
799 foreach ($link->attributes() as $parameter => $value) {
800 $attributes[$parameter] = $value;
802 XML::addElement($doc, $entry, "link", "", $attributes);
806 $attributes = ["rel" => "alternate", "type" => "text/html", "href" => $r->link];
807 XML::addElement($doc, $entry, "link", "", $attributes);
811 XML::addElement($doc, $entry, "content", BBCode::convert($r->content), ["type" => "html"]);
821 * @brief Adds the elements for attachments
823 * @param object $doc XML document
824 * @param object $root XML root
825 * @param array $item Item element
827 * @return object XML attachment object
828 * @todo Find proper type-hints
830 private static function getAttachment($doc, $root, $item)
832 $arr = explode('[/attach],', $item['attach']);
834 foreach ($arr as $r) {
836 $cnt = preg_match('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\" title=\"(.*?)\"|', $r, $matches);
838 $attributes = ["rel" => "enclosure",
839 "href" => $matches[1],
840 "type" => $matches[3]];
842 if (intval($matches[2])) {
843 $attributes["length"] = intval($matches[2]);
846 if (trim($matches[4]) != "") {
847 $attributes["title"] = trim($matches[4]);
850 XML::addElement($doc, $root, "link", "", $attributes);
857 * @brief Adds the "entry" elements for the DFRN protocol
859 * @param object $doc XML document
860 * @param string $type "text" or "html"
861 * @param array $item Item element
862 * @param array $owner Owner record
863 * @param bool $comment Trigger the sending of the "comment" element
864 * @param int $cid Contact ID of the recipient
865 * @param bool $single If set, the entry is created as an XML document with a single "entry" element
867 * @return object XML entry object
868 * @todo Find proper type-hints
870 private static function entry($doc, $type, array $item, array $owner, $comment = false, $cid = 0, $single = false)
874 if (!$item['parent']) {
878 if ($item['deleted']) {
879 $attributes = ["ref" => $item['uri'], "when" => DateTimeFormat::utc($item['edited'] . '+00:00', DateTimeFormat::ATOM)];
880 return XML::createElement($doc, "at:deleted-entry", "", $attributes);
884 $entry = $doc->createElement("entry");
886 $entry = $doc->createElementNS(NAMESPACE_ATOM1, 'entry');
887 $doc->appendChild($entry);
889 $entry->setAttribute("xmlns:thr", NAMESPACE_THREAD);
890 $entry->setAttribute("xmlns:at", NAMESPACE_TOMB);
891 $entry->setAttribute("xmlns:media", NAMESPACE_MEDIA);
892 $entry->setAttribute("xmlns:dfrn", NAMESPACE_DFRN);
893 $entry->setAttribute("xmlns:activity", NAMESPACE_ACTIVITY);
894 $entry->setAttribute("xmlns:georss", NAMESPACE_GEORSS);
895 $entry->setAttribute("xmlns:poco", NAMESPACE_POCO);
896 $entry->setAttribute("xmlns:ostatus", NAMESPACE_OSTATUS);
897 $entry->setAttribute("xmlns:statusnet", NAMESPACE_STATUSNET);
900 if ($item['private']) {
901 $body = Item::fixPrivatePhotos($item['body'], $owner['uid'], $item, $cid);
903 $body = $item['body'];
906 // Remove the abstract element. It is only locally important.
907 $body = BBCode::stripAbstract($body);
910 if ($type == 'html') {
913 if ($item['title'] != "") {
914 $htmlbody = "[b]" . $item['title'] . "[/b]\n\n" . $htmlbody;
917 $htmlbody = BBCode::convert($htmlbody, false, 7);
920 $author = self::addEntryAuthor($doc, "author", $item["author-link"], $item);
921 $entry->appendChild($author);
923 $dfrnowner = self::addEntryAuthor($doc, "dfrn:owner", $item["owner-link"], $item);
924 $entry->appendChild($dfrnowner);
926 if (($item['parent'] != $item['id']) || ($item['parent-uri'] !== $item['uri']) || (($item['thr-parent'] !== '') && ($item['thr-parent'] !== $item['uri']))) {
927 $parent_item = (($item['thr-parent']) ? $item['thr-parent'] : $item['parent-uri']);
928 $parent = Item::selectFirst(['guid', 'plink'], ['uri' => $parent_item, 'uid' => $item['uid']]);
929 $attributes = ["ref" => $parent_item, "type" => "text/html",
930 "href" => $parent['plink'],
931 "dfrn:diaspora_guid" => $parent['guid']];
932 XML::addElement($doc, $entry, "thr:in-reply-to", "", $attributes);
935 // Add conversation data. This is used for OStatus
936 $conversation_href = System::baseUrl()."/display/".$owner["nick"]."/".$item["parent"];
937 $conversation_uri = $conversation_href;
939 if (isset($parent_item)) {
940 $conversation = DBA::selectFirst('conversation', ['conversation-uri', 'conversation-href'], ['item-uri' => $item['parent-uri']]);
941 if (DBA::isResult($conversation)) {
942 if ($conversation['conversation-uri'] != '') {
943 $conversation_uri = $conversation['conversation-uri'];
945 if ($conversation['conversation-href'] != '') {
946 $conversation_href = $conversation['conversation-href'];
952 "href" => $conversation_href,
953 "ref" => $conversation_uri];
955 XML::addElement($doc, $entry, "ostatus:conversation", $conversation_uri, $attributes);
957 XML::addElement($doc, $entry, "id", $item["uri"]);
958 XML::addElement($doc, $entry, "title", $item["title"]);
960 XML::addElement($doc, $entry, "published", DateTimeFormat::utc($item["created"] . "+00:00", DateTimeFormat::ATOM));
961 XML::addElement($doc, $entry, "updated", DateTimeFormat::utc($item["edited"] . "+00:00", DateTimeFormat::ATOM));
963 // "dfrn:env" is used to read the content
964 XML::addElement($doc, $entry, "dfrn:env", base64url_encode($body, true));
966 // The "content" field is not read by the receiver. We could remove it when the type is "text"
967 // We keep it at the moment, maybe there is some old version that doesn't read "dfrn:env"
968 XML::addElement($doc, $entry, "content", (($type == 'html') ? $htmlbody : $body), ["type" => $type]);
970 // We save this value in "plink". Maybe we should read it from there as well?
976 ["rel" => "alternate", "type" => "text/html",
977 "href" => System::baseUrl() . "/display/" . $item["guid"]]
980 // "comment-allow" is some old fashioned stuff for old Friendica versions.
981 // It is included in the rewritten code for completeness
983 XML::addElement($doc, $entry, "dfrn:comment-allow", 1);
986 if ($item['location']) {
987 XML::addElement($doc, $entry, "dfrn:location", $item['location']);
990 if ($item['coord']) {
991 XML::addElement($doc, $entry, "georss:point", $item['coord']);
994 if ($item['private']) {
995 XML::addElement($doc, $entry, "dfrn:private", ($item['private'] ? $item['private'] : 1));
998 if ($item['extid']) {
999 XML::addElement($doc, $entry, "dfrn:extid", $item['extid']);
1002 if ($item['post-type'] == Item::PT_PAGE) {
1003 XML::addElement($doc, $entry, "dfrn:bookmark", "true");
1007 XML::addElement($doc, $entry, "statusnet:notice_info", "", ["local_id" => $item['id'], "source" => $item['app']]);
1010 XML::addElement($doc, $entry, "dfrn:diaspora_guid", $item["guid"]);
1012 // The signed text contains the content in Markdown, the sender handle and the signatur for the content
1013 // It is needed for relayed comments to Diaspora.
1014 if ($item['signed_text']) {
1015 $sign = base64_encode(json_encode(['signed_text' => $item['signed_text'],'signature' => $item['signature'],'signer' => $item['signer']]));
1016 XML::addElement($doc, $entry, "dfrn:diaspora_signature", $sign);
1019 XML::addElement($doc, $entry, "activity:verb", self::constructVerb($item));
1021 if ($item['object-type'] != "") {
1022 XML::addElement($doc, $entry, "activity:object-type", $item['object-type']);
1023 } elseif ($item['id'] == $item['parent']) {
1024 XML::addElement($doc, $entry, "activity:object-type", ACTIVITY_OBJ_NOTE);
1026 XML::addElement($doc, $entry, "activity:object-type", ACTIVITY_OBJ_COMMENT);
1029 $actobj = self::createActivity($doc, "activity:object", $item['object']);
1031 $entry->appendChild($actobj);
1034 $actarg = self::createActivity($doc, "activity:target", $item['target']);
1036 $entry->appendChild($actarg);
1039 $tags = Item::getFeedTags($item);
1041 /// @TODO Combine this with similar below if() block?
1043 foreach ($tags as $t) {
1044 if (($type != 'html') || ($t[0] != "@")) {
1045 XML::addElement($doc, $entry, "category", "", ["scheme" => "X-DFRN:".$t[0].":".$t[1], "term" => $t[2]]);
1051 foreach ($tags as $t) {
1053 $mentioned[$t[1]] = $t[1];
1058 foreach ($mentioned as $mention) {
1060 "SELECT `forum`, `prv` FROM `contact` WHERE `uid` = %d AND `nurl` = '%s'",
1061 intval($owner["uid"]),
1062 DBA::escape(normalise_link($mention))
1065 if (DBA::isResult($r) && ($r[0]["forum"] || $r[0]["prv"])) {
1071 ["rel" => "mentioned",
1072 "ostatus:object-type" => ACTIVITY_OBJ_GROUP,
1081 ["rel" => "mentioned",
1082 "ostatus:object-type" => ACTIVITY_OBJ_PERSON,
1088 self::getAttachment($doc, $entry, $item);
1094 * @brief encrypts data via AES
1096 * @param string $data The data that is to be encrypted
1097 * @param string $key The AES key
1099 * @return string encrypted data
1101 private static function aesEncrypt($data, $key)
1103 return openssl_encrypt($data, 'aes-128-ecb', $key, OPENSSL_RAW_DATA);
1107 * @brief decrypts data via AES
1109 * @param string $encrypted The encrypted data
1110 * @param string $key The AES key
1112 * @return string decrypted data
1114 public static function aesDecrypt($encrypted, $key)
1116 return openssl_decrypt($encrypted, 'aes-128-ecb', $key, OPENSSL_RAW_DATA);
1120 * @brief Delivers the atom content to the contacts
1122 * @param array $owner Owner record
1123 * @param array $contact Contact record of the receiver
1124 * @param string $atom Content that will be transmitted
1125 * @param bool $dissolve (to be documented)
1127 * @return int Deliver status. Negative values mean an error.
1128 * @todo Add array type-hint for $owner, $contact
1130 public static function deliver($owner, $contact, $atom, $dissolve = false)
1134 // At first try the Diaspora transport layer
1135 $ret = self::transmit($owner, $contact, $atom);
1137 logger('Delivery via Diaspora transport layer was successful with status ' . $ret);
1141 $idtosend = $orig_id = (($contact['dfrn-id']) ? $contact['dfrn-id'] : $contact['issued-id']);
1143 if ($contact['duplex'] && $contact['dfrn-id']) {
1144 $idtosend = '0:' . $orig_id;
1146 if ($contact['duplex'] && $contact['issued-id']) {
1147 $idtosend = '1:' . $orig_id;
1150 $rino = Config::get('system', 'rino_encrypt');
1151 $rino = intval($rino);
1153 logger("Local rino version: ". $rino, LOGGER_DEBUG);
1155 $ssl_val = intval(Config::get('system', 'ssl_policy'));
1159 case SSL_POLICY_FULL:
1160 $ssl_policy = 'full';
1162 case SSL_POLICY_SELFSIGN:
1163 $ssl_policy = 'self';
1165 case SSL_POLICY_NONE:
1167 $ssl_policy = 'none';
1171 $url = $contact['notify'] . '&dfrn_id=' . $idtosend . '&dfrn_version=' . DFRN_PROTOCOL_VERSION . (($rino) ? '&rino='.$rino : '');
1173 logger('dfrn_deliver: ' . $url);
1175 $ret = Network::curl($url);
1177 if (!empty($ret["errno"]) && ($ret['errno'] == CURLE_OPERATION_TIMEDOUT)) {
1178 Contact::markForArchival($contact);
1179 return -2; // timed out
1182 $xml = $ret['body'];
1184 $curl_stat = $a->get_curl_code();
1185 if (empty($curl_stat)) {
1186 Contact::markForArchival($contact);
1187 return -3; // timed out
1190 logger('dfrn_deliver: ' . $xml, LOGGER_DATA);
1193 Contact::markForArchival($contact);
1197 if (strpos($xml, '<?xml') === false) {
1198 logger('dfrn_deliver: no valid XML returned');
1199 logger('dfrn_deliver: returned XML: ' . $xml, LOGGER_DATA);
1200 Contact::markForArchival($contact);
1204 $res = XML::parseString($xml);
1206 if (!is_object($res) || (intval($res->status) != 0) || !strlen($res->challenge) || !strlen($res->dfrn_id)) {
1207 Contact::markForArchival($contact);
1209 if (empty($res->status)) {
1212 $status = $res->status;
1219 $sent_dfrn_id = hex2bin((string) $res->dfrn_id);
1220 $challenge = hex2bin((string) $res->challenge);
1221 $perm = (($res->perm) ? $res->perm : null);
1222 $dfrn_version = (float) (($res->dfrn_version) ? $res->dfrn_version : 2.0);
1223 $rino_remote_version = intval($res->rino);
1224 $page = (($owner['page-flags'] == Contact::PAGE_COMMUNITY) ? 1 : 0);
1226 logger("Remote rino version: ".$rino_remote_version." for ".$contact["url"], LOGGER_DEBUG);
1228 if ($owner['page-flags'] == Contact::PAGE_PRVGROUP) {
1232 $final_dfrn_id = '';
1235 if ((($perm == 'rw') && (! intval($contact['writable'])))
1236 || (($perm == 'r') && (intval($contact['writable'])))
1239 "update contact set writable = %d where id = %d",
1240 intval(($perm == 'rw') ? 1 : 0),
1241 intval($contact['id'])
1243 $contact['writable'] = (string) 1 - intval($contact['writable']);
1247 if (($contact['duplex'] && strlen($contact['pubkey']))
1248 || ($owner['page-flags'] == Contact::PAGE_COMMUNITY && strlen($contact['pubkey']))
1249 || ($contact['rel'] == Contact::SHARING && strlen($contact['pubkey']))
1251 openssl_public_decrypt($sent_dfrn_id, $final_dfrn_id, $contact['pubkey']);
1252 openssl_public_decrypt($challenge, $postvars['challenge'], $contact['pubkey']);
1254 openssl_private_decrypt($sent_dfrn_id, $final_dfrn_id, $contact['prvkey']);
1255 openssl_private_decrypt($challenge, $postvars['challenge'], $contact['prvkey']);
1258 $final_dfrn_id = substr($final_dfrn_id, 0, strpos($final_dfrn_id, '.'));
1260 if (strpos($final_dfrn_id, ':') == 1) {
1261 $final_dfrn_id = substr($final_dfrn_id, 2);
1264 if ($final_dfrn_id != $orig_id) {
1265 logger('dfrn_deliver: wrong dfrn_id.');
1266 // did not decode properly - cannot trust this site
1267 Contact::markForArchival($contact);
1271 $postvars['dfrn_id'] = $idtosend;
1272 $postvars['dfrn_version'] = DFRN_PROTOCOL_VERSION;
1274 $postvars['dissolve'] = '1';
1277 if ((($contact['rel']) && ($contact['rel'] != Contact::SHARING) && (! $contact['blocked'])) || ($owner['page-flags'] == Contact::PAGE_COMMUNITY)) {
1278 $postvars['data'] = $atom;
1279 $postvars['perm'] = 'rw';
1281 $postvars['data'] = str_replace('<dfrn:comment-allow>1', '<dfrn:comment-allow>0', $atom);
1282 $postvars['perm'] = 'r';
1285 $postvars['ssl_policy'] = $ssl_policy;
1288 $postvars['page'] = $page;
1292 if ($rino > 0 && $rino_remote_version > 0 && (! $dissolve)) {
1293 logger('rino version: '. $rino_remote_version);
1295 switch ($rino_remote_version) {
1297 $key = openssl_random_pseudo_bytes(16);
1298 $data = self::aesEncrypt($postvars['data'], $key);
1301 logger("rino: invalid requested version '$rino_remote_version'");
1302 Contact::markForArchival($contact);
1306 $postvars['rino'] = $rino_remote_version;
1307 $postvars['data'] = bin2hex($data);
1309 if ($dfrn_version >= 2.1) {
1310 if (($contact['duplex'] && strlen($contact['pubkey']))
1311 || ($owner['page-flags'] == Contact::PAGE_COMMUNITY && strlen($contact['pubkey']))
1312 || ($contact['rel'] == Contact::SHARING && strlen($contact['pubkey']))
1314 openssl_public_encrypt($key, $postvars['key'], $contact['pubkey']);
1316 openssl_private_encrypt($key, $postvars['key'], $contact['prvkey']);
1319 if (($contact['duplex'] && strlen($contact['prvkey'])) || ($owner['page-flags'] == Contact::PAGE_COMMUNITY)) {
1320 openssl_private_encrypt($key, $postvars['key'], $contact['prvkey']);
1322 openssl_public_encrypt($key, $postvars['key'], $contact['pubkey']);
1326 logger('md5 rawkey ' . md5($postvars['key']));
1328 $postvars['key'] = bin2hex($postvars['key']);
1332 logger('dfrn_deliver: ' . "SENDING: " . print_r($postvars, true), LOGGER_DATA);
1334 $xml = Network::post($contact['notify'], $postvars);
1336 logger('dfrn_deliver: ' . "RECEIVED: " . $xml, LOGGER_DATA);
1338 $curl_stat = $a->get_curl_code();
1339 if (empty($curl_stat) || empty($xml)) {
1340 Contact::markForArchival($contact);
1341 return -9; // timed out
1344 if (($curl_stat == 503) && stristr($a->get_curl_headers(), 'retry-after')) {
1345 Contact::markForArchival($contact);
1349 if (strpos($xml, '<?xml') === false) {
1350 logger('dfrn_deliver: phase 2: no valid XML returned');
1351 logger('dfrn_deliver: phase 2: returned XML: ' . $xml, LOGGER_DATA);
1352 Contact::markForArchival($contact);
1356 $res = XML::parseString($xml);
1358 if (!isset($res->status)) {
1359 Contact::markForArchival($contact);
1363 // Possibly old servers had returned an empty value when everything was okay
1364 if (empty($res->status)) {
1368 if (!empty($res->message)) {
1369 logger('Delivery returned status '.$res->status.' - '.$res->message, LOGGER_DEBUG);
1372 if (($res->status >= 200) && ($res->status <= 299)) {
1373 Contact::unmarkForArchival($contact);
1376 return intval($res->status);
1380 * @brief Transmits atom content to the contacts via the Diaspora transport layer
1382 * @param array $owner Owner record
1383 * @param array $contact Contact record of the receiver
1384 * @param string $atom Content that will be transmitted
1386 * @return int Deliver status. Negative values mean an error.
1388 public static function transmit($owner, $contact, $atom, $public_batch = false)
1392 if (!$public_batch) {
1393 if (empty($contact['addr'])) {
1394 logger('Empty contact handle for ' . $contact['id'] . ' - ' . $contact['url'] . ' - trying to update it.');
1395 if (Contact::updateFromProbe($contact['id'])) {
1396 $new_contact = DBA::selectFirst('contact', ['addr'], ['id' => $contact['id']]);
1397 $contact['addr'] = $new_contact['addr'];
1400 if (empty($contact['addr'])) {
1401 logger('Unable to find contact handle for ' . $contact['id'] . ' - ' . $contact['url']);
1402 Contact::markForArchival($contact);
1407 $fcontact = Diaspora::personByHandle($contact['addr']);
1408 if (empty($fcontact)) {
1409 logger('Unable to find contact details for ' . $contact['id'] . ' - ' . $contact['addr']);
1410 Contact::markForArchival($contact);
1413 $pubkey = $fcontact['pubkey'];
1418 $envelope = Diaspora::buildMessage($atom, $owner, $contact, $owner['uprvkey'], $pubkey, $public_batch);
1420 // Create the endpoint for public posts. This is some WIP and should later be added to the probing
1421 if ($public_batch && empty($contact["batch"])) {
1422 $parts = parse_url($contact["notify"]);
1423 $path_parts = explode('/', $parts['path']);
1424 array_pop($path_parts);
1425 $parts['path'] = implode('/', $path_parts);
1426 $contact["batch"] = Network::unparseURL($parts);
1429 $dest_url = ($public_batch ? $contact["batch"] : $contact["notify"]);
1431 $content_type = ($public_batch ? "application/magic-envelope+xml" : "application/json");
1433 $xml = Network::post($dest_url, $envelope, ["Content-Type: ".$content_type]);
1435 $curl_stat = $a->get_curl_code();
1436 if (empty($curl_stat) || empty($xml)) {
1437 logger('Empty answer from ' . $contact['id'] . ' - ' . $dest_url);
1438 Contact::markForArchival($contact);
1439 return -9; // timed out
1442 if (($curl_stat == 503) && (stristr($a->get_curl_headers(), 'retry-after'))) {
1443 Contact::markForArchival($contact);
1447 if (strpos($xml, '<?xml') === false) {
1448 logger('No valid XML returned from ' . $contact['id'] . ' - ' . $dest_url);
1449 logger('Returned XML: ' . $xml, LOGGER_DATA);
1450 Contact::markForArchival($contact);
1454 $res = XML::parseString($xml);
1456 if (empty($res->status)) {
1457 Contact::markForArchival($contact);
1461 if (!empty($res->message)) {
1462 logger('Transmit to ' . $dest_url . ' returned status '.$res->status.' - '.$res->message, LOGGER_DEBUG);
1465 if (($res->status >= 200) && ($res->status <= 299)) {
1466 Contact::unmarkForArchival($contact);
1469 return intval($res->status);
1473 * @brief Add new birthday event for this person
1475 * @param array $contact Contact record
1476 * @param string $birthday Birthday of the contact
1478 * @todo Add array type-hint for $contact
1480 private static function birthdayEvent($contact, $birthday)
1482 // Check for duplicates
1484 "SELECT `id` FROM `event` WHERE `uid` = %d AND `cid` = %d AND `start` = '%s' AND `type` = '%s' LIMIT 1",
1485 intval($contact['uid']),
1486 intval($contact['id']),
1487 DBA::escape(DateTimeFormat::utc($birthday)),
1488 DBA::escape('birthday')
1491 if (DBA::isResult($r)) {
1495 logger('updating birthday: ' . $birthday . ' for contact ' . $contact['id']);
1497 $bdtext = L10n::t('%s\'s birthday', $contact['name']);
1498 $bdtext2 = L10n::t('Happy Birthday %s', ' [url=' . $contact['url'] . ']' . $contact['name'] . '[/url]');
1501 "INSERT INTO `event` (`uid`,`cid`,`created`,`edited`,`start`,`finish`,`summary`,`desc`,`type`)
1502 VALUES ( %d, %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s') ",
1503 intval($contact['uid']),
1504 intval($contact['id']),
1505 DBA::escape(DateTimeFormat::utcNow()),
1506 DBA::escape(DateTimeFormat::utcNow()),
1507 DBA::escape(DateTimeFormat::utc($birthday)),
1508 DBA::escape(DateTimeFormat::utc($birthday . ' + 1 day ')),
1509 DBA::escape($bdtext),
1510 DBA::escape($bdtext2),
1511 DBA::escape('birthday')
1516 * @brief Fetch the author data from head or entry items
1518 * @param object $xpath XPath object
1519 * @param object $context In which context should the data be searched
1520 * @param array $importer Record of the importer user mixed with contact of the content
1521 * @param string $element Element name from which the data is fetched
1522 * @param bool $onlyfetch Should the data only be fetched or should it update the contact record as well
1523 * @param string $xml optional, default empty
1525 * @return array Relevant data of the author
1526 * @todo Find good type-hints for all parameter
1528 private static function fetchauthor($xpath, $context, $importer, $element, $onlyfetch, $xml = "")
1531 $author["name"] = XML::getFirstNodeValue($xpath, $element."/atom:name/text()", $context);
1532 $author["link"] = XML::getFirstNodeValue($xpath, $element."/atom:uri/text()", $context);
1534 $fields = ['id', 'uid', 'url', 'network', 'avatar-date', 'avatar', 'name-date', 'uri-date', 'addr',
1535 'name', 'nick', 'about', 'location', 'keywords', 'xmpp', 'bdyear', 'bd', 'hidden', 'contact-type'];
1536 $condition = ["`uid` = ? AND `nurl` = ? AND `network` != ?",
1537 $importer["importer_uid"], normalise_link($author["link"]), Protocol::STATUSNET];
1538 $contact_old = DBA::selectFirst('contact', $fields, $condition);
1540 if (DBA::isResult($contact_old)) {
1541 $author["contact-id"] = $contact_old["id"];
1542 $author["network"] = $contact_old["network"];
1545 logger("Contact ".$author["link"]." wasn't found for user ".$importer["importer_uid"]." XML: ".$xml, LOGGER_DEBUG);
1548 $author["contact-unknown"] = true;
1549 $author["contact-id"] = $importer["id"];
1550 $author["network"] = $importer["network"];
1554 // Until now we aren't serving different sizes - but maybe later
1556 /// @todo check if "avatar" or "photo" would be the best field in the specification
1557 $avatars = $xpath->query($element . "/atom:link[@rel='avatar']", $context);
1558 foreach ($avatars as $avatar) {
1561 foreach ($avatar->attributes as $attributes) {
1562 /// @TODO Rewrite these similar if() to one switch
1563 if ($attributes->name == "href") {
1564 $href = $attributes->textContent;
1566 if ($attributes->name == "width") {
1567 $width = $attributes->textContent;
1569 if ($attributes->name == "updated") {
1570 $author["avatar-date"] = $attributes->textContent;
1573 if (($width > 0) && ($href != "")) {
1574 $avatarlist[$width] = $href;
1578 if (count($avatarlist) > 0) {
1579 krsort($avatarlist);
1580 $author["avatar"] = current($avatarlist);
1583 if (DBA::isResult($contact_old) && !$onlyfetch) {
1584 logger("Check if contact details for contact " . $contact_old["id"] . " (" . $contact_old["nick"] . ") have to be updated.", LOGGER_DEBUG);
1586 $poco = ["url" => $contact_old["url"]];
1588 // When was the last change to name or uri?
1589 $name_element = $xpath->query($element . "/atom:name", $context)->item(0);
1590 foreach ($name_element->attributes as $attributes) {
1591 if ($attributes->name == "updated") {
1592 $poco["name-date"] = $attributes->textContent;
1596 $link_element = $xpath->query($element . "/atom:link", $context)->item(0);
1597 foreach ($link_element->attributes as $attributes) {
1598 if ($attributes->name == "updated") {
1599 $poco["uri-date"] = $attributes->textContent;
1603 // Update contact data
1604 $value = XML::getFirstNodeValue($xpath, $element . "/dfrn:handle/text()", $context);
1606 $poco["addr"] = $value;
1609 $value = XML::getFirstNodeValue($xpath, $element . "/poco:displayName/text()", $context);
1611 $poco["name"] = $value;
1614 $value = XML::getFirstNodeValue($xpath, $element . "/poco:preferredUsername/text()", $context);
1616 $poco["nick"] = $value;
1619 $value = XML::getFirstNodeValue($xpath, $element . "/poco:note/text()", $context);
1621 $poco["about"] = $value;
1624 $value = XML::getFirstNodeValue($xpath, $element . "/poco:address/poco:formatted/text()", $context);
1626 $poco["location"] = $value;
1629 /// @todo Only search for elements with "poco:type" = "xmpp"
1630 $value = XML::getFirstNodeValue($xpath, $element . "/poco:ims/poco:value/text()", $context);
1632 $poco["xmpp"] = $value;
1635 /// @todo Add support for the following fields that we don't support by now in the contact table:
1636 /// - poco:utcOffset
1642 // If the "hide" element is present then the profile isn't searchable.
1643 $hide = intval(XML::getFirstNodeValue($xpath, $element . "/dfrn:hide/text()", $context) == "true");
1645 logger("Hidden status for contact " . $contact_old["url"] . ": " . $hide, LOGGER_DEBUG);
1647 // If the contact isn't searchable then set the contact to "hidden".
1648 // Problem: This can be manually overridden by the user.
1650 $contact_old["hidden"] = true;
1653 // Save the keywords into the contact table
1655 $tagelements = $xpath->evaluate($element . "/poco:tags/text()", $context);
1656 foreach ($tagelements as $tag) {
1657 $tags[$tag->nodeValue] = $tag->nodeValue;
1661 $poco["keywords"] = implode(", ", $tags);
1664 // "dfrn:birthday" contains the birthday converted to UTC
1665 $birthday = XML::getFirstNodeValue($xpath, $element . "/poco:birthday/text()", $context);
1667 if (strtotime($birthday) > time()) {
1668 $bd_timestamp = strtotime($birthday);
1670 $poco["bdyear"] = date("Y", $bd_timestamp);
1673 // "poco:birthday" is the birthday in the format "yyyy-mm-dd"
1674 $value = XML::getFirstNodeValue($xpath, $element . "/poco:birthday/text()", $context);
1676 if (!in_array($value, ["", "0000-00-00", "0001-01-01"])) {
1677 $bdyear = date("Y");
1678 $value = str_replace("0000", $bdyear, $value);
1680 if (strtotime($value) < time()) {
1681 $value = str_replace($bdyear, $bdyear + 1, $value);
1682 $bdyear = $bdyear + 1;
1685 $poco["bd"] = $value;
1688 $contact = array_merge($contact_old, $poco);
1690 if ($contact_old["bdyear"] != $contact["bdyear"]) {
1691 self::birthdayEvent($contact, $birthday);
1694 // Get all field names
1696 foreach ($contact_old as $field => $data) {
1697 $fields[$field] = $data;
1700 unset($fields["id"]);
1701 unset($fields["uid"]);
1702 unset($fields["url"]);
1703 unset($fields["avatar-date"]);
1704 unset($fields["avatar"]);
1705 unset($fields["name-date"]);
1706 unset($fields["uri-date"]);
1709 // Update check for this field has to be done differently
1710 $datefields = ["name-date", "uri-date"];
1711 foreach ($datefields as $field) {
1712 if (strtotime($contact[$field]) > strtotime($contact_old[$field])) {
1713 logger("Difference for contact " . $contact["id"] . " in field '" . $field . "'. New value: '" . $contact[$field] . "', old value '" . $contact_old[$field] . "'", LOGGER_DEBUG);
1718 foreach ($fields as $field => $data) {
1719 if ($contact[$field] != $contact_old[$field]) {
1720 logger("Difference for contact " . $contact["id"] . " in field '" . $field . "'. New value: '" . $contact[$field] . "', old value '" . $contact_old[$field] . "'", LOGGER_DEBUG);
1726 logger("Update contact data for contact " . $contact["id"] . " (" . $contact["nick"] . ")", LOGGER_DEBUG);
1729 "UPDATE `contact` SET `name` = '%s', `nick` = '%s', `about` = '%s', `location` = '%s',
1730 `addr` = '%s', `keywords` = '%s', `bdyear` = '%s', `bd` = '%s', `hidden` = %d,
1731 `xmpp` = '%s', `name-date` = '%s', `uri-date` = '%s'
1732 WHERE `id` = %d AND `network` = '%s'",
1733 DBA::escape($contact["name"]), DBA::escape($contact["nick"]), DBA::escape($contact["about"]), DBA::escape($contact["location"]),
1734 DBA::escape($contact["addr"]), DBA::escape($contact["keywords"]), DBA::escape($contact["bdyear"]),
1735 DBA::escape($contact["bd"]), intval($contact["hidden"]), DBA::escape($contact["xmpp"]),
1736 DBA::escape(DateTimeFormat::utc($contact["name-date"])), DBA::escape(DateTimeFormat::utc($contact["uri-date"])),
1737 intval($contact["id"]), DBA::escape($contact["network"])
1741 Contact::updateAvatar(
1743 $importer['importer_uid'],
1745 (strtotime($contact['avatar-date']) > strtotime($contact_old['avatar-date']) || ($author['avatar'] != $contact_old['avatar']))
1749 * The generation is a sign for the reliability of the provided data.
1750 * It is used in the socgraph.php to prevent that old contact data
1751 * that was relayed over several servers can overwrite contact
1752 * data that we received directly.
1755 $poco["generation"] = 2;
1756 $poco["photo"] = $author["avatar"];
1757 $poco["hide"] = $hide;
1758 $poco["contact-type"] = $contact["contact-type"];
1759 $gcid = GContact::update($poco);
1761 GContact::link($gcid, $importer["importer_uid"], $contact["id"]);
1768 * @brief Transforms activity objects into an XML string
1770 * @param object $xpath XPath object
1771 * @param object $activity Activity object
1772 * @param string $element element name
1774 * @return string XML string
1775 * @todo Find good type-hints for all parameter
1777 private static function transformActivity($xpath, $activity, $element)
1779 if (!is_object($activity)) {
1783 $obj_doc = new DOMDocument("1.0", "utf-8");
1784 $obj_doc->formatOutput = true;
1786 $obj_element = $obj_doc->createElementNS(NAMESPACE_ATOM1, $element);
1788 $activity_type = $xpath->query("activity:object-type/text()", $activity)->item(0)->nodeValue;
1789 XML::addElement($obj_doc, $obj_element, "type", $activity_type);
1791 $id = $xpath->query("atom:id", $activity)->item(0);
1792 if (is_object($id)) {
1793 $obj_element->appendChild($obj_doc->importNode($id, true));
1796 $title = $xpath->query("atom:title", $activity)->item(0);
1797 if (is_object($title)) {
1798 $obj_element->appendChild($obj_doc->importNode($title, true));
1801 $links = $xpath->query("atom:link", $activity);
1802 if (is_object($links)) {
1803 foreach ($links as $link) {
1804 $obj_element->appendChild($obj_doc->importNode($link, true));
1808 $content = $xpath->query("atom:content", $activity)->item(0);
1809 if (is_object($content)) {
1810 $obj_element->appendChild($obj_doc->importNode($content, true));
1813 $obj_doc->appendChild($obj_element);
1815 $objxml = $obj_doc->saveXML($obj_element);
1817 /// @todo This isn't totally clean. We should find a way to transform the namespaces
1818 $objxml = str_replace("<".$element.' xmlns="http://www.w3.org/2005/Atom">', "<".$element.">", $objxml);
1823 * @brief Processes the mail elements
1825 * @param object $xpath XPath object
1826 * @param object $mail mail elements
1827 * @param array $importer Record of the importer user mixed with contact of the content
1829 * @todo Find good type-hints for all parameter
1831 private static function processMail($xpath, $mail, $importer)
1833 logger("Processing mails");
1835 /// @TODO Rewrite this to one statement
1837 $msg["uid"] = $importer["importer_uid"];
1838 $msg["from-name"] = $xpath->query("dfrn:sender/dfrn:name/text()", $mail)->item(0)->nodeValue;
1839 $msg["from-url"] = $xpath->query("dfrn:sender/dfrn:uri/text()", $mail)->item(0)->nodeValue;
1840 $msg["from-photo"] = $xpath->query("dfrn:sender/dfrn:avatar/text()", $mail)->item(0)->nodeValue;
1841 $msg["contact-id"] = $importer["id"];
1842 $msg["uri"] = $xpath->query("dfrn:id/text()", $mail)->item(0)->nodeValue;
1843 $msg["parent-uri"] = $xpath->query("dfrn:in-reply-to/text()", $mail)->item(0)->nodeValue;
1844 $msg["created"] = DateTimeFormat::utc($xpath->query("dfrn:sentdate/text()", $mail)->item(0)->nodeValue);
1845 $msg["title"] = $xpath->query("dfrn:subject/text()", $mail)->item(0)->nodeValue;
1846 $msg["body"] = $xpath->query("dfrn:content/text()", $mail)->item(0)->nodeValue;
1848 $msg["replied"] = 0;
1850 DBA::insert('mail', $msg);
1852 $msg["id"] = DBA::lastInsertId();
1854 // send notifications.
1855 /// @TODO Arange this mess
1857 "type" => NOTIFY_MAIL,
1858 "notify_flags" => $importer["notify-flags"],
1859 "language" => $importer["language"],
1860 "to_name" => $importer["username"],
1861 "to_email" => $importer["email"],
1862 "uid" => $importer["importer_uid"],
1864 "source_name" => $msg["from-name"],
1865 "source_link" => $importer["url"],
1866 "source_photo" => $importer["thumb"],
1867 "verb" => ACTIVITY_POST,
1871 notification($notif_params);
1873 logger("Mail is processed, notification was sent.");
1877 * @brief Processes the suggestion elements
1879 * @param object $xpath XPath object
1880 * @param object $suggestion suggestion elements
1881 * @param array $importer Record of the importer user mixed with contact of the content
1883 * @todo Find good type-hints for all parameter
1885 private static function processSuggestion($xpath, $suggestion, $importer)
1889 logger("Processing suggestions");
1891 /// @TODO Rewrite this to one statement
1893 $suggest["uid"] = $importer["importer_uid"];
1894 $suggest["cid"] = $importer["id"];
1895 $suggest["url"] = $xpath->query("dfrn:url/text()", $suggestion)->item(0)->nodeValue;
1896 $suggest["name"] = $xpath->query("dfrn:name/text()", $suggestion)->item(0)->nodeValue;
1897 $suggest["photo"] = $xpath->query("dfrn:photo/text()", $suggestion)->item(0)->nodeValue;
1898 $suggest["request"] = $xpath->query("dfrn:request/text()", $suggestion)->item(0)->nodeValue;
1899 $suggest["body"] = $xpath->query("dfrn:note/text()", $suggestion)->item(0)->nodeValue;
1901 // Does our member already have a friend matching this description?
1904 "SELECT `id` FROM `contact` WHERE `name` = '%s' AND `nurl` = '%s' AND `uid` = %d LIMIT 1",
1905 DBA::escape($suggest["name"]),
1906 DBA::escape(normalise_link($suggest["url"])),
1907 intval($suggest["uid"])
1911 * The valid result means the friend we're about to send a friend
1912 * suggestion already has them in their contact, which means no further
1913 * action is required.
1915 * @see https://github.com/friendica/friendica/pull/3254#discussion_r107315246
1917 if (DBA::isResult($r)) {
1921 // Do we already have an fcontact record for this person?
1925 "SELECT `id` FROM `fcontact` WHERE `url` = '%s' AND `name` = '%s' AND `request` = '%s' LIMIT 1",
1926 DBA::escape($suggest["url"]),
1927 DBA::escape($suggest["name"]),
1928 DBA::escape($suggest["request"])
1930 if (DBA::isResult($r)) {
1933 // OK, we do. Do we already have an introduction for this person ?
1935 "SELECT `id` FROM `intro` WHERE `uid` = %d AND `fid` = %d LIMIT 1",
1936 intval($suggest["uid"]),
1941 * The valid result means the friend we're about to send a friend
1942 * suggestion already has them in their contact, which means no further
1943 * action is required.
1945 * @see https://github.com/friendica/friendica/pull/3254#discussion_r107315246
1947 if (DBA::isResult($r)) {
1953 "INSERT INTO `fcontact` (`name`,`url`,`photo`,`request`) VALUES ('%s', '%s', '%s', '%s')",
1954 DBA::escape($suggest["name"]),
1955 DBA::escape($suggest["url"]),
1956 DBA::escape($suggest["photo"]),
1957 DBA::escape($suggest["request"])
1961 "SELECT `id` FROM `fcontact` WHERE `url` = '%s' AND `name` = '%s' AND `request` = '%s' LIMIT 1",
1962 DBA::escape($suggest["url"]),
1963 DBA::escape($suggest["name"]),
1964 DBA::escape($suggest["request"])
1968 * If no record in fcontact is found, below INSERT statement will not
1969 * link an introduction to it.
1971 if (!DBA::isResult($r)) {
1972 // Database record did not get created. Quietly give up.
1978 $hash = random_string();
1981 "INSERT INTO `intro` (`uid`, `fid`, `contact-id`, `note`, `hash`, `datetime`, `blocked`)
1982 VALUES(%d, %d, %d, '%s', '%s', '%s', %d)",
1983 intval($suggest["uid"]),
1985 intval($suggest["cid"]),
1986 DBA::escape($suggest["body"]),
1988 DBA::escape(DateTimeFormat::utcNow()),
1994 "type" => NOTIFY_SUGGEST,
1995 "notify_flags" => $importer["notify-flags"],
1996 "language" => $importer["language"],
1997 "to_name" => $importer["username"],
1998 "to_email" => $importer["email"],
1999 "uid" => $importer["importer_uid"],
2001 "link" => System::baseUrl()."/notifications/intros",
2002 "source_name" => $importer["name"],
2003 "source_link" => $importer["url"],
2004 "source_photo" => $importer["photo"],
2005 "verb" => ACTIVITY_REQ_FRIEND,
2013 * @brief Processes the relocation elements
2015 * @param object $xpath XPath object
2016 * @param object $relocation relocation elements
2017 * @param array $importer Record of the importer user mixed with contact of the content
2019 * @todo Find good type-hints for all parameter
2021 private static function processRelocation($xpath, $relocation, $importer)
2023 logger("Processing relocations");
2025 /// @TODO Rewrite this to one statement
2027 $relocate["uid"] = $importer["importer_uid"];
2028 $relocate["cid"] = $importer["id"];
2029 $relocate["url"] = $xpath->query("dfrn:url/text()", $relocation)->item(0)->nodeValue;
2030 $relocate["addr"] = $xpath->query("dfrn:addr/text()", $relocation)->item(0)->nodeValue;
2031 $relocate["name"] = $xpath->query("dfrn:name/text()", $relocation)->item(0)->nodeValue;
2032 $relocate["avatar"] = $xpath->query("dfrn:avatar/text()", $relocation)->item(0)->nodeValue;
2033 $relocate["photo"] = $xpath->query("dfrn:photo/text()", $relocation)->item(0)->nodeValue;
2034 $relocate["thumb"] = $xpath->query("dfrn:thumb/text()", $relocation)->item(0)->nodeValue;
2035 $relocate["micro"] = $xpath->query("dfrn:micro/text()", $relocation)->item(0)->nodeValue;
2036 $relocate["request"] = $xpath->query("dfrn:request/text()", $relocation)->item(0)->nodeValue;
2037 $relocate["confirm"] = $xpath->query("dfrn:confirm/text()", $relocation)->item(0)->nodeValue;
2038 $relocate["notify"] = $xpath->query("dfrn:notify/text()", $relocation)->item(0)->nodeValue;
2039 $relocate["poll"] = $xpath->query("dfrn:poll/text()", $relocation)->item(0)->nodeValue;
2040 $relocate["sitepubkey"] = $xpath->query("dfrn:sitepubkey/text()", $relocation)->item(0)->nodeValue;
2042 if (($relocate["avatar"] == "") && ($relocate["photo"] != "")) {
2043 $relocate["avatar"] = $relocate["photo"];
2046 if ($relocate["addr"] == "") {
2047 $relocate["addr"] = preg_replace("=(https?://)(.*)/profile/(.*)=ism", "$3@$2", $relocate["url"]);
2052 "SELECT `photo`, `url` FROM `contact` WHERE `id` = %d AND `uid` = %d",
2053 intval($importer["id"]),
2054 intval($importer["importer_uid"])
2057 if (!DBA::isResult($r)) {
2058 logger("Query failed to execute, no result returned in " . __FUNCTION__);
2064 // Update the gcontact entry
2065 $relocate["server_url"] = preg_replace("=(https?://)(.*)/profile/(.*)=ism", "$1$2", $relocate["url"]);
2067 $fields = ['name' => $relocate["name"], 'photo' => $relocate["avatar"],
2068 'url' => $relocate["url"], 'nurl' => normalise_link($relocate["url"]),
2069 'addr' => $relocate["addr"], 'connect' => $relocate["addr"],
2070 'notify' => $relocate["notify"], 'server_url' => $relocate["server_url"]];
2071 DBA::update('gcontact', $fields, ['nurl' => normalise_link($old["url"])]);
2073 // Update the contact table. We try to find every entry.
2074 $fields = ['name' => $relocate["name"], 'avatar' => $relocate["avatar"],
2075 'url' => $relocate["url"], 'nurl' => normalise_link($relocate["url"]),
2076 'addr' => $relocate["addr"], 'request' => $relocate["request"],
2077 'confirm' => $relocate["confirm"], 'notify' => $relocate["notify"],
2078 'poll' => $relocate["poll"], 'site-pubkey' => $relocate["sitepubkey"]];
2079 $condition = ["(`id` = ?) OR (`nurl` = ?)", $importer["id"], normalise_link($old["url"])];
2081 DBA::update('contact', $fields, $condition);
2083 Contact::updateAvatar($relocate["avatar"], $importer["importer_uid"], $importer["id"], true);
2085 logger('Contacts are updated.');
2088 /// merge with current record, current contents have priority
2089 /// update record, set url-updated
2090 /// update profile photos
2091 /// schedule a scan?
2096 * @brief Updates an item
2098 * @param array $current the current item record
2099 * @param array $item the new item record
2100 * @param array $importer Record of the importer user mixed with contact of the content
2101 * @param int $entrytype Is it a toplevel entry, a comment or a relayed comment?
2103 * @todo set proper type-hints (array?)
2105 private static function updateContent($current, $item, $importer, $entrytype)
2109 if (self::isEditedTimestampNewer($current, $item)) {
2110 // do not accept (ignore) an earlier edit than one we currently have.
2111 if (DateTimeFormat::utc($item["edited"]) < $current["edited"]) {
2115 $fields = ['title' => defaults($item, 'title', ''), 'body' => defaults($item, 'body', ''),
2116 'tag' => defaults($item, 'tag', ''), 'changed' => DateTimeFormat::utcNow(),
2117 'edited' => DateTimeFormat::utc($item["edited"])];
2119 $condition = ["`uri` = ? AND `uid` IN (0, ?)", $item["uri"], $importer["importer_uid"]];
2120 Item::update($fields, $condition);
2128 * @brief Detects the entry type of the item
2130 * @param array $importer Record of the importer user mixed with contact of the content
2131 * @param array $item the new item record
2133 * @return int Is it a toplevel entry, a comment or a relayed comment?
2134 * @todo set proper type-hints (array?)
2136 private static function getEntryType($importer, $item)
2138 if ($item["parent-uri"] != $item["uri"]) {
2141 if ($importer["page-flags"] == Contact::PAGE_COMMUNITY || $importer["page-flags"] == Contact::PAGE_PRVGROUP) {
2144 logger("possible community action");
2146 $sql_extra = " AND `contact`.`self` AND `item`.`wall` ";
2149 // was the top-level post for this action written by somebody on this site?
2150 // Specifically, the recipient?
2152 $is_a_remote_action = false;
2154 $parent = Item::selectFirst(['parent-uri'], ['uri' => $item["parent-uri"]]);
2155 if (DBA::isResult($parent)) {
2157 "SELECT `item`.`forum_mode`, `item`.`wall` FROM `item`
2158 INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
2159 WHERE `item`.`uri` = '%s' AND (`item`.`parent-uri` = '%s' OR `item`.`thr-parent` = '%s')
2160 AND `item`.`uid` = %d
2163 DBA::escape($parent["parent-uri"]),
2164 DBA::escape($parent["parent-uri"]),
2165 DBA::escape($parent["parent-uri"]),
2166 intval($importer["importer_uid"])
2168 if (DBA::isResult($r)) {
2169 $is_a_remote_action = true;
2174 * Does this have the characteristics of a community or private group action?
2175 * If it's an action to a wall post on a community/prvgroup page it's a
2176 * valid community action. Also forum_mode makes it valid for sure.
2177 * If neither, it's not.
2179 if ($is_a_remote_action && $community && (!$r[0]["forum_mode"]) && (!$r[0]["wall"])) {
2180 $is_a_remote_action = false;
2181 logger("not a community action");
2184 if ($is_a_remote_action) {
2185 return DFRN::REPLY_RC;
2190 return DFRN::TOP_LEVEL;
2195 * @brief Send a "poke"
2197 * @param array $item the new item record
2198 * @param array $importer Record of the importer user mixed with contact of the content
2199 * @param int $posted_id The record number of item record that was just posted
2201 * @todo set proper type-hints (array?)
2203 private static function doPoke($item, $importer, $posted_id)
2205 $verb = urldecode(substr($item["verb"], strpos($item["verb"], "#")+1));
2209 $xo = XML::parseString($item["object"], false);
2211 if (($xo->type == ACTIVITY_OBJ_PERSON) && ($xo->id)) {
2212 // somebody was poked/prodded. Was it me?
2213 foreach ($xo->link as $l) {
2214 $atts = $l->attributes();
2215 switch ($atts["rel"]) {
2217 $Blink = $atts["href"];
2224 if ($Blink && link_compare($Blink, System::baseUrl() . "/profile/" . $importer["nickname"])) {
2225 $author = DBA::selectFirst('contact', ['name', 'thumb', 'url'], ['id' => $item['author-id']]);
2227 // send a notification
2230 "type" => NOTIFY_POKE,
2231 "notify_flags" => $importer["notify-flags"],
2232 "language" => $importer["language"],
2233 "to_name" => $importer["username"],
2234 "to_email" => $importer["email"],
2235 "uid" => $importer["importer_uid"],
2237 "link" => System::baseUrl()."/display/".urlencode(Item::getGuidById($posted_id)),
2238 "source_name" => $author["name"],
2239 "source_link" => $author["url"],
2240 "source_photo" => $author["thumb"],
2241 "verb" => $item["verb"],
2242 "otype" => "person",
2243 "activity" => $verb,
2244 "parent" => $item["parent"]]
2251 * @brief Processes several actions, depending on the verb
2253 * @param int $entrytype Is it a toplevel entry, a comment or a relayed comment?
2254 * @param array $importer Record of the importer user mixed with contact of the content
2255 * @param array $item the new item record
2256 * @param bool $is_like Is the verb a "like"?
2258 * @return bool Should the processing of the entries be continued?
2259 * @todo set proper type-hints (array?)
2261 private static function processVerbs($entrytype, $importer, &$item, &$is_like)
2263 logger("Process verb ".$item["verb"]." and object-type ".$item["object-type"]." for entrytype ".$entrytype, LOGGER_DEBUG);
2265 if (($entrytype == DFRN::TOP_LEVEL)) {
2266 // The filling of the the "contact" variable is done for legcy reasons
2267 // The functions below are partly used by ostatus.php as well - where we have this variable
2268 $r = q("SELECT * FROM `contact` WHERE `id` = %d", intval($importer["id"]));
2270 $nickname = $contact["nick"];
2272 // Big question: Do we need these functions? They were part of the "consume_feed" function.
2273 // This function once was responsible for DFRN and OStatus.
2274 if (activity_match($item["verb"], ACTIVITY_FOLLOW)) {
2275 logger("New follower");
2276 Contact::addRelationship($importer, $contact, $item, $nickname);
2279 if (activity_match($item["verb"], ACTIVITY_UNFOLLOW)) {
2280 logger("Lost follower");
2281 Contact::removeFollower($importer, $contact, $item);
2284 if (activity_match($item["verb"], ACTIVITY_REQ_FRIEND)) {
2285 logger("New friend request");
2286 Contact::addRelationship($importer, $contact, $item, $nickname, true);
2289 if (activity_match($item["verb"], ACTIVITY_UNFRIEND)) {
2290 logger("Lost sharer");
2291 Contact::removeSharer($importer, $contact, $item);
2295 if (($item["verb"] == ACTIVITY_LIKE)
2296 || ($item["verb"] == ACTIVITY_DISLIKE)
2297 || ($item["verb"] == ACTIVITY_ATTEND)
2298 || ($item["verb"] == ACTIVITY_ATTENDNO)
2299 || ($item["verb"] == ACTIVITY_ATTENDMAYBE)
2302 $item["gravity"] = GRAVITY_ACTIVITY;
2303 // only one like or dislike per person
2304 // splitted into two queries for performance issues
2305 $condition = ['uid' => $item["uid"], 'author-id' => $item["author-id"], 'gravity' => GRAVITY_ACTIVITY,
2306 'verb' => $item["verb"], 'parent-uri' => $item["parent-uri"]];
2307 if (Item::exists($condition)) {
2311 $condition = ['uid' => $item["uid"], 'author-id' => $item["author-id"], 'gravity' => GRAVITY_ACTIVITY,
2312 'verb' => $item["verb"], 'thr-parent' => $item["parent-uri"]];
2313 if (Item::exists($condition)) {
2320 if (($item["verb"] == ACTIVITY_TAG) && ($item["object-type"] == ACTIVITY_OBJ_TAGTERM)) {
2321 $xo = XML::parseString($item["object"], false);
2322 $xt = XML::parseString($item["target"], false);
2324 if ($xt->type == ACTIVITY_OBJ_NOTE) {
2325 $item_tag = Item::selectFirst(['id', 'tag'], ['uri' => $xt->id, 'uid' => $importer["importer_uid"]]);
2327 if (!DBA::isResult($item_tag)) {
2328 logger("Query failed to execute, no result returned in " . __FUNCTION__);
2332 // extract tag, if not duplicate, add to parent item
2334 if (!stristr($item_tag["tag"], trim($xo->content))) {
2335 $tag = $item_tag["tag"] . (strlen($item_tag["tag"]) ? ',' : '') . '#[url=' . $xo->id . ']'. $xo->content . '[/url]';
2336 Item::update(['tag' => $tag], ['id' => $item_tag["id"]]);
2346 * @brief Processes the link elements
2348 * @param object $links link elements
2349 * @param array $item the item record
2351 * @todo set proper type-hints
2353 private static function parseLinks($links, &$item)
2360 foreach ($links as $link) {
2361 foreach ($link->attributes as $attributes) {
2362 switch ($attributes->name) {
2363 case "href" : $href = $attributes->textContent; break;
2364 case "rel" : $rel = $attributes->textContent; break;
2365 case "type" : $type = $attributes->textContent; break;
2366 case "length": $length = $attributes->textContent; break;
2367 case "title" : $title = $attributes->textContent; break;
2370 if (($rel != "") && ($href != "")) {
2373 $item["plink"] = $href;
2377 if (strlen($item["attach"])) {
2378 $item["attach"] .= ",";
2381 $item["attach"] .= '[attach]href="' . $href . '" length="' . $length . '" type="' . $type . '" title="' . $title . '"[/attach]';
2389 * @brief Processes the entry elements which contain the items and comments
2391 * @param array $header Array of the header elements that always stay the same
2392 * @param object $xpath XPath object
2393 * @param object $entry entry elements
2394 * @param array $importer Record of the importer user mixed with contact of the content
2395 * @param object $xml xml
2397 * @todo Add type-hints
2399 private static function processEntry($header, $xpath, $entry, $importer, $xml)
2401 logger("Processing entries");
2405 $item["protocol"] = Conversation::PARCEL_DFRN;
2407 $item["source"] = $xml;
2410 $item["uri"] = XML::getFirstNodeValue($xpath, "atom:id/text()", $entry);
2412 $item["edited"] = XML::getFirstNodeValue($xpath, "atom:updated/text()", $entry);
2414 $current = Item::selectFirst(['id', 'uid', 'edited', 'body'],
2415 ['uri' => $item["uri"], 'uid' => $importer["importer_uid"]]
2417 // Is there an existing item?
2418 if (DBA::isResult($current) && !self::isEditedTimestampNewer($current, $item)) {
2419 logger("Item ".$item["uri"]." (".$item['edited'].") already existed.", LOGGER_DEBUG);
2424 $owner = self::fetchauthor($xpath, $entry, $importer, "dfrn:owner", true);
2426 $owner_unknown = (isset($owner["contact-unknown"]) && $owner["contact-unknown"]);
2428 $item["owner-name"] = $owner["name"];
2429 $item["owner-link"] = $owner["link"];
2430 $item["owner-avatar"] = $owner["avatar"];
2431 $item["owner-id"] = Contact::getIdForURL($owner["link"], 0);
2434 $author = self::fetchauthor($xpath, $entry, $importer, "atom:author", true);
2436 $item["author-name"] = $author["name"];
2437 $item["author-link"] = $author["link"];
2438 $item["author-avatar"] = $author["avatar"];
2439 $item["author-id"] = Contact::getIdForURL($author["link"], 0);
2441 $item["title"] = XML::getFirstNodeValue($xpath, "atom:title/text()", $entry);
2443 $item["created"] = XML::getFirstNodeValue($xpath, "atom:published/text()", $entry);
2445 $item["body"] = XML::getFirstNodeValue($xpath, "dfrn:env/text()", $entry);
2446 $item["body"] = str_replace([' ',"\t","\r","\n"], ['','','',''], $item["body"]);
2447 // make sure nobody is trying to sneak some html tags by us
2448 $item["body"] = notags(base64url_decode($item["body"]));
2450 $item["body"] = BBCode::limitBodySize($item["body"]);
2452 /// @todo Do we really need this check for HTML elements? (It was copied from the old function)
2453 if ((strpos($item['body'], '<') !== false) && (strpos($item['body'], '>') !== false)) {
2454 $base_url = get_app()->get_baseurl();
2455 $item['body'] = reltoabs($item['body'], $base_url);
2457 $item['body'] = html2bb_video($item['body']);
2459 $item['body'] = OEmbed::HTML2BBCode($item['body']);
2461 $config = HTMLPurifier_Config::createDefault();
2462 $config->set('Cache.DefinitionImpl', null);
2464 // we shouldn't need a whitelist, because the bbcode converter
2465 // will strip out any unsupported tags.
2467 $purifier = new HTMLPurifier($config);
2468 $item['body'] = $purifier->purify($item['body']);
2470 $item['body'] = @HTML::toBBCode($item['body']);
2473 /// @todo We should check for a repeated post and if we know the repeated author.
2475 // We don't need the content element since "dfrn:env" is always present
2476 //$item["body"] = $xpath->query("atom:content/text()", $entry)->item(0)->nodeValue;
2478 $item["location"] = XML::getFirstNodeValue($xpath, "dfrn:location/text()", $entry);
2480 $item["coord"] = XML::getFirstNodeValue($xpath, "georss:point", $entry);
2482 $item["private"] = XML::getFirstNodeValue($xpath, "dfrn:private/text()", $entry);
2484 $item["extid"] = XML::getFirstNodeValue($xpath, "dfrn:extid/text()", $entry);
2486 if (XML::getFirstNodeValue($xpath, "dfrn:bookmark/text()", $entry) == "true") {
2487 $item["post-type"] = Item::PT_PAGE;
2490 $notice_info = $xpath->query("statusnet:notice_info", $entry);
2491 if ($notice_info && ($notice_info->length > 0)) {
2492 foreach ($notice_info->item(0)->attributes as $attributes) {
2493 if ($attributes->name == "source") {
2494 $item["app"] = strip_tags($attributes->textContent);
2499 $item["guid"] = XML::getFirstNodeValue($xpath, "dfrn:diaspora_guid/text()", $entry);
2501 // We store the data from "dfrn:diaspora_signature" in a different table, this is done in "Item::insert"
2502 $dsprsig = unxmlify(XML::getFirstNodeValue($xpath, "dfrn:diaspora_signature/text()", $entry));
2503 if ($dsprsig != "") {
2504 $item["dsprsig"] = $dsprsig;
2507 $item["verb"] = XML::getFirstNodeValue($xpath, "activity:verb/text()", $entry);
2509 if (XML::getFirstNodeValue($xpath, "activity:object-type/text()", $entry) != "") {
2510 $item["object-type"] = XML::getFirstNodeValue($xpath, "activity:object-type/text()", $entry);
2513 $object = $xpath->query("activity:object", $entry)->item(0);
2514 $item["object"] = self::transformActivity($xpath, $object, "object");
2516 if (trim($item["object"]) != "") {
2517 $r = XML::parseString($item["object"], false);
2518 if (isset($r->type)) {
2519 $item["object-type"] = $r->type;
2523 $target = $xpath->query("activity:target", $entry)->item(0);
2524 $item["target"] = self::transformActivity($xpath, $target, "target");
2526 $categories = $xpath->query("atom:category", $entry);
2528 foreach ($categories as $category) {
2531 foreach ($category->attributes as $attributes) {
2532 if ($attributes->name == "term") {
2533 $term = $attributes->textContent;
2536 if ($attributes->name == "scheme") {
2537 $scheme = $attributes->textContent;
2541 if (($term != "") && ($scheme != "")) {
2542 $parts = explode(":", $scheme);
2543 if ((count($parts) >= 4) && (array_shift($parts) == "X-DFRN")) {
2544 $termhash = array_shift($parts);
2545 $termurl = implode(":", $parts);
2547 if (!empty($item["tag"])) {
2548 $item["tag"] .= ",";
2553 $item["tag"] .= $termhash . "[url=" . $termurl . "]" . $term . "[/url]";
2561 $links = $xpath->query("atom:link", $entry);
2563 self::parseLinks($links, $item);
2566 $item['conversation-uri'] = XML::getFirstNodeValue($xpath, 'ostatus:conversation/text()', $entry);
2568 $conv = $xpath->query('ostatus:conversation', $entry);
2569 if (is_object($conv->item(0))) {
2570 foreach ($conv->item(0)->attributes as $attributes) {
2571 if ($attributes->name == "ref") {
2572 $item['conversation-uri'] = $attributes->textContent;
2574 if ($attributes->name == "href") {
2575 $item['conversation-href'] = $attributes->textContent;
2580 // Is it a reply or a top level posting?
2581 $item["parent-uri"] = $item["uri"];
2583 $inreplyto = $xpath->query("thr:in-reply-to", $entry);
2584 if (is_object($inreplyto->item(0))) {
2585 foreach ($inreplyto->item(0)->attributes as $attributes) {
2586 if ($attributes->name == "ref") {
2587 $item["parent-uri"] = $attributes->textContent;
2592 // Get the type of the item (Top level post, reply or remote reply)
2593 $entrytype = self::getEntryType($importer, $item);
2595 // Now assign the rest of the values that depend on the type of the message
2596 if (in_array($entrytype, [DFRN::REPLY, DFRN::REPLY_RC])) {
2597 if (!isset($item["object-type"])) {
2598 $item["object-type"] = ACTIVITY_OBJ_COMMENT;
2601 if ($item["contact-id"] != $owner["contact-id"]) {
2602 $item["contact-id"] = $owner["contact-id"];
2605 if (($item["network"] != $owner["network"]) && ($owner["network"] != "")) {
2606 $item["network"] = $owner["network"];
2609 if ($item["contact-id"] != $author["contact-id"]) {
2610 $item["contact-id"] = $author["contact-id"];
2613 if (($item["network"] != $author["network"]) && ($author["network"] != "")) {
2614 $item["network"] = $author["network"];
2618 if ($entrytype == DFRN::REPLY_RC) {
2620 } elseif ($entrytype == DFRN::TOP_LEVEL) {
2621 if (!isset($item["object-type"])) {
2622 $item["object-type"] = ACTIVITY_OBJ_NOTE;
2626 if (($item["object-type"] == ACTIVITY_OBJ_EVENT) && !$owner_unknown) {
2627 logger("Item ".$item["uri"]." seems to contain an event.", LOGGER_DEBUG);
2628 $ev = Event::fromBBCode($item["body"]);
2629 if ((x($ev, "desc") || x($ev, "summary")) && x($ev, "start")) {
2630 logger("Event in item ".$item["uri"]." was found.", LOGGER_DEBUG);
2631 $ev["cid"] = $importer["id"];
2632 $ev["uid"] = $importer["importer_uid"];
2633 $ev["uri"] = $item["uri"];
2634 $ev["edited"] = $item["edited"];
2635 $ev["private"] = $item["private"];
2636 $ev["guid"] = $item["guid"];
2637 $ev["plink"] = $item["plink"];
2640 "SELECT `id` FROM `event` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2641 DBA::escape($item["uri"]),
2642 intval($importer["importer_uid"])
2644 if (DBA::isResult($r)) {
2645 $ev["id"] = $r[0]["id"];
2648 $event_id = Event::store($ev);
2649 logger("Event ".$event_id." was stored", LOGGER_DEBUG);
2655 if (!self::processVerbs($entrytype, $importer, $item, $is_like)) {
2656 logger("Exiting because 'processVerbs' told us so", LOGGER_DEBUG);
2660 // This check is done here to be able to receive connection requests in "processVerbs"
2661 if (($entrytype == DFRN::TOP_LEVEL) && $owner_unknown) {
2662 logger("Item won't be stored because user " . $importer["importer_uid"] . " doesn't follow " . $item["owner-link"] . ".", LOGGER_DEBUG);
2667 // Update content if 'updated' changes
2668 if (DBA::isResult($current)) {
2669 if (self::updateContent($current, $item, $importer, $entrytype)) {
2670 logger("Item ".$item["uri"]." was updated.", LOGGER_DEBUG);
2672 logger("Item " . $item["uri"] . " already existed.", LOGGER_DEBUG);
2677 if (in_array($entrytype, [DFRN::REPLY, DFRN::REPLY_RC])) {
2678 $posted_id = Item::insert($item);
2682 logger("Reply from contact ".$item["contact-id"]." was stored with id ".$posted_id, LOGGER_DEBUG);
2684 if ($item['uid'] == 0) {
2685 Item::distribute($posted_id);
2690 } else { // $entrytype == DFRN::TOP_LEVEL
2691 if (($importer["uid"] == 0) && ($importer["importer_uid"] != 0)) {
2692 logger("Contact ".$importer["id"]." isn't known to user ".$importer["importer_uid"].". The post will be ignored.", LOGGER_DEBUG);
2695 if (!link_compare($item["owner-link"], $importer["url"])) {
2697 * The item owner info is not our contact. It's OK and is to be expected if this is a tgroup delivery,
2698 * but otherwise there's a possible data mixup on the sender's system.
2699 * the tgroup delivery code called from Item::insert will correct it if it's a forum,
2700 * but we're going to unconditionally correct it here so that the post will always be owned by our contact.
2702 logger('Correcting item owner.', LOGGER_DEBUG);
2703 $item["owner-link"] = $importer["url"];
2704 $item["owner-id"] = Contact::getIdForURL($importer["url"], 0);
2707 if (($importer["rel"] == Contact::FOLLOWER) && (!self::tgroupCheck($importer["importer_uid"], $item))) {
2708 logger("Contact ".$importer["id"]." is only follower and tgroup check was negative.", LOGGER_DEBUG);
2712 // This is my contact on another system, but it's really me.
2713 // Turn this into a wall post.
2714 $notify = Item::isRemoteSelf($importer, $item);
2716 $posted_id = Item::insert($item, false, $notify);
2719 $posted_id = $notify;
2722 logger("Item was stored with id ".$posted_id, LOGGER_DEBUG);
2724 if ($item['uid'] == 0) {
2725 Item::distribute($posted_id);
2728 if (stristr($item["verb"], ACTIVITY_POKE)) {
2729 self::doPoke($item, $importer, $posted_id);
2735 * @brief Deletes items
2737 * @param object $xpath XPath object
2738 * @param object $deletion deletion elements
2739 * @param array $importer Record of the importer user mixed with contact of the content
2741 * @todo set proper type-hints
2743 private static function processDeletion($xpath, $deletion, $importer)
2745 logger("Processing deletions");
2748 foreach ($deletion->attributes as $attributes) {
2749 if ($attributes->name == "ref") {
2750 $uri = $attributes->textContent;
2754 if (!$uri || !$importer["id"]) {
2758 $condition = ['uri' => $uri, 'uid' => $importer["importer_uid"]];
2759 $item = Item::selectFirst(['id', 'parent', 'contact-id', 'file', 'deleted'], $condition);
2760 if (!DBA::isResult($item)) {
2761 logger("Item with uri " . $uri . " for user " . $importer["importer_uid"] . " wasn't found.", LOGGER_DEBUG);
2765 if (strstr($item['file'], '[')) {
2766 logger("Item with uri " . $uri . " for user " . $importer["importer_uid"] . " is filed. So it won't be deleted.", LOGGER_DEBUG);
2770 // When it is a starting post it has to belong to the person that wants to delete it
2771 if (($item['id'] == $item['parent']) && ($item['contact-id'] != $importer["id"])) {
2772 logger("Item with uri " . $uri . " don't belong to contact " . $importer["id"] . " - ignoring deletion.", LOGGER_DEBUG);
2776 // Comments can be deleted by the thread owner or comment owner
2777 if (($item['id'] != $item['parent']) && ($item['contact-id'] != $importer["id"])) {
2778 $condition = ['id' => $item['parent'], 'contact-id' => $importer["id"]];
2779 if (!Item::exists($condition)) {
2780 logger("Item with uri " . $uri . " wasn't found or mustn't be deleted by contact " . $importer["id"] . " - ignoring deletion.", LOGGER_DEBUG);
2785 if ($item["deleted"]) {
2789 logger('deleting item '.$item['id'].' uri='.$uri, LOGGER_DEBUG);
2791 Item::delete(['id' => $item['id']]);
2795 * @brief Imports a DFRN message
2797 * @param string $xml The DFRN message
2798 * @param array $importer Record of the importer user mixed with contact of the content
2799 * @param bool $sort_by_date Is used when feeds are polled
2800 * @return integer Import status
2801 * @todo set proper type-hints
2803 public static function import($xml, $importer, $sort_by_date = false)
2809 $doc = new DOMDocument();
2810 @$doc->loadXML($xml);
2812 $xpath = new DOMXPath($doc);
2813 $xpath->registerNamespace("atom", NAMESPACE_ATOM1);
2814 $xpath->registerNamespace("thr", NAMESPACE_THREAD);
2815 $xpath->registerNamespace("at", NAMESPACE_TOMB);
2816 $xpath->registerNamespace("media", NAMESPACE_MEDIA);
2817 $xpath->registerNamespace("dfrn", NAMESPACE_DFRN);
2818 $xpath->registerNamespace("activity", NAMESPACE_ACTIVITY);
2819 $xpath->registerNamespace("georss", NAMESPACE_GEORSS);
2820 $xpath->registerNamespace("poco", NAMESPACE_POCO);
2821 $xpath->registerNamespace("ostatus", NAMESPACE_OSTATUS);
2822 $xpath->registerNamespace("statusnet", NAMESPACE_STATUSNET);
2825 $header["uid"] = $importer["importer_uid"];
2826 $header["network"] = Protocol::DFRN;
2827 $header["wall"] = 0;
2828 $header["origin"] = 0;
2829 $header["contact-id"] = $importer["id"];
2831 // Update the contact table if the data has changed
2833 // The "atom:author" is only present in feeds
2834 if ($xpath->query("/atom:feed/atom:author")->length > 0) {
2835 self::fetchauthor($xpath, $doc->firstChild, $importer, "atom:author", false, $xml);
2838 // Only the "dfrn:owner" in the head section contains all data
2839 if ($xpath->query("/atom:feed/dfrn:owner")->length > 0) {
2840 self::fetchauthor($xpath, $doc->firstChild, $importer, "dfrn:owner", false, $xml);
2843 logger("Import DFRN message for user " . $importer["importer_uid"] . " from contact " . $importer["id"], LOGGER_DEBUG);
2845 // is it a public forum? Private forums aren't exposed with this method
2846 $forum = intval(XML::getFirstNodeValue($xpath, "/atom:feed/dfrn:community/text()"));
2848 // The account type is new since 3.5.1
2849 if ($xpath->query("/atom:feed/dfrn:account_type")->length > 0) {
2850 $accounttype = intval(XML::getFirstNodeValue($xpath, "/atom:feed/dfrn:account_type/text()"));
2852 if ($accounttype != $importer["contact-type"]) {
2853 DBA::update('contact', ['contact-type' => $accounttype], ['id' => $importer["id"]]);
2855 // A forum contact can either have set "forum" or "prv" - but not both
2856 if (($accounttype == Contact::ACCOUNT_TYPE_COMMUNITY) && (($forum != $importer["forum"]) || ($forum == $importer["prv"]))) {
2857 $condition = ['(`forum` != ? OR `prv` != ?) AND `id` = ?', $forum, !$forum, $importer["id"]];
2858 DBA::update('contact', ['forum' => $forum, 'prv' => !$forum], $condition);
2860 } elseif ($forum != $importer["forum"]) { // Deprecated since 3.5.1
2861 $condition = ['`forum` != ? AND `id` = ?', $forum, $importer["id"]];
2862 DBA::update('contact', ['forum' => $forum], $condition);
2866 // We are processing relocations even if we are ignoring a contact
2867 $relocations = $xpath->query("/atom:feed/dfrn:relocate");
2868 foreach ($relocations as $relocation) {
2869 self::processRelocation($xpath, $relocation, $importer);
2872 if (($importer["uid"] != 0) && !$importer["readonly"]) {
2873 $mails = $xpath->query("/atom:feed/dfrn:mail");
2874 foreach ($mails as $mail) {
2875 self::processMail($xpath, $mail, $importer);
2878 $suggestions = $xpath->query("/atom:feed/dfrn:suggest");
2879 foreach ($suggestions as $suggestion) {
2880 self::processSuggestion($xpath, $suggestion, $importer);
2884 $deletions = $xpath->query("/atom:feed/at:deleted-entry");
2885 foreach ($deletions as $deletion) {
2886 self::processDeletion($xpath, $deletion, $importer);
2889 if (!$sort_by_date) {
2890 $entries = $xpath->query("/atom:feed/atom:entry");
2891 foreach ($entries as $entry) {
2892 self::processEntry($header, $xpath, $entry, $importer, $xml);
2896 $entries = $xpath->query("/atom:feed/atom:entry");
2897 foreach ($entries as $entry) {
2898 $created = XML::getFirstNodeValue($xpath, "atom:published/text()", $entry);
2899 $newentries[strtotime($created)] = $entry;
2902 // Now sort after the publishing date
2905 foreach ($newentries as $entry) {
2906 self::processEntry($header, $xpath, $entry, $importer, $xml);
2909 logger("Import done for user " . $importer["importer_uid"] . " from contact " . $importer["id"], LOGGER_DEBUG);
2915 * @param string $contact_nick contact nickname
2917 public static function autoRedir(App $a, $contact_nick)
2920 if (x($_REQUEST, 'redir') && intval($_REQUEST['redir'])) {
2924 if ((! $contact_nick) || ($contact_nick === $a->user['nickname'])) {
2929 // We need to find out if $contact_nick is a user on this hub, and if so, if I
2930 // am a contact of that user. However, that user may have other contacts with the
2931 // same nickname as me on other hubs or other networks. Exclude these by requiring
2932 // that the contact have a local URL. I will be the only person with my nickname at
2933 // this URL, so if a result is found, then I am a contact of the $contact_nick user.
2935 // We also have to make sure that I'm a legitimate contact--I'm not blocked or pending.
2937 $baseurl = System::baseUrl();
2938 $domain_st = strpos($baseurl, "://");
2939 if ($domain_st === false) {
2942 $baseurl = substr($baseurl, $domain_st + 3);
2943 $nurl = normalise_link($baseurl);
2945 /// @todo Why is there a query for "url" *and* "nurl"? Especially this normalising is strange.
2946 $r = q("SELECT `id` FROM `contact` WHERE `uid` = (SELECT `uid` FROM `user` WHERE `nickname` = '%s' LIMIT 1)
2947 AND `nick` = '%s' AND NOT `self` AND (`url` LIKE '%%%s%%' OR `nurl` LIKE '%%%s%%') AND NOT `blocked` AND NOT `pending` LIMIT 1",
2948 DBA::escape($contact_nick),
2949 DBA::escape($a->user['nickname']),
2950 DBA::escape($baseurl),
2953 if ((! DBA::isResult($r)) || $r[0]['id'] == remote_user()) {
2957 $r = q("SELECT * FROM contact WHERE nick = '%s'
2958 AND network = '%s' AND uid = %d AND url LIKE '%%%s%%' LIMIT 1",
2959 DBA::escape($contact_nick),
2960 DBA::escape(Protocol::DFRN),
2961 intval(local_user()),
2962 DBA::escape($baseurl)
2964 if (! DBA::isResult($r)) {
2970 $dfrn_id = (($r[0]['issued-id']) ? $r[0]['issued-id'] : $r[0]['dfrn-id']);
2972 if ($r[0]['duplex'] && $r[0]['issued-id']) {
2973 $orig_id = $r[0]['issued-id'];
2974 $dfrn_id = '1:' . $orig_id;
2976 if ($r[0]['duplex'] && $r[0]['dfrn-id']) {
2977 $orig_id = $r[0]['dfrn-id'];
2978 $dfrn_id = '0:' . $orig_id;
2981 // ensure that we've got a valid ID. There may be some edge cases with forums and non-duplex mode
2982 // that may have triggered some of the "went to {profile/intro} and got an RSS feed" issues
2984 if (strlen($dfrn_id) < 3) {
2988 $sec = random_string();
2990 DBA::insert('profile_check', ['uid' => local_user(), 'cid' => $cid, 'dfrn_id' => $dfrn_id, 'sec' => $sec, 'expire' => time() + 45]);
2992 $url = curPageURL();
2994 logger('auto_redir: ' . $r[0]['name'] . ' ' . $sec, LOGGER_DEBUG);
2995 $dest = (($url) ? '&destination_url=' . $url : '');
2996 goaway($r[0]['poll'] . '?dfrn_id=' . $dfrn_id
2997 . '&dfrn_version=' . DFRN_PROTOCOL_VERSION . '&type=profile&sec=' . $sec . $dest);
3004 * @brief Returns the activity verb
3006 * @param array $item Item array
3008 * @return string activity verb
3010 private static function constructVerb(array $item)
3012 if ($item['verb']) {
3013 return $item['verb'];
3015 return ACTIVITY_POST;
3018 private static function tgroupCheck($uid, $item)
3022 // check that the message originated elsewhere and is a top-level post
3024 if ($item['wall'] || $item['origin'] || ($item['uri'] != $item['parent-uri'])) {
3028 $u = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1",
3031 if (!DBA::isResult($u)) {
3035 $community_page = ($u[0]['page-flags'] == Contact::PAGE_COMMUNITY);
3036 $prvgroup = ($u[0]['page-flags'] == Contact::PAGE_PRVGROUP);
3038 $link = normalise_link(System::baseUrl() . '/profile/' . $u[0]['nickname']);
3041 * Diaspora uses their own hardwired link URL in @-tags
3042 * instead of the one we supply with webfinger
3044 $dlink = normalise_link(System::baseUrl() . '/u/' . $u[0]['nickname']);
3046 $cnt = preg_match_all('/[\@\!]\[url\=(.*?)\](.*?)\[\/url\]/ism', $item['body'], $matches, PREG_SET_ORDER);
3048 foreach ($matches as $mtch) {
3049 if (link_compare($link, $mtch[1]) || link_compare($dlink, $mtch[1])) {
3051 logger('mention found: ' . $mtch[2]);
3060 return $community_page || $prvgroup;
3064 * This function returns true if $update has an edited timestamp newer
3065 * than $existing, i.e. $update contains new data which should override
3066 * what's already there. If there is no timestamp yet, the update is
3067 * assumed to be newer. If the update has no timestamp, the existing
3068 * item is assumed to be up-to-date. If the timestamps are equal it
3069 * assumes the update has been seen before and should be ignored.
3072 private static function isEditedTimestampNewer($existing, $update)
3074 if (!x($existing, 'edited') || !$existing['edited']) {
3077 if (!x($update, 'edited') || !$update['edited']) {
3081 $existing_edited = DateTimeFormat::utc($existing['edited']);
3082 $update_edited = DateTimeFormat::utc($update['edited']);
3084 return (strcmp($existing_edited, $update_edited) < 0);