3 * @copyright Copyright (C) 2010-2021, the Friendica project
5 * @license GNU AGPL version 3 or any later version
7 * This program is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU Affero General Public License as
9 * published by the Free Software Foundation, either version 3 of the
10 * License, or (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU Affero General Public License for more details.
17 * You should have received a copy of the GNU Affero General Public License
18 * along with this program. If not, see <https://www.gnu.org/licenses/>.
22 namespace Friendica\Protocol;
26 use Friendica\App\BaseURL;
27 use Friendica\Content\Text\BBCode;
28 use Friendica\Core\Hook;
29 use Friendica\Core\Logger;
30 use Friendica\Core\Protocol;
31 use Friendica\Database\DBA;
33 use Friendica\Model\Contact;
34 use Friendica\Model\Conversation;
35 use Friendica\Model\Event;
36 use Friendica\Model\FContact;
37 use Friendica\Model\GServer;
38 use Friendica\Model\Item;
39 use Friendica\Model\ItemURI;
40 use Friendica\Model\Mail;
41 use Friendica\Model\Notification;
42 use Friendica\Model\PermissionSet;
43 use Friendica\Model\Post;
44 use Friendica\Model\Post\Category;
45 use Friendica\Model\Profile;
46 use Friendica\Model\Tag;
47 use Friendica\Model\User;
48 use Friendica\Model\Verb;
49 use Friendica\Network\Probe;
50 use Friendica\Util\Crypto;
51 use Friendica\Util\DateTimeFormat;
52 use Friendica\Util\Images;
53 use Friendica\Util\Network;
54 use Friendica\Util\Proxy;
55 use Friendica\Util\Strings;
56 use Friendica\Util\XML;
59 * This class contain functions to create and send DFRN XML files
64 const TOP_LEVEL = 0; // Top level posting
65 const REPLY = 1; // Regular reply that is stored locally
66 const REPLY_RC = 2; // Reply that will be relayed
69 * Generates an array of contact and user for DFRN imports
71 * This array contains not only the receiver but also the sender of the message.
73 * @param integer $cid Contact id
74 * @param integer $uid User id
76 * @return array importer
79 public static function getImporter($cid, $uid = 0)
81 $condition = ['id' => $cid, 'blocked' => false, 'pending' => false];
82 $contact = DBA::selectFirst('contact', [], $condition);
83 if (!DBA::isResult($contact)) {
87 $contact['cpubkey'] = $contact['pubkey'];
88 $contact['cprvkey'] = $contact['prvkey'];
89 $contact['senderName'] = $contact['name'];
92 $condition = ['uid' => $uid, 'account_expired' => false, 'account_removed' => false];
93 $user = DBA::selectFirst('user', [], $condition);
94 if (!DBA::isResult($user)) {
98 $user['importer_uid'] = $user['uid'];
99 $user['uprvkey'] = $user['prvkey'];
101 $user = ['importer_uid' => 0, 'uprvkey' => '', 'timezone' => 'UTC',
102 'nickname' => '', 'sprvkey' => '', 'spubkey' => '',
103 'page-flags' => 0, 'account-type' => 0, 'prvnets' => 0];
106 return array_merge($contact, $user);
110 * Generates the atom entries for delivery.php
112 * This function is used whenever content is transmitted via DFRN.
114 * @param array $items Item elements
115 * @param array $owner Owner record
117 * @return string DFRN entries
118 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
119 * @throws \ImagickException
120 * @todo Find proper type-hints
122 public static function entries($items, $owner)
124 $doc = new DOMDocument('1.0', 'utf-8');
125 $doc->formatOutput = true;
127 $root = self::addHeader($doc, $owner, "dfrn:owner", "", false);
129 if (! count($items)) {
130 return trim($doc->saveXML());
133 foreach ($items as $item) {
134 // These values aren't sent when sending from the queue.
135 /// @todo Check if we can set these values from the queue or if they are needed at all.
136 $item["entry:comment-allow"] = ($item["entry:comment-allow"] ?? '') ?: true;
137 $item["entry:cid"] = $item["entry:cid"] ?? 0;
139 $entry = self::entry($doc, "text", $item, $owner, $item["entry:comment-allow"], $item["entry:cid"]);
141 $root->appendChild($entry);
145 return trim($doc->saveXML());
149 * Generate an atom feed for the given user
151 * This function is called when another server is pulling data from the user feed.
153 * @param string $dfrn_id DFRN ID from the requesting party
154 * @param string $owner_nick Owner nick name
155 * @param string $last_update Date of the last update
156 * @param int $direction Can be -1, 0 or 1.
157 * @param boolean $onlyheader Output only the header without content? (Default is "no")
159 * @return string DFRN feed entries
160 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
161 * @throws \ImagickException
163 public static function feed($dfrn_id, $owner_nick, $last_update, $direction = 0, $onlyheader = false)
167 $sitefeed = ((strlen($owner_nick)) ? false : true); // not yet implemented, need to rewrite huge chunks of following logic
168 $public_feed = (($dfrn_id) ? false : true);
169 $starred = false; // not yet implemented, possible security issues
172 if ($public_feed && $a->argc > 2) {
173 for ($x = 2; $x < $a->argc; $x++) {
174 if ($a->argv[$x] == 'converse') {
177 if ($a->argv[$x] == 'starred') {
180 if ($a->argv[$x] == 'category' && $a->argc > ($x + 1) && strlen($a->argv[$x+1])) {
181 $category = $a->argv[$x+1];
186 // default permissions - anonymous user
188 $sql_extra = sprintf(" AND `private` != %s ", Item::PRIVATE);
190 $owner = DBA::selectFirst('owner-view', [], ['nickname' => $owner_nick]);
191 if (!DBA::isResult($owner)) {
192 Logger::log(sprintf('No contact found for nickname=%d', $owner_nick), Logger::WARNING);
196 $owner_id = $owner['uid'];
199 switch ($direction) {
201 $sql_extra = sprintf(" AND `issued-id` = '%s' ", DBA::escape($dfrn_id));
204 $sql_extra = sprintf(" AND `issued-id` = '%s' AND `duplex` = 1 ", DBA::escape($dfrn_id));
207 $sql_extra = sprintf(" AND `dfrn-id` = '%s' AND `duplex` = 1 ", DBA::escape($dfrn_id));
214 $contact = DBA::selectFirst('contact', [], ["NOT `blocked` AND `contact`.`uid` = ?" . $sql_extra, $owner_id]);
215 if (!DBA::isResult($contact)) {
216 Logger::notice('No contact found', ['uid' => $owner_id]);
220 $set = PermissionSet::get($owner_id, $contact['id']);
223 $sql_extra = " AND `psid` IN (" . implode(',', $set) .")";
225 $sql_extra = sprintf(" AND `private` != %s", Item::PRIVATE);
229 if (!strlen($last_update)) {
230 $last_update = 'now -30 days';
233 if (isset($category)) {
234 $sql_extra .= sprintf(" AND `uri-id` IN (SELECT `uri-id` FROM `category-view` WHERE `name` = '%s' AND `type` = %d AND `uid` = %d)",
235 DBA::escape(Strings::protectSprintf($category)), intval(Category::CATEGORY), intval($owner_id));
238 if ($public_feed && ! $converse) {
239 $sql_extra .= " AND `self` ";
242 $check_date = DateTimeFormat::utc($last_update);
244 $condition = ["`uid` = ? AND `wall` AND `changed` > ? AND `vid` != ? AND `visible`" . $sql_extra,
245 $owner_id, $check_date, Verb::getID(Activity::ANNOUNCE)];
247 $params = ['sort' => ['parent' => $public_feed, 'received']];
248 $items = Post::selectToArray(Item::DELIVER_FIELDLIST, $condition, $params, ['limit' => 300]);
251 * Will check further below if this actually returned results.
252 * We will provide an empty feed if that is the case.
255 $doc = new DOMDocument('1.0', 'utf-8');
256 $doc->formatOutput = true;
258 $alternatelink = $owner['url'];
260 if (isset($category)) {
261 $alternatelink .= "/category/".$category;
265 $author = "dfrn:owner";
270 $root = self::addHeader($doc, $owner, $author, $alternatelink, true);
272 /// @TODO This hook can't work anymore
273 // \Friendica\Core\Hook::callAll('atom_feed', $atom);
275 if (!DBA::isResult($items) || $onlyheader) {
276 $atom = trim($doc->saveXML());
278 Hook::callAll('atom_feed_end', $atom);
283 foreach ($items as $item) {
284 // prevent private email from leaking.
285 if ($item['network'] == Protocol::MAIL) {
289 // public feeds get html, our own nodes use bbcode
293 // catch any email that's in a public conversation and make sure it doesn't leak
294 if ($item['private'] == Item::PRIVATE) {
301 $entry = self::entry($doc, $type, $item, $owner, true);
303 $root->appendChild($entry);
307 $atom = trim($doc->saveXML());
309 Hook::callAll('atom_feed_end', $atom);
315 * Generate an atom entry for a given uri id and user
317 * @param int $uri_id The uri id
318 * @param int $uid The user id
319 * @param boolean $conversation Show the conversation. If false show the single post.
321 * @return string DFRN feed entry
322 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
323 * @throws \ImagickException
325 public static function itemFeed(int $uri_id, int $uid, bool $conversation = false)
328 $condition = ['parent-uri-id' => $uri_id];
330 $condition = ['uri-id' => $uri_id];
333 $condition['uid'] = $uid;
335 $items = Post::selectToArray(Item::DELIVER_FIELDLIST, $condition);
336 if (!DBA::isResult($items)) {
342 if ($item['uid'] != 0) {
343 $owner = User::getOwnerDataById($item['uid']);
348 $owner = ['uid' => 0, 'nick' => 'feed-item'];
351 $doc = new DOMDocument('1.0', 'utf-8');
352 $doc->formatOutput = true;
356 $root = $doc->createElementNS(ActivityNamespace::ATOM1, 'feed');
357 $doc->appendChild($root);
359 $root->setAttribute("xmlns:thr", ActivityNamespace::THREAD);
360 $root->setAttribute("xmlns:at", ActivityNamespace::TOMB);
361 $root->setAttribute("xmlns:media", ActivityNamespace::MEDIA);
362 $root->setAttribute("xmlns:dfrn", ActivityNamespace::DFRN);
363 $root->setAttribute("xmlns:activity", ActivityNamespace::ACTIVITY);
364 $root->setAttribute("xmlns:georss", ActivityNamespace::GEORSS);
365 $root->setAttribute("xmlns:poco", ActivityNamespace::POCO);
366 $root->setAttribute("xmlns:ostatus", ActivityNamespace::OSTATUS);
367 $root->setAttribute("xmlns:statusnet", ActivityNamespace::STATUSNET);
369 //$root = self::addHeader($doc, $owner, "dfrn:owner", "", false);
371 foreach ($items as $item) {
372 $entry = self::entry($doc, $type, $item, $owner, true, 0);
374 $root->appendChild($entry);
378 self::entry($doc, $type, $item, $owner, true, 0, true);
381 $atom = trim($doc->saveXML());
386 * Create XML text for DFRN mails
388 * @param array $mail Mail record
389 * @param array $owner Owner record
391 * @return string DFRN mail
392 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
393 * @todo Find proper type-hints
395 public static function mail(array $mail, array $owner)
397 $doc = new DOMDocument('1.0', 'utf-8');
398 $doc->formatOutput = true;
400 $root = self::addHeader($doc, $owner, "dfrn:owner", "", false);
402 $mailElement = $doc->createElement("dfrn:mail");
403 $senderElement = $doc->createElement("dfrn:sender");
405 XML::addElement($doc, $senderElement, "dfrn:name", $owner['name']);
406 XML::addElement($doc, $senderElement, "dfrn:uri", $owner['url']);
407 XML::addElement($doc, $senderElement, "dfrn:avatar", $owner['thumb']);
409 $mailElement->appendChild($senderElement);
411 XML::addElement($doc, $mailElement, "dfrn:id", $mail['uri']);
412 XML::addElement($doc, $mailElement, "dfrn:in-reply-to", $mail['parent-uri']);
413 XML::addElement($doc, $mailElement, "dfrn:sentdate", DateTimeFormat::utc($mail['created'] . '+00:00', DateTimeFormat::ATOM));
414 XML::addElement($doc, $mailElement, "dfrn:subject", $mail['title']);
415 XML::addElement($doc, $mailElement, "dfrn:content", $mail['body']);
417 $root->appendChild($mailElement);
419 return trim($doc->saveXML());
423 * Create XML text for DFRN friend suggestions
425 * @param array $item suggestion elements
426 * @param array $owner Owner record
428 * @return string DFRN suggestions
429 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
430 * @todo Find proper type-hints
432 public static function fsuggest($item, $owner)
434 $doc = new DOMDocument('1.0', 'utf-8');
435 $doc->formatOutput = true;
437 $root = self::addHeader($doc, $owner, "dfrn:owner", "", false);
439 $suggest = $doc->createElement("dfrn:suggest");
441 XML::addElement($doc, $suggest, "dfrn:url", $item['url']);
442 XML::addElement($doc, $suggest, "dfrn:name", $item['name']);
443 XML::addElement($doc, $suggest, "dfrn:photo", $item['photo']);
444 XML::addElement($doc, $suggest, "dfrn:request", $item['request']);
445 XML::addElement($doc, $suggest, "dfrn:note", $item['note']);
447 $root->appendChild($suggest);
449 return trim($doc->saveXML());
453 * Create XML text for DFRN relocations
455 * @param array $owner Owner record
456 * @param int $uid User ID
458 * @return string DFRN relocations
459 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
460 * @todo Find proper type-hints
462 public static function relocate($owner, $uid)
465 /* get site pubkey. this could be a new installation with no site keys*/
466 $pubkey = DI::config()->get('system', 'site_pubkey');
468 $res = Crypto::newKeypair(1024);
469 DI::config()->set('system', 'site_prvkey', $res['prvkey']);
470 DI::config()->set('system', 'site_pubkey', $res['pubkey']);
474 "SELECT `resource-id` , `scale`, type FROM `photo`
475 WHERE `profile` = 1 AND `uid` = %d ORDER BY scale;",
479 $ext = Images::supportedTypes();
481 foreach ($rp as $p) {
482 $photos[$p['scale']] = DI::baseUrl().'/photo/'.$p['resource-id'].'-'.$p['scale'].'.'.$ext[$p['type']];
486 $doc = new DOMDocument('1.0', 'utf-8');
487 $doc->formatOutput = true;
489 $root = self::addHeader($doc, $owner, "dfrn:owner", "", false);
491 $relocate = $doc->createElement("dfrn:relocate");
493 XML::addElement($doc, $relocate, "dfrn:url", $owner['url']);
494 XML::addElement($doc, $relocate, "dfrn:name", $owner['name']);
495 XML::addElement($doc, $relocate, "dfrn:addr", $owner['addr']);
496 XML::addElement($doc, $relocate, "dfrn:avatar", $owner['avatar']);
497 XML::addElement($doc, $relocate, "dfrn:photo", $photos[4]);
498 XML::addElement($doc, $relocate, "dfrn:thumb", $photos[5]);
499 XML::addElement($doc, $relocate, "dfrn:micro", $photos[6]);
500 XML::addElement($doc, $relocate, "dfrn:request", $owner['request']);
501 XML::addElement($doc, $relocate, "dfrn:confirm", $owner['confirm']);
502 XML::addElement($doc, $relocate, "dfrn:notify", $owner['notify']);
503 XML::addElement($doc, $relocate, "dfrn:poll", $owner['poll']);
504 XML::addElement($doc, $relocate, "dfrn:sitepubkey", DI::config()->get('system', 'site_pubkey'));
506 $root->appendChild($relocate);
508 return trim($doc->saveXML());
512 * Adds the header elements for the DFRN protocol
514 * @param DOMDocument $doc XML document
515 * @param array $owner Owner record
516 * @param string $authorelement Element name for the author
517 * @param string $alternatelink link to profile or category
518 * @param bool $public Is it a header for public posts?
520 * @return object XML root object
521 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
522 * @todo Find proper type-hints
524 private static function addHeader(DOMDocument $doc, $owner, $authorelement, $alternatelink = "", $public = false)
527 if ($alternatelink == "") {
528 $alternatelink = $owner['url'];
531 $root = $doc->createElementNS(ActivityNamespace::ATOM1, 'feed');
532 $doc->appendChild($root);
534 $root->setAttribute("xmlns:thr", ActivityNamespace::THREAD);
535 $root->setAttribute("xmlns:at", ActivityNamespace::TOMB);
536 $root->setAttribute("xmlns:media", ActivityNamespace::MEDIA);
537 $root->setAttribute("xmlns:dfrn", ActivityNamespace::DFRN);
538 $root->setAttribute("xmlns:activity", ActivityNamespace::ACTIVITY);
539 $root->setAttribute("xmlns:georss", ActivityNamespace::GEORSS);
540 $root->setAttribute("xmlns:poco", ActivityNamespace::POCO);
541 $root->setAttribute("xmlns:ostatus", ActivityNamespace::OSTATUS);
542 $root->setAttribute("xmlns:statusnet", ActivityNamespace::STATUSNET);
544 XML::addElement($doc, $root, "id", DI::baseUrl()."/profile/".$owner["nick"]);
545 XML::addElement($doc, $root, "title", $owner["name"]);
547 $attributes = ["uri" => "https://friendi.ca", "version" => FRIENDICA_VERSION."-".DB_UPDATE_VERSION];
548 XML::addElement($doc, $root, "generator", FRIENDICA_PLATFORM, $attributes);
550 $attributes = ["rel" => "license", "href" => "http://creativecommons.org/licenses/by/3.0/"];
551 XML::addElement($doc, $root, "link", "", $attributes);
553 $attributes = ["rel" => "alternate", "type" => "text/html", "href" => $alternatelink];
554 XML::addElement($doc, $root, "link", "", $attributes);
558 // DFRN itself doesn't uses this. But maybe someone else wants to subscribe to the public feed.
559 OStatus::hublinks($doc, $root, $owner["nick"]);
561 $attributes = ["rel" => "salmon", "href" => DI::baseUrl()."/salmon/".$owner["nick"]];
562 XML::addElement($doc, $root, "link", "", $attributes);
564 $attributes = ["rel" => "http://salmon-protocol.org/ns/salmon-replies", "href" => DI::baseUrl()."/salmon/".$owner["nick"]];
565 XML::addElement($doc, $root, "link", "", $attributes);
567 $attributes = ["rel" => "http://salmon-protocol.org/ns/salmon-mention", "href" => DI::baseUrl()."/salmon/".$owner["nick"]];
568 XML::addElement($doc, $root, "link", "", $attributes);
571 // For backward compatibility we keep this element
572 if ($owner['page-flags'] == User::PAGE_FLAGS_COMMUNITY) {
573 XML::addElement($doc, $root, "dfrn:community", 1);
576 // The former element is replaced by this one
577 XML::addElement($doc, $root, "dfrn:account_type", $owner["account-type"]);
579 /// @todo We need a way to transmit the different page flags like "User::PAGE_FLAGS_PRVGROUP"
581 XML::addElement($doc, $root, "updated", DateTimeFormat::utcNow(DateTimeFormat::ATOM));
583 $author = self::addAuthor($doc, $owner, $authorelement, $public);
584 $root->appendChild($author);
590 * Adds the author element in the header for the DFRN protocol
592 * @param DOMDocument $doc XML document
593 * @param array $owner Owner record
594 * @param string $authorelement Element name for the author
595 * @param boolean $public boolean
597 * @return \DOMElement XML author object
598 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
599 * @todo Find proper type-hints
601 private static function addAuthor(DOMDocument $doc, array $owner, $authorelement, $public)
603 // Should the profile be "unsearchable" in the net? Then add the "hide" element
604 $hide = DBA::exists('profile', ['uid' => $owner['uid'], 'net-publish' => false]);
606 $author = $doc->createElement($authorelement);
608 $namdate = DateTimeFormat::utc($owner['name-date'].'+00:00', DateTimeFormat::ATOM);
609 $picdate = DateTimeFormat::utc($owner['avatar-date'].'+00:00', DateTimeFormat::ATOM);
613 if (!$public || !$hide) {
614 $attributes = ["dfrn:updated" => $namdate];
617 XML::addElement($doc, $author, "name", $owner["name"], $attributes);
618 XML::addElement($doc, $author, "uri", DI::baseUrl().'/profile/'.$owner["nickname"], $attributes);
619 XML::addElement($doc, $author, "dfrn:handle", $owner["addr"], $attributes);
621 $attributes = ["rel" => "photo", "type" => "image/jpeg",
622 "media:width" => Proxy::PIXEL_SMALL, "media:height" => Proxy::PIXEL_SMALL,
623 "href" => Contact::getAvatarUrlForId($owner['id'], Proxy::SIZE_SMALL, $owner['updated'])];
625 if (!$public || !$hide) {
626 $attributes["dfrn:updated"] = $picdate;
629 XML::addElement($doc, $author, "link", "", $attributes);
631 $attributes["rel"] = "avatar";
632 XML::addElement($doc, $author, "link", "", $attributes);
635 XML::addElement($doc, $author, "dfrn:hide", "true");
638 // The following fields will only be generated if the data isn't meant for a public feed
643 $birthday = feed_birthday($owner['uid'], $owner['timezone']);
646 XML::addElement($doc, $author, "dfrn:birthday", $birthday);
649 // Only show contact details when we are allowed to
650 $profile = DBA::selectFirst('owner-view',
651 ['about', 'name', 'homepage', 'nickname', 'timezone', 'locality', 'region', 'country-name', 'pub_keywords', 'xmpp', 'dob'],
652 ['uid' => $owner['uid'], 'hidewall' => false]);
653 if (DBA::isResult($profile)) {
654 XML::addElement($doc, $author, "poco:displayName", $profile["name"]);
655 XML::addElement($doc, $author, "poco:updated", $namdate);
657 if (trim($profile["dob"]) > DBA::NULL_DATE) {
658 XML::addElement($doc, $author, "poco:birthday", "0000-".date("m-d", strtotime($profile["dob"])));
661 XML::addElement($doc, $author, "poco:note", $profile["about"]);
662 XML::addElement($doc, $author, "poco:preferredUsername", $profile["nickname"]);
664 $savetz = date_default_timezone_get();
665 date_default_timezone_set($profile["timezone"]);
666 XML::addElement($doc, $author, "poco:utcOffset", date("P"));
667 date_default_timezone_set($savetz);
669 if (trim($profile["homepage"]) != "") {
670 $urls = $doc->createElement("poco:urls");
671 XML::addElement($doc, $urls, "poco:type", "homepage");
672 XML::addElement($doc, $urls, "poco:value", $profile["homepage"]);
673 XML::addElement($doc, $urls, "poco:primary", "true");
674 $author->appendChild($urls);
677 if (trim($profile["pub_keywords"]) != "") {
678 $keywords = explode(",", $profile["pub_keywords"]);
680 foreach ($keywords as $keyword) {
681 XML::addElement($doc, $author, "poco:tags", trim($keyword));
685 if (trim($profile["xmpp"]) != "") {
686 $ims = $doc->createElement("poco:ims");
687 XML::addElement($doc, $ims, "poco:type", "xmpp");
688 XML::addElement($doc, $ims, "poco:value", $profile["xmpp"]);
689 XML::addElement($doc, $ims, "poco:primary", "true");
690 $author->appendChild($ims);
693 if (trim($profile["locality"].$profile["region"].$profile["country-name"]) != "") {
694 $element = $doc->createElement("poco:address");
696 XML::addElement($doc, $element, "poco:formatted", Profile::formatLocation($profile));
698 if (trim($profile["locality"]) != "") {
699 XML::addElement($doc, $element, "poco:locality", $profile["locality"]);
702 if (trim($profile["region"]) != "") {
703 XML::addElement($doc, $element, "poco:region", $profile["region"]);
706 if (trim($profile["country-name"]) != "") {
707 XML::addElement($doc, $element, "poco:country", $profile["country-name"]);
710 $author->appendChild($element);
718 * Adds the author elements in the "entry" elements of the DFRN protocol
720 * @param DOMDocument $doc XML document
721 * @param string $element Element name for the author
722 * @param string $contact_url Link of the contact
723 * @param array $item Item elements
725 * @return \DOMElement XML author object
726 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
727 * @todo Find proper type-hints
729 private static function addEntryAuthor(DOMDocument $doc, $element, $contact_url, $item)
731 $author = $doc->createElement($element);
733 $contact = Contact::getByURLForUser($contact_url, $item["uid"], false, ['url', 'name', 'addr', 'photo']);
734 if (!empty($contact)) {
735 XML::addElement($doc, $author, "name", $contact["name"]);
736 XML::addElement($doc, $author, "uri", $contact["url"]);
737 XML::addElement($doc, $author, "dfrn:handle", $contact["addr"]);
740 /// - Check real image type and image size
741 /// - Check which of these boths elements we should use
744 "type" => "image/jpeg",
746 "media:height" => 80,
747 "href" => $contact["photo"]];
748 XML::addElement($doc, $author, "link", "", $attributes);
752 "type" => "image/jpeg",
754 "media:height" => 80,
755 "href" => $contact["photo"]];
756 XML::addElement($doc, $author, "link", "", $attributes);
763 * Adds the activity elements
765 * @param DOMDocument $doc XML document
766 * @param string $element Element name for the activity
767 * @param string $activity activity value
769 * @return \DOMElement XML activity object
770 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
771 * @todo Find proper type-hints
773 private static function createActivity(DOMDocument $doc, $element, $activity)
776 $entry = $doc->createElement($element);
778 $r = XML::parseString($activity);
784 XML::addElement($doc, $entry, "activity:object-type", $r->type);
788 XML::addElement($doc, $entry, "id", $r->id);
792 XML::addElement($doc, $entry, "title", $r->title);
796 if (substr($r->link, 0, 1) == '<') {
797 if (strstr($r->link, '&') && (! strstr($r->link, '&'))) {
798 $r->link = str_replace('&', '&', $r->link);
801 $r->link = preg_replace('/\<link(.*?)\"\>/', '<link$1"/>', $r->link);
803 // XML does need a single element as root element so we add a dummy element here
804 $data = XML::parseString("<dummy>" . $r->link . "</dummy>");
805 if (is_object($data)) {
806 foreach ($data->link as $link) {
808 foreach ($link->attributes() as $parameter => $value) {
809 $attributes[$parameter] = $value;
811 XML::addElement($doc, $entry, "link", "", $attributes);
815 $attributes = ["rel" => "alternate", "type" => "text/html", "href" => $r->link];
816 XML::addElement($doc, $entry, "link", "", $attributes);
820 XML::addElement($doc, $entry, "content", BBCode::convert($r->content), ["type" => "html"]);
830 * Adds the elements for attachments
832 * @param object $doc XML document
833 * @param object $root XML root
834 * @param array $item Item element
836 * @return void XML attachment object
837 * @todo Find proper type-hints
839 private static function getAttachment($doc, $root, $item)
841 foreach (Post\Media::getByURIId($item['uri-id'], [Post\Media::DOCUMENT, Post\Media::TORRENT, Post\Media::UNKNOWN]) as $attachment) {
842 $attributes = ['rel' => 'enclosure',
843 'href' => $attachment['url'],
844 'type' => $attachment['mimetype']];
846 if (!empty($attachment['size'])) {
847 $attributes['length'] = intval($attachment['size']);
849 if (!empty($attachment['description'])) {
850 $attributes['title'] = $attachment['description'];
853 XML::addElement($doc, $root, 'link', '', $attributes);
858 * Adds the "entry" elements for the DFRN protocol
860 * @param DOMDocument $doc XML document
861 * @param string $type "text" or "html"
862 * @param array $item Item element
863 * @param array $owner Owner record
864 * @param bool $comment Trigger the sending of the "comment" element
865 * @param int $cid Contact ID of the recipient
866 * @param bool $single If set, the entry is created as an XML document with a single "entry" element
868 * @return null|\DOMElement XML entry object
869 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
870 * @throws \ImagickException
871 * @todo Find proper type-hints
873 private static function entry(DOMDocument $doc, $type, array $item, array $owner, $comment = false, $cid = 0, $single = false)
877 if (!$item['parent']) {
878 Logger::notice('Item without parent found.', ['type' => $type, 'item' => $item]);
882 if ($item['deleted']) {
883 $attributes = ["ref" => $item['uri'], "when" => DateTimeFormat::utc($item['edited'] . '+00:00', DateTimeFormat::ATOM)];
884 return XML::createElement($doc, "at:deleted-entry", "", $attributes);
888 $entry = $doc->createElement("entry");
890 $entry = $doc->createElementNS(ActivityNamespace::ATOM1, 'entry');
891 $doc->appendChild($entry);
893 $entry->setAttribute("xmlns:thr", ActivityNamespace::THREAD);
894 $entry->setAttribute("xmlns:at", ActivityNamespace::TOMB);
895 $entry->setAttribute("xmlns:media", ActivityNamespace::MEDIA);
896 $entry->setAttribute("xmlns:dfrn", ActivityNamespace::DFRN);
897 $entry->setAttribute("xmlns:activity", ActivityNamespace::ACTIVITY);
898 $entry->setAttribute("xmlns:georss", ActivityNamespace::GEORSS);
899 $entry->setAttribute("xmlns:poco", ActivityNamespace::POCO);
900 $entry->setAttribute("xmlns:ostatus", ActivityNamespace::OSTATUS);
901 $entry->setAttribute("xmlns:statusnet", ActivityNamespace::STATUSNET);
904 $body = Post\Media::addAttachmentsToBody($item['uri-id'], $item['body'] ?? '');
906 if ($item['private'] == Item::PRIVATE) {
907 $body = Item::fixPrivatePhotos($body, $owner['uid'], $item, $cid);
910 // Remove the abstract element. It is only locally important.
911 $body = BBCode::stripAbstract($body);
914 if ($type == 'html') {
917 if ($item['title'] != "") {
918 $htmlbody = "[b]" . $item['title'] . "[/b]\n\n" . $htmlbody;
921 $htmlbody = BBCode::convert($htmlbody, false, BBCode::OSTATUS);
924 $author = self::addEntryAuthor($doc, "author", $item["author-link"], $item);
925 $entry->appendChild($author);
927 $dfrnowner = self::addEntryAuthor($doc, "dfrn:owner", $item["owner-link"], $item);
928 $entry->appendChild($dfrnowner);
930 if ($item['gravity'] != GRAVITY_PARENT) {
931 $parent = Post::selectFirst(['guid', 'plink'], ['uri' => $item['thr-parent'], 'uid' => $item['uid']]);
932 if (DBA::isResult($parent)) {
933 $attributes = ["ref" => $item['thr-parent'], "type" => "text/html",
934 "href" => $parent['plink'],
935 "dfrn:diaspora_guid" => $parent['guid']];
936 XML::addElement($doc, $entry, "thr:in-reply-to", "", $attributes);
940 // Add conversation data. This is used for OStatus
941 $conversation_href = DI::baseUrl()."/display/".$item["parent-guid"];
942 $conversation_uri = $conversation_href;
944 if (isset($parent_item)) {
945 $conversation = DBA::selectFirst('conversation', ['conversation-uri', 'conversation-href'], ['item-uri' => $item['thr-parent']]);
946 if (DBA::isResult($conversation)) {
947 if ($conversation['conversation-uri'] != '') {
948 $conversation_uri = $conversation['conversation-uri'];
950 if ($conversation['conversation-href'] != '') {
951 $conversation_href = $conversation['conversation-href'];
957 "href" => $conversation_href,
958 "ref" => $conversation_uri];
960 XML::addElement($doc, $entry, "ostatus:conversation", $conversation_uri, $attributes);
962 XML::addElement($doc, $entry, "id", $item["uri"]);
963 XML::addElement($doc, $entry, "title", $item["title"]);
965 XML::addElement($doc, $entry, "published", DateTimeFormat::utc($item["created"] . "+00:00", DateTimeFormat::ATOM));
966 XML::addElement($doc, $entry, "updated", DateTimeFormat::utc($item["edited"] . "+00:00", DateTimeFormat::ATOM));
968 // "dfrn:env" is used to read the content
969 XML::addElement($doc, $entry, "dfrn:env", Strings::base64UrlEncode($body, true));
971 // The "content" field is not read by the receiver. We could remove it when the type is "text"
972 // We keep it at the moment, maybe there is some old version that doesn't read "dfrn:env"
973 XML::addElement($doc, $entry, "content", (($type == 'html') ? $htmlbody : $body), ["type" => $type]);
975 // We save this value in "plink". Maybe we should read it from there as well?
981 ["rel" => "alternate", "type" => "text/html",
982 "href" => DI::baseUrl() . "/display/" . $item["guid"]]
985 // "comment-allow" is some old fashioned stuff for old Friendica versions.
986 // It is included in the rewritten code for completeness
988 XML::addElement($doc, $entry, "dfrn:comment-allow", 1);
991 if ($item['location']) {
992 XML::addElement($doc, $entry, "dfrn:location", $item['location']);
995 if ($item['coord']) {
996 XML::addElement($doc, $entry, "georss:point", $item['coord']);
999 if ($item['private']) {
1000 // Friendica versions prior to 2020.3 can't handle "unlisted" properly. So we can only transmit public and private
1001 XML::addElement($doc, $entry, "dfrn:private", ($item['private'] == Item::PRIVATE ? Item::PRIVATE : Item::PUBLIC));
1002 XML::addElement($doc, $entry, "dfrn:unlisted", $item['private'] == Item::UNLISTED);
1005 if ($item['extid']) {
1006 XML::addElement($doc, $entry, "dfrn:extid", $item['extid']);
1009 if ($item['post-type'] == Item::PT_PAGE) {
1010 XML::addElement($doc, $entry, "dfrn:bookmark", "true");
1014 XML::addElement($doc, $entry, "statusnet:notice_info", "", ["local_id" => $item['id'], "source" => $item['app']]);
1017 XML::addElement($doc, $entry, "dfrn:diaspora_guid", $item["guid"]);
1019 // The signed text contains the content in Markdown, the sender handle and the signatur for the content
1020 // It is needed for relayed comments to Diaspora.
1021 if ($item['signed_text']) {
1022 $sign = base64_encode(json_encode(['signed_text' => $item['signed_text'],'signature' => '','signer' => '']));
1023 XML::addElement($doc, $entry, "dfrn:diaspora_signature", $sign);
1026 XML::addElement($doc, $entry, "activity:verb", self::constructVerb($item));
1028 if ($item['object-type'] != "") {
1029 XML::addElement($doc, $entry, "activity:object-type", $item['object-type']);
1030 } elseif ($item['gravity'] == GRAVITY_PARENT) {
1031 XML::addElement($doc, $entry, "activity:object-type", Activity\ObjectType::NOTE);
1033 XML::addElement($doc, $entry, "activity:object-type", Activity\ObjectType::COMMENT);
1036 $actobj = self::createActivity($doc, "activity:object", $item['object']);
1038 $entry->appendChild($actobj);
1041 $actarg = self::createActivity($doc, "activity:target", $item['target']);
1043 $entry->appendChild($actarg);
1046 $tags = Tag::getByURIId($item['uri-id']);
1049 foreach ($tags as $tag) {
1050 if (($type != 'html') || ($tag['type'] == Tag::HASHTAG)) {
1051 XML::addElement($doc, $entry, "category", "", ["scheme" => "X-DFRN:" . Tag::TAG_CHARACTER[$tag['type']] . ":" . $tag['url'], "term" => $tag['name']]);
1053 if ($tag['type'] != Tag::HASHTAG) {
1054 $mentioned[$tag['url']] = $tag['url'];
1059 foreach ($mentioned as $mention) {
1060 $condition = ['uid' => $owner["uid"], 'nurl' => Strings::normaliseLink($mention)];
1061 $contact = DBA::selectFirst('contact', ['forum', 'prv'], $condition);
1063 if (DBA::isResult($contact) && ($contact["forum"] || $contact["prv"])) {
1069 ["rel" => "mentioned",
1070 "ostatus:object-type" => Activity\ObjectType::GROUP,
1079 ["rel" => "mentioned",
1080 "ostatus:object-type" => Activity\ObjectType::PERSON,
1086 self::getAttachment($doc, $entry, $item);
1092 * encrypts data via AES
1094 * @param string $data The data that is to be encrypted
1095 * @param string $key The AES key
1097 * @return string encrypted data
1099 private static function aesEncrypt($data, $key)
1101 return openssl_encrypt($data, 'aes-128-ecb', $key, OPENSSL_RAW_DATA);
1105 * decrypts data via AES
1107 * @param string $encrypted The encrypted data
1108 * @param string $key The AES key
1110 * @return string decrypted data
1112 public static function aesDecrypt($encrypted, $key)
1114 return openssl_decrypt($encrypted, 'aes-128-ecb', $key, OPENSSL_RAW_DATA);
1118 * Delivers the atom content to the contacts
1120 * @param array $owner Owner record
1121 * @param array $contact Contact record of the receiver
1122 * @param string $atom Content that will be transmitted
1123 * @param bool $dissolve (to be documented)
1125 * @return int Deliver status. Negative values mean an error.
1126 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1127 * @throws \ImagickException
1128 * @todo Add array type-hint for $owner, $contact
1130 public static function deliver($owner, $contact, $atom, $dissolve = false)
1132 $idtosend = $orig_id = (($contact['dfrn-id']) ? $contact['dfrn-id'] : $contact['issued-id']);
1134 if ($contact['duplex'] && $contact['dfrn-id']) {
1135 $idtosend = '0:' . $orig_id;
1137 if ($contact['duplex'] && $contact['issued-id']) {
1138 $idtosend = '1:' . $orig_id;
1141 $rino = DI::config()->get('system', 'rino_encrypt');
1142 $rino = intval($rino);
1144 Logger::log("Local rino version: ". $rino, Logger::DEBUG);
1146 $ssl_val = intval(DI::config()->get('system', 'ssl_policy'));
1149 case BaseURL::SSL_POLICY_FULL:
1150 $ssl_policy = 'full';
1152 case BaseURL::SSL_POLICY_SELFSIGN:
1153 $ssl_policy = 'self';
1155 case BaseURL::SSL_POLICY_NONE:
1157 $ssl_policy = 'none';
1161 $url = $contact['notify'] . '&dfrn_id=' . $idtosend . '&dfrn_version=' . DFRN_PROTOCOL_VERSION . (($rino) ? '&rino='.$rino : '');
1163 Logger::log('dfrn_deliver: ' . $url);
1165 $curlResult = DI::httpRequest()->get($url);
1167 if ($curlResult->isTimeout()) {
1168 return -2; // timed out
1171 $xml = $curlResult->getBody();
1173 $curl_stat = $curlResult->getReturnCode();
1174 if (empty($curl_stat)) {
1175 return -3; // timed out
1178 Logger::log('dfrn_deliver: ' . $xml, Logger::DATA);
1184 if (strpos($xml, '<?xml') === false) {
1185 Logger::log('dfrn_deliver: no valid XML returned');
1186 Logger::log('dfrn_deliver: returned XML: ' . $xml, Logger::DATA);
1190 $res = XML::parseString($xml);
1192 if (!is_object($res) || (intval($res->status) != 0) || !strlen($res->challenge) || !strlen($res->dfrn_id)) {
1193 if (empty($res->status)) {
1196 $status = $res->status;
1203 $sent_dfrn_id = hex2bin((string) $res->dfrn_id);
1204 $challenge = hex2bin((string) $res->challenge);
1205 $perm = (($res->perm) ? $res->perm : null);
1206 $dfrn_version = floatval($res->dfrn_version ?: 2.0);
1207 $rino_remote_version = intval($res->rino);
1208 $page = (($owner['page-flags'] == User::PAGE_FLAGS_COMMUNITY) ? 1 : 0);
1210 Logger::log("Remote rino version: ".$rino_remote_version." for ".$contact["url"], Logger::DEBUG);
1212 if ($owner['page-flags'] == User::PAGE_FLAGS_PRVGROUP) {
1216 $final_dfrn_id = '';
1219 if ((($perm == 'rw') && !intval($contact['writable']))
1220 || (($perm == 'r') && intval($contact['writable']))
1222 DBA::update('contact', ['writable' => ($perm == 'rw')], ['id' => $contact['id']]);
1224 $contact['writable'] = (string) 1 - intval($contact['writable']);
1228 if (($contact['duplex'] && strlen($contact['pubkey']))
1229 || ($owner['page-flags'] == User::PAGE_FLAGS_COMMUNITY && strlen($contact['pubkey']))
1230 || ($contact['rel'] == Contact::SHARING && strlen($contact['pubkey']))
1232 openssl_public_decrypt($sent_dfrn_id, $final_dfrn_id, $contact['pubkey']);
1233 openssl_public_decrypt($challenge, $postvars['challenge'], $contact['pubkey']);
1235 openssl_private_decrypt($sent_dfrn_id, $final_dfrn_id, $contact['prvkey']);
1236 openssl_private_decrypt($challenge, $postvars['challenge'], $contact['prvkey']);
1239 $final_dfrn_id = substr($final_dfrn_id, 0, strpos($final_dfrn_id, '.'));
1241 if (strpos($final_dfrn_id, ':') == 1) {
1242 $final_dfrn_id = substr($final_dfrn_id, 2);
1245 if ($final_dfrn_id != $orig_id) {
1246 Logger::log('dfrn_deliver: wrong dfrn_id.');
1247 // did not decode properly - cannot trust this site
1251 $postvars['dfrn_id'] = $idtosend;
1252 $postvars['dfrn_version'] = DFRN_PROTOCOL_VERSION;
1254 $postvars['dissolve'] = '1';
1257 if ((($contact['rel']) && ($contact['rel'] != Contact::SHARING) && (! $contact['blocked'])) || ($owner['page-flags'] == User::PAGE_FLAGS_COMMUNITY)) {
1258 $postvars['data'] = $atom;
1259 $postvars['perm'] = 'rw';
1261 $postvars['data'] = str_replace('<dfrn:comment-allow>1', '<dfrn:comment-allow>0', $atom);
1262 $postvars['perm'] = 'r';
1265 $postvars['ssl_policy'] = $ssl_policy;
1268 $postvars['page'] = $page;
1272 if ($rino > 0 && $rino_remote_version > 0 && (! $dissolve)) {
1273 Logger::log('rino version: '. $rino_remote_version);
1275 switch ($rino_remote_version) {
1277 $key = random_bytes(16);
1278 $data = self::aesEncrypt($postvars['data'], $key);
1282 Logger::log("rino: invalid requested version '$rino_remote_version'");
1286 $postvars['rino'] = $rino_remote_version;
1287 $postvars['data'] = bin2hex($data);
1289 if ($dfrn_version >= 2.1) {
1290 if (($contact['duplex'] && strlen($contact['pubkey']))
1291 || ($owner['page-flags'] == User::PAGE_FLAGS_COMMUNITY && strlen($contact['pubkey']))
1292 || ($contact['rel'] == Contact::SHARING && strlen($contact['pubkey']))
1294 openssl_public_encrypt($key, $postvars['key'], $contact['pubkey']);
1296 openssl_private_encrypt($key, $postvars['key'], $contact['prvkey']);
1299 if (($contact['duplex'] && strlen($contact['prvkey'])) || ($owner['page-flags'] == User::PAGE_FLAGS_COMMUNITY)) {
1300 openssl_private_encrypt($key, $postvars['key'], $contact['prvkey']);
1302 openssl_public_encrypt($key, $postvars['key'], $contact['pubkey']);
1306 Logger::log('md5 rawkey ' . md5($postvars['key']));
1308 $postvars['key'] = bin2hex($postvars['key']);
1312 Logger::debug('dfrn_deliver', ['post' => $postvars]);
1314 $postResult = DI::httpRequest()->post($contact['notify'], $postvars);
1316 $xml = $postResult->getBody();
1318 Logger::log('dfrn_deliver: ' . "RECEIVED: " . $xml, Logger::DATA);
1320 $curl_stat = $postResult->getReturnCode();
1321 if (empty($curl_stat) || empty($xml)) {
1322 return -9; // timed out
1325 if (($curl_stat == 503) && stristr($postResult->getHeader(), 'retry-after')) {
1329 if (strpos($xml, '<?xml') === false) {
1330 Logger::log('dfrn_deliver: phase 2: no valid XML returned');
1331 Logger::log('dfrn_deliver: phase 2: returned XML: ' . $xml, Logger::DATA);
1335 $res = XML::parseString($xml);
1337 if (!isset($res->status)) {
1341 // Possibly old servers had returned an empty value when everything was okay
1342 if (empty($res->status)) {
1346 if (!empty($res->message)) {
1347 Logger::log('Delivery returned status '.$res->status.' - '.$res->message, Logger::DEBUG);
1350 return intval($res->status);
1354 * Transmits atom content to the contacts via the Diaspora transport layer
1356 * @param array $owner Owner record
1357 * @param array $contact Contact record of the receiver
1358 * @param string $atom Content that will be transmitted
1360 * @param bool $public_batch
1361 * @return int Deliver status. Negative values mean an error.
1362 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1363 * @throws \ImagickException
1365 public static function transmit($owner, $contact, $atom, $public_batch = false)
1367 if (!$public_batch) {
1368 if (empty($contact['addr'])) {
1369 Logger::log('Empty contact handle for ' . $contact['id'] . ' - ' . $contact['url'] . ' - trying to update it.');
1370 if (Contact::updateFromProbe($contact['id'])) {
1371 $new_contact = DBA::selectFirst('contact', ['addr'], ['id' => $contact['id']]);
1372 $contact['addr'] = $new_contact['addr'];
1375 if (empty($contact['addr'])) {
1376 Logger::log('Unable to find contact handle for ' . $contact['id'] . ' - ' . $contact['url']);
1381 $fcontact = FContact::getByURL($contact['addr']);
1382 if (empty($fcontact)) {
1383 Logger::log('Unable to find contact details for ' . $contact['id'] . ' - ' . $contact['addr']);
1386 $pubkey = $fcontact['pubkey'];
1391 $envelope = Diaspora::buildMessage($atom, $owner, $contact, $owner['uprvkey'], $pubkey, $public_batch);
1393 // Create the endpoint for public posts. This is some WIP and should later be added to the probing
1394 if ($public_batch && empty($contact["batch"])) {
1395 $parts = parse_url($contact["notify"]);
1396 $path_parts = explode('/', $parts['path']);
1397 array_pop($path_parts);
1398 $parts['path'] = implode('/', $path_parts);
1399 $contact["batch"] = Network::unparseURL($parts);
1402 $dest_url = ($public_batch ? $contact["batch"] : $contact["notify"]);
1404 if (empty($dest_url)) {
1405 Logger::info('Empty destination', ['public' => $public_batch, 'contact' => $contact]);
1409 $content_type = ($public_batch ? "application/magic-envelope+xml" : "application/json");
1411 $postResult = DI::httpRequest()->post($dest_url, $envelope, ["Content-Type: " . $content_type]);
1412 $xml = $postResult->getBody();
1414 $curl_stat = $postResult->getReturnCode();
1415 if (empty($curl_stat) || empty($xml)) {
1416 Logger::log('Empty answer from ' . $contact['id'] . ' - ' . $dest_url);
1417 return -9; // timed out
1420 if (($curl_stat == 503) && (stristr($postResult->getHeader(), 'retry-after'))) {
1424 if (strpos($xml, '<?xml') === false) {
1425 Logger::log('No valid XML returned from ' . $contact['id'] . ' - ' . $dest_url);
1426 Logger::log('Returned XML: ' . $xml, Logger::DATA);
1430 $res = XML::parseString($xml);
1432 if (empty($res->status)) {
1436 if (!empty($res->message)) {
1437 Logger::log('Transmit to ' . $dest_url . ' returned status '.$res->status.' - '.$res->message, Logger::DEBUG);
1440 return intval($res->status);
1444 * Fetch the author data from head or entry items
1446 * @param \DOMXPath $xpath XPath object
1447 * @param \DOMNode $context In which context should the data be searched
1448 * @param array $importer Record of the importer user mixed with contact of the content
1449 * @param string $element Element name from which the data is fetched
1450 * @param bool $onlyfetch Should the data only be fetched or should it update the contact record as well
1451 * @param string $xml optional, default empty
1453 * @return array Relevant data of the author
1454 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1455 * @throws \ImagickException
1456 * @todo Find good type-hints for all parameter
1458 private static function fetchauthor(\DOMXPath $xpath, \DOMNode $context, $importer, $element, $onlyfetch, $xml = "")
1461 $author["name"] = XML::getFirstNodeValue($xpath, $element."/atom:name/text()", $context);
1462 $author["link"] = XML::getFirstNodeValue($xpath, $element."/atom:uri/text()", $context);
1464 $fields = ['id', 'uid', 'url', 'network', 'avatar-date', 'avatar', 'name-date', 'uri-date', 'addr',
1465 'name', 'nick', 'about', 'location', 'keywords', 'xmpp', 'bdyear', 'bd', 'hidden', 'contact-type'];
1466 $condition = ["`uid` = ? AND `nurl` = ? AND `network` != ? AND NOT `pending` AND NOT `blocked`",
1467 $importer["importer_uid"], Strings::normaliseLink($author["link"]), Protocol::STATUSNET];
1469 if ($importer['account-type'] != User::ACCOUNT_TYPE_COMMUNITY) {
1470 $condition = DBA::mergeConditions($condition, ['rel' => [Contact::SHARING, Contact::FRIEND]]);
1473 $contact_old = DBA::selectFirst('contact', $fields, $condition);
1475 if (DBA::isResult($contact_old)) {
1476 $author["contact-id"] = $contact_old["id"];
1477 $author["network"] = $contact_old["network"];
1479 Logger::info('Contact not found', ['condition' => $condition]);
1481 $author["contact-unknown"] = true;
1482 $contact = Contact::getByURL($author["link"], null, ["id", "network"]);
1483 $author["contact-id"] = $contact["id"] ?? $importer["id"];
1484 $author["network"] = $contact["network"] ?? $importer["network"];
1488 // Until now we aren't serving different sizes - but maybe later
1490 /// @todo check if "avatar" or "photo" would be the best field in the specification
1491 $avatars = $xpath->query($element . "/atom:link[@rel='avatar']", $context);
1492 foreach ($avatars as $avatar) {
1495 foreach ($avatar->attributes as $attributes) {
1496 /// @TODO Rewrite these similar if() to one switch
1497 if ($attributes->name == "href") {
1498 $href = $attributes->textContent;
1500 if ($attributes->name == "width") {
1501 $width = $attributes->textContent;
1503 if ($attributes->name == "updated") {
1504 $author["avatar-date"] = $attributes->textContent;
1507 if (($width > 0) && ($href != "")) {
1508 $avatarlist[$width] = $href;
1512 if (count($avatarlist) > 0) {
1513 krsort($avatarlist);
1514 $author["avatar"] = current($avatarlist);
1517 if (empty($author['avatar']) && !empty($author['link'])) {
1518 $cid = Contact::getIdForURL($author['link'], 0);
1520 $contact = DBA::selectFirst('contact', ['avatar'], ['id' => $cid]);
1521 if (DBA::isResult($contact)) {
1522 $author['avatar'] = $contact['avatar'];
1527 if (empty($author['avatar'])) {
1528 Logger::log('Empty author: ' . $xml);
1529 $author['avatar'] = '';
1532 if (DBA::isResult($contact_old) && !$onlyfetch) {
1533 Logger::log("Check if contact details for contact " . $contact_old["id"] . " (" . $contact_old["nick"] . ") have to be updated.", Logger::DEBUG);
1535 $poco = ["url" => $contact_old["url"], "network" => $contact_old["network"]];
1537 // When was the last change to name or uri?
1538 $name_element = $xpath->query($element . "/atom:name", $context)->item(0);
1539 foreach ($name_element->attributes as $attributes) {
1540 if ($attributes->name == "updated") {
1541 $poco["name-date"] = $attributes->textContent;
1545 $link_element = $xpath->query($element . "/atom:link", $context)->item(0);
1546 foreach ($link_element->attributes as $attributes) {
1547 if ($attributes->name == "updated") {
1548 $poco["uri-date"] = $attributes->textContent;
1552 // Update contact data
1553 $value = XML::getFirstNodeValue($xpath, $element . "/dfrn:handle/text()", $context);
1555 $poco["addr"] = $value;
1558 $value = XML::getFirstNodeValue($xpath, $element . "/poco:displayName/text()", $context);
1560 $poco["name"] = $value;
1563 $value = XML::getFirstNodeValue($xpath, $element . "/poco:preferredUsername/text()", $context);
1565 $poco["nick"] = $value;
1568 $value = XML::getFirstNodeValue($xpath, $element . "/poco:note/text()", $context);
1570 $poco["about"] = $value;
1573 $value = XML::getFirstNodeValue($xpath, $element . "/poco:address/poco:formatted/text()", $context);
1575 $poco["location"] = $value;
1578 /// @todo Only search for elements with "poco:type" = "xmpp"
1579 $value = XML::getFirstNodeValue($xpath, $element . "/poco:ims/poco:value/text()", $context);
1581 $poco["xmpp"] = $value;
1584 /// @todo Add support for the following fields that we don't support by now in the contact table:
1585 /// - poco:utcOffset
1591 // If the "hide" element is present then the profile isn't searchable.
1592 $hide = intval(XML::getFirstNodeValue($xpath, $element . "/dfrn:hide/text()", $context) == "true");
1594 Logger::log("Hidden status for contact " . $contact_old["url"] . ": " . $hide, Logger::DEBUG);
1596 // If the contact isn't searchable then set the contact to "hidden".
1597 // Problem: This can be manually overridden by the user.
1599 $contact_old["hidden"] = true;
1602 // Save the keywords into the contact table
1604 $tagelements = $xpath->evaluate($element . "/poco:tags/text()", $context);
1605 foreach ($tagelements as $tag) {
1606 $tags[$tag->nodeValue] = $tag->nodeValue;
1610 $poco["keywords"] = implode(", ", $tags);
1613 // "dfrn:birthday" contains the birthday converted to UTC
1614 $birthday = XML::getFirstNodeValue($xpath, $element . "/dfrn:birthday/text()", $context);
1616 $birthday_date = new \DateTime($birthday);
1617 if ($birthday_date > new \DateTime()) {
1618 $poco["bdyear"] = $birthday_date->format("Y");
1620 } catch (\Exception $e) {
1624 // "poco:birthday" is the birthday in the format "yyyy-mm-dd"
1625 $value = XML::getFirstNodeValue($xpath, $element . "/poco:birthday/text()", $context);
1627 if (!in_array($value, ["", "0000-00-00", DBA::NULL_DATE])) {
1628 $bdyear = date("Y");
1629 $value = str_replace(["0000", "0001"], $bdyear, $value);
1631 if (strtotime($value) < time()) {
1632 $value = str_replace($bdyear, $bdyear + 1, $value);
1635 $poco["bd"] = $value;
1638 $contact = array_merge($contact_old, $poco);
1640 if ($contact_old["bdyear"] != $contact["bdyear"]) {
1641 Event::createBirthday($contact, $birthday);
1644 $fields = ['name' => $contact['name'], 'nick' => $contact['nick'], 'about' => $contact['about'],
1645 'location' => $contact['location'], 'addr' => $contact['addr'], 'keywords' => $contact['keywords'],
1646 'bdyear' => $contact['bdyear'], 'bd' => $contact['bd'], 'hidden' => $contact['hidden'],
1647 'xmpp' => $contact['xmpp'], 'name-date' => DateTimeFormat::utc($contact['name-date']),
1648 'unsearchable' => $contact['hidden'], 'uri-date' => DateTimeFormat::utc($contact['uri-date'])];
1650 DBA::update('contact', $fields, ['id' => $contact['id'], 'network' => $contact['network']], $contact_old);
1652 // Update the public contact. Don't set the "hidden" value, this is used differently for public contacts
1653 unset($fields['hidden']);
1654 $condition = ['uid' => 0, 'nurl' => Strings::normaliseLink($contact_old['url'])];
1655 DBA::update('contact', $fields, $condition, true);
1657 Contact::updateAvatar($contact['id'], $author['avatar']);
1659 $pcid = Contact::getIdForURL($contact_old['url']);
1660 if (!empty($pcid)) {
1661 Contact::updateAvatar($pcid, $author['avatar']);
1669 * Transforms activity objects into an XML string
1671 * @param object $xpath XPath object
1672 * @param object $activity Activity object
1673 * @param string $element element name
1675 * @return string XML string
1676 * @todo Find good type-hints for all parameter
1678 private static function transformActivity($xpath, $activity, $element)
1680 if (!is_object($activity)) {
1684 $obj_doc = new DOMDocument("1.0", "utf-8");
1685 $obj_doc->formatOutput = true;
1687 $obj_element = $obj_doc->createElementNS( ActivityNamespace::ATOM1, $element);
1689 $activity_type = $xpath->query("activity:object-type/text()", $activity)->item(0)->nodeValue;
1690 XML::addElement($obj_doc, $obj_element, "type", $activity_type);
1692 $id = $xpath->query("atom:id", $activity)->item(0);
1693 if (is_object($id)) {
1694 $obj_element->appendChild($obj_doc->importNode($id, true));
1697 $title = $xpath->query("atom:title", $activity)->item(0);
1698 if (is_object($title)) {
1699 $obj_element->appendChild($obj_doc->importNode($title, true));
1702 $links = $xpath->query("atom:link", $activity);
1703 if (is_object($links)) {
1704 foreach ($links as $link) {
1705 $obj_element->appendChild($obj_doc->importNode($link, true));
1709 $content = $xpath->query("atom:content", $activity)->item(0);
1710 if (is_object($content)) {
1711 $obj_element->appendChild($obj_doc->importNode($content, true));
1714 $obj_doc->appendChild($obj_element);
1716 $objxml = $obj_doc->saveXML($obj_element);
1718 /// @todo This isn't totally clean. We should find a way to transform the namespaces
1719 $objxml = str_replace("<".$element.' xmlns="http://www.w3.org/2005/Atom">', "<".$element.">", $objxml);
1724 * Processes the mail elements
1726 * @param object $xpath XPath object
1727 * @param object $mail mail elements
1728 * @param array $importer Record of the importer user mixed with contact of the content
1730 * @throws \Exception
1731 * @todo Find good type-hints for all parameter
1733 private static function processMail($xpath, $mail, $importer)
1735 Logger::log("Processing mails");
1738 $msg["uid"] = $importer["importer_uid"];
1739 $msg["from-name"] = XML::getFirstValue($xpath, "dfrn:sender/dfrn:name/text()", $mail);
1740 $msg["from-url"] = XML::getFirstValue($xpath, "dfrn:sender/dfrn:uri/text()", $mail);
1741 $msg["from-photo"] = XML::getFirstValue($xpath, "dfrn:sender/dfrn:avatar/text()", $mail);
1742 $msg["contact-id"] = $importer["id"];
1743 $msg["uri"] = XML::getFirstValue($xpath, "dfrn:id/text()", $mail);
1744 $msg["parent-uri"] = XML::getFirstValue($xpath, "dfrn:in-reply-to/text()", $mail);
1745 $msg["created"] = DateTimeFormat::utc(XML::getFirstValue($xpath, "dfrn:sentdate/text()", $mail));
1746 $msg["title"] = XML::getFirstValue($xpath, "dfrn:subject/text()", $mail);
1747 $msg["body"] = XML::getFirstValue($xpath, "dfrn:content/text()", $mail);
1753 * Processes the suggestion elements
1755 * @param object $xpath XPath object
1756 * @param object $suggestion suggestion elements
1757 * @param array $importer Record of the importer user mixed with contact of the content
1759 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1760 * @todo Find good type-hints for all parameter
1762 private static function processSuggestion($xpath, $suggestion, $importer)
1764 Logger::notice('Processing suggestions');
1766 $url = $xpath->evaluate('string(dfrn:url[1]/text())', $suggestion);
1767 $cid = Contact::getIdForURL($url);
1768 $note = $xpath->evaluate('string(dfrn:note[1]/text())', $suggestion);
1770 return FContact::addSuggestion($importer['importer_uid'], $cid, $importer['id'], $note);
1774 * Processes the relocation elements
1776 * @param object $xpath XPath object
1777 * @param object $relocation relocation elements
1778 * @param array $importer Record of the importer user mixed with contact of the content
1780 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1781 * @throws \ImagickException
1782 * @todo Find good type-hints for all parameter
1784 private static function processRelocation($xpath, $relocation, $importer)
1786 Logger::log("Processing relocations");
1788 /// @TODO Rewrite this to one statement
1790 $relocate["uid"] = $importer["importer_uid"];
1791 $relocate["cid"] = $importer["id"];
1792 $relocate["url"] = $xpath->query("dfrn:url/text()", $relocation)->item(0)->nodeValue;
1793 $relocate["addr"] = $xpath->query("dfrn:addr/text()", $relocation)->item(0)->nodeValue;
1794 $relocate["name"] = $xpath->query("dfrn:name/text()", $relocation)->item(0)->nodeValue;
1795 $relocate["avatar"] = $xpath->query("dfrn:avatar/text()", $relocation)->item(0)->nodeValue;
1796 $relocate["photo"] = $xpath->query("dfrn:photo/text()", $relocation)->item(0)->nodeValue;
1797 $relocate["thumb"] = $xpath->query("dfrn:thumb/text()", $relocation)->item(0)->nodeValue;
1798 $relocate["micro"] = $xpath->query("dfrn:micro/text()", $relocation)->item(0)->nodeValue;
1799 $relocate["request"] = $xpath->query("dfrn:request/text()", $relocation)->item(0)->nodeValue;
1800 $relocate["confirm"] = $xpath->query("dfrn:confirm/text()", $relocation)->item(0)->nodeValue;
1801 $relocate["notify"] = $xpath->query("dfrn:notify/text()", $relocation)->item(0)->nodeValue;
1802 $relocate["poll"] = $xpath->query("dfrn:poll/text()", $relocation)->item(0)->nodeValue;
1803 $relocate["sitepubkey"] = $xpath->query("dfrn:sitepubkey/text()", $relocation)->item(0)->nodeValue;
1805 if (($relocate["avatar"] == "") && ($relocate["photo"] != "")) {
1806 $relocate["avatar"] = $relocate["photo"];
1809 if ($relocate["addr"] == "") {
1810 $relocate["addr"] = preg_replace("=(https?://)(.*)/profile/(.*)=ism", "$3@$2", $relocate["url"]);
1815 "SELECT `photo`, `url` FROM `contact` WHERE `id` = %d AND `uid` = %d",
1816 intval($importer["id"]),
1817 intval($importer["importer_uid"])
1820 if (!DBA::isResult($r)) {
1821 Logger::log("Query failed to execute, no result returned in " . __FUNCTION__);
1827 // Update the contact table. We try to find every entry.
1828 $fields = ['name' => $relocate["name"], 'avatar' => $relocate["avatar"],
1829 'url' => $relocate["url"], 'nurl' => Strings::normaliseLink($relocate["url"]),
1830 'addr' => $relocate["addr"], 'request' => $relocate["request"],
1831 'confirm' => $relocate["confirm"], 'notify' => $relocate["notify"],
1832 'poll' => $relocate["poll"], 'site-pubkey' => $relocate["sitepubkey"]];
1833 $condition = ["(`id` = ?) OR (`nurl` = ?)", $importer["id"], Strings::normaliseLink($old["url"])];
1835 DBA::update('contact', $fields, $condition);
1837 Contact::updateAvatar($importer["id"], $relocate["avatar"], true);
1839 Logger::log('Contacts are updated.');
1842 /// merge with current record, current contents have priority
1843 /// update record, set url-updated
1844 /// update profile photos
1845 /// schedule a scan?
1852 * @param array $current the current item record
1853 * @param array $item the new item record
1854 * @param array $importer Record of the importer user mixed with contact of the content
1855 * @param int $entrytype Is it a toplevel entry, a comment or a relayed comment?
1857 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1858 * @todo set proper type-hints (array?)
1860 private static function updateContent($current, $item, $importer, $entrytype)
1864 if (self::isEditedTimestampNewer($current, $item)) {
1865 // do not accept (ignore) an earlier edit than one we currently have.
1866 if (DateTimeFormat::utc($item["edited"]) < $current["edited"]) {
1870 $fields = ['title' => $item['title'] ?? '', 'body' => $item['body'] ?? '',
1871 'changed' => DateTimeFormat::utcNow(),
1872 'edited' => DateTimeFormat::utc($item["edited"])];
1874 $condition = ["`uri` = ? AND `uid` IN (0, ?)", $item["uri"], $importer["importer_uid"]];
1875 Item::update($fields, $condition);
1883 * Detects the entry type of the item
1885 * @param array $importer Record of the importer user mixed with contact of the content
1886 * @param array $item the new item record
1888 * @return int Is it a toplevel entry, a comment or a relayed comment?
1889 * @throws \Exception
1890 * @todo set proper type-hints (array?)
1892 private static function getEntryType($importer, $item)
1894 if ($item["thr-parent"] != $item["uri"]) {
1897 if ($importer["page-flags"] == User::PAGE_FLAGS_COMMUNITY || $importer["page-flags"] == User::PAGE_FLAGS_PRVGROUP) {
1900 Logger::log("possible community action");
1902 $sql_extra = " AND `self` AND `wall`";
1905 // was the top-level post for this action written by somebody on this site?
1906 // Specifically, the recipient?
1907 $parent = Post::selectFirst(['forum_mode', 'wall'],
1908 ["`uri` = ? AND `uid` = ?" . $sql_extra, $item["thr-parent"], $importer["importer_uid"]]);
1910 $is_a_remote_action = DBA::isResult($parent);
1913 * Does this have the characteristics of a community or private group action?
1914 * If it's an action to a wall post on a community/prvgroup page it's a
1915 * valid community action. Also forum_mode makes it valid for sure.
1916 * If neither, it's not.
1918 if ($is_a_remote_action && $community && (!$parent["forum_mode"]) && (!$parent["wall"])) {
1919 $is_a_remote_action = false;
1920 Logger::log("not a community action");
1923 if ($is_a_remote_action) {
1924 return DFRN::REPLY_RC;
1929 return DFRN::TOP_LEVEL;
1936 * @param array $item The new item record
1937 * @param array $importer Record of the importer user mixed with contact of the content
1939 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1940 * @todo set proper type-hints (array?)
1942 private static function doPoke(array $item, array $importer)
1944 $verb = urldecode(substr($item["verb"], strpos($item["verb"], "#")+1));
1948 $xo = XML::parseString($item["object"]);
1950 if (($xo->type == Activity\ObjectType::PERSON) && ($xo->id)) {
1951 // somebody was poked/prodded. Was it me?
1953 foreach ($xo->link as $l) {
1954 $atts = $l->attributes();
1955 switch ($atts["rel"]) {
1957 $Blink = $atts["href"];
1964 if ($Blink && Strings::compareLink($Blink, DI::baseUrl() . "/profile/" . $importer["nickname"])) {
1965 $author = DBA::selectFirst('contact', ['id', 'name', 'thumb', 'url'], ['id' => $item['author-id']]);
1967 $parent = Post::selectFirst(['id'], ['uri' => $item['thr-parent'], 'uid' => $importer["importer_uid"]]);
1968 $item['parent'] = $parent['id'];
1970 // send a notification
1973 "type" => Notification\Type::POKE,
1974 "otype" => Notification\ObjectType::PERSON,
1975 "activity" => $verb,
1976 "verb" => $item["verb"],
1977 "uid" => $importer["importer_uid"],
1978 "cid" => $author["id"],
1980 "link" => DI::baseUrl() . "/display/" . urlencode($item['guid']),
1988 * Processes several actions, depending on the verb
1990 * @param int $entrytype Is it a toplevel entry, a comment or a relayed comment?
1991 * @param array $importer Record of the importer user mixed with contact of the content
1992 * @param array $item the new item record
1993 * @param bool $is_like Is the verb a "like"?
1995 * @return bool Should the processing of the entries be continued?
1996 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1997 * @todo set proper type-hints (array?)
1999 private static function processVerbs($entrytype, $importer, &$item, &$is_like)
2001 Logger::log("Process verb ".$item["verb"]." and object-type ".$item["object-type"]." for entrytype ".$entrytype, Logger::DEBUG);
2003 if (($entrytype == DFRN::TOP_LEVEL) && !empty($importer['id'])) {
2004 // The filling of the the "contact" variable is done for legcy reasons
2005 // The functions below are partly used by ostatus.php as well - where we have this variable
2006 $contact = Contact::selectFirst([], ['id' => $importer['id']]);
2008 $activity = DI::activity();
2010 // Big question: Do we need these functions? They were part of the "consume_feed" function.
2011 // This function once was responsible for DFRN and OStatus.
2012 if ($activity->match($item["verb"], Activity::FOLLOW)) {
2013 Logger::log("New follower");
2014 Contact::addRelationship($importer, $contact, $item);
2017 if ($activity->match($item["verb"], Activity::UNFOLLOW)) {
2018 Logger::log("Lost follower");
2019 Contact::removeFollower($importer, $contact, $item);
2022 if ($activity->match($item["verb"], Activity::REQ_FRIEND)) {
2023 Logger::log("New friend request");
2024 Contact::addRelationship($importer, $contact, $item, true);
2027 if ($activity->match($item["verb"], Activity::UNFRIEND)) {
2028 Logger::log("Lost sharer");
2029 Contact::removeSharer($importer, $contact, $item);
2033 if (($item["verb"] == Activity::LIKE)
2034 || ($item["verb"] == Activity::DISLIKE)
2035 || ($item["verb"] == Activity::ATTEND)
2036 || ($item["verb"] == Activity::ATTENDNO)
2037 || ($item["verb"] == Activity::ATTENDMAYBE)
2038 || ($item["verb"] == Activity::ANNOUNCE)
2041 $item["gravity"] = GRAVITY_ACTIVITY;
2042 // only one like or dislike per person
2043 // split into two queries for performance issues
2044 $condition = ['uid' => $item["uid"], 'author-id' => $item["author-id"], 'gravity' => GRAVITY_ACTIVITY,
2045 'verb' => $item['verb'], 'parent-uri' => $item['thr-parent']];
2046 if (Post::exists($condition)) {
2050 $condition = ['uid' => $item["uid"], 'author-id' => $item["author-id"], 'gravity' => GRAVITY_ACTIVITY,
2051 'verb' => $item['verb'], 'thr-parent' => $item['thr-parent']];
2052 if (Post::exists($condition)) {
2056 // The owner of an activity must be the author
2057 $item["owner-name"] = $item["author-name"];
2058 $item["owner-link"] = $item["author-link"];
2059 $item["owner-avatar"] = $item["author-avatar"];
2060 $item["owner-id"] = $item["author-id"];
2065 if (($item["verb"] == Activity::TAG) && ($item["object-type"] == Activity\ObjectType::TAGTERM)) {
2066 $xo = XML::parseString($item["object"]);
2067 $xt = XML::parseString($item["target"]);
2069 if ($xt->type == Activity\ObjectType::NOTE) {
2070 $item_tag = Post::selectFirst(['id', 'uri-id'], ['uri' => $xt->id, 'uid' => $importer["importer_uid"]]);
2072 if (!DBA::isResult($item_tag)) {
2073 Logger::log("Query failed to execute, no result returned in " . __FUNCTION__);
2077 // extract tag, if not duplicate, add to parent item
2079 Tag::store($item_tag['uri-id'], Tag::HASHTAG, $xo->content);
2088 * Processes the link elements
2090 * @param object $links link elements
2091 * @param array $item the item record
2093 * @todo set proper type-hints
2095 private static function parseLinks($links, &$item)
2102 foreach ($links as $link) {
2103 foreach ($link->attributes as $attributes) {
2104 switch ($attributes->name) {
2105 case "href" : $href = $attributes->textContent; break;
2106 case "rel" : $rel = $attributes->textContent; break;
2107 case "type" : $type = $attributes->textContent; break;
2108 case "length": $length = $attributes->textContent; break;
2109 case "title" : $title = $attributes->textContent; break;
2112 if (($rel != "") && ($href != "")) {
2115 $item["plink"] = $href;
2118 Post\Media::insert(['uri-id' => $item['uri-id'], 'type' => Post\Media::DOCUMENT,
2119 'url' => $href, 'mimetype' => $type, 'size' => $length, 'description' => $title]);
2127 * Checks if an incoming message is wanted
2129 * @param array $item
2130 * @return boolean Is the message wanted?
2132 private static function isSolicitedMessage(array $item)
2134 if (DBA::exists('contact', ["`nurl` = ? AND `uid` != ? AND `rel` IN (?, ?)",
2135 Strings::normaliseLink($item["author-link"]), 0, Contact::FRIEND, Contact::SHARING])) {
2136 Logger::info('Author has got followers - accepted', ['uri' => $item['uri'], 'author' => $item["author-link"]]);
2140 $taglist = Tag::getByURIId($item['uri-id'], [Tag::HASHTAG]);
2141 $tags = array_column($taglist, 'name');
2142 return Relay::isSolicitedPost($tags, $item['body'], $item['author-id'], $item['uri'], Protocol::DFRN);
2146 * Processes the entry elements which contain the items and comments
2148 * @param array $header Array of the header elements that always stay the same
2149 * @param object $xpath XPath object
2150 * @param object $entry entry elements
2151 * @param array $importer Record of the importer user mixed with contact of the content
2152 * @param string $xml xml
2154 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2155 * @throws \ImagickException
2156 * @todo Add type-hints
2158 private static function processEntry($header, $xpath, $entry, $importer, $xml, $protocol)
2160 Logger::log("Processing entries");
2164 $item["protocol"] = $protocol;
2166 $item["source"] = $xml;
2169 $item["uri"] = XML::getFirstNodeValue($xpath, "atom:id/text()", $entry);
2171 $item["edited"] = XML::getFirstNodeValue($xpath, "atom:updated/text()", $entry);
2173 $current = Post::selectFirst(['id', 'uid', 'edited', 'body'],
2174 ['uri' => $item["uri"], 'uid' => $importer["importer_uid"]]
2176 // Is there an existing item?
2177 if (DBA::isResult($current) && !self::isEditedTimestampNewer($current, $item)) {
2178 Logger::log("Item ".$item["uri"]." (".$item['edited'].") already existed.", Logger::DEBUG);
2183 $owner = self::fetchauthor($xpath, $entry, $importer, "dfrn:owner", true, $xml);
2185 $owner_unknown = (isset($owner["contact-unknown"]) && $owner["contact-unknown"]);
2187 $item["owner-name"] = $owner["name"];
2188 $item["owner-link"] = $owner["link"];
2189 $item["owner-avatar"] = $owner["avatar"];
2190 $item["owner-id"] = Contact::getIdForURL($owner["link"], 0);
2193 $author = self::fetchauthor($xpath, $entry, $importer, "atom:author", true, $xml);
2195 $item["author-name"] = $author["name"];
2196 $item["author-link"] = $author["link"];
2197 $item["author-avatar"] = $author["avatar"];
2198 $item["author-id"] = Contact::getIdForURL($author["link"], 0);
2200 $item["title"] = XML::getFirstNodeValue($xpath, "atom:title/text()", $entry);
2202 if (!empty($item["title"])) {
2203 $item["post-type"] = Item::PT_ARTICLE;
2205 $item["post-type"] = Item::PT_NOTE;
2208 $item["created"] = XML::getFirstNodeValue($xpath, "atom:published/text()", $entry);
2210 $item["body"] = XML::getFirstNodeValue($xpath, "dfrn:env/text()", $entry);
2211 $item["body"] = str_replace([' ',"\t","\r","\n"], ['','','',''], $item["body"]);
2213 $item["body"] = Strings::base64UrlDecode($item["body"]);
2215 $item["body"] = BBCode::limitBodySize($item["body"]);
2217 /// @todo We should check for a repeated post and if we know the repeated author.
2219 // We don't need the content element since "dfrn:env" is always present
2220 //$item["body"] = $xpath->query("atom:content/text()", $entry)->item(0)->nodeValue;
2222 $item["location"] = XML::getFirstNodeValue($xpath, "dfrn:location/text()", $entry);
2224 $item["coord"] = XML::getFirstNodeValue($xpath, "georss:point", $entry);
2226 $item["private"] = XML::getFirstNodeValue($xpath, "dfrn:private/text()", $entry);
2228 $unlisted = XML::getFirstNodeValue($xpath, "dfrn:unlisted/text()", $entry);
2229 if (!empty($unlisted) && ($item['private'] != Item::PRIVATE)) {
2230 $item['private'] = Item::UNLISTED;
2233 $item["extid"] = XML::getFirstNodeValue($xpath, "dfrn:extid/text()", $entry);
2235 if (XML::getFirstNodeValue($xpath, "dfrn:bookmark/text()", $entry) == "true") {
2236 $item["post-type"] = Item::PT_PAGE;
2239 $notice_info = $xpath->query("statusnet:notice_info", $entry);
2240 if ($notice_info && ($notice_info->length > 0)) {
2241 foreach ($notice_info->item(0)->attributes as $attributes) {
2242 if ($attributes->name == "source") {
2243 $item["app"] = strip_tags($attributes->textContent);
2248 $item["guid"] = XML::getFirstNodeValue($xpath, "dfrn:diaspora_guid/text()", $entry);
2250 $item['uri-id'] = ItemURI::insert(['uri' => $item['uri'], 'guid' => $item['guid']]);
2252 $item["body"] = Item::improveSharedDataInBody($item);
2254 Tag::storeFromBody($item['uri-id'], $item["body"]);
2256 // We store the data from "dfrn:diaspora_signature" in a different table, this is done in "Item::insert"
2257 $dsprsig = XML::unescape(XML::getFirstNodeValue($xpath, "dfrn:diaspora_signature/text()", $entry));
2258 if ($dsprsig != "") {
2259 $signature = json_decode(base64_decode($dsprsig));
2260 // We don't store the old style signatures anymore that also contained the "signature" and "signer"
2261 if (!empty($signature->signed_text) && empty($signature->signature) && empty($signature->signer)) {
2262 $item["diaspora_signed_text"] = $signature->signed_text;
2266 $item["verb"] = XML::getFirstNodeValue($xpath, "activity:verb/text()", $entry);
2268 if (XML::getFirstNodeValue($xpath, "activity:object-type/text()", $entry) != "") {
2269 $item["object-type"] = XML::getFirstNodeValue($xpath, "activity:object-type/text()", $entry);
2272 $object = $xpath->query("activity:object", $entry)->item(0);
2273 $item["object"] = self::transformActivity($xpath, $object, "object");
2275 if (trim($item["object"]) != "") {
2276 $r = XML::parseString($item["object"]);
2277 if (isset($r->type)) {
2278 $item["object-type"] = $r->type;
2282 $target = $xpath->query("activity:target", $entry)->item(0);
2283 $item["target"] = self::transformActivity($xpath, $target, "target");
2285 $categories = $xpath->query("atom:category", $entry);
2287 foreach ($categories as $category) {
2290 foreach ($category->attributes as $attributes) {
2291 if ($attributes->name == "term") {
2292 $term = $attributes->textContent;
2295 if ($attributes->name == "scheme") {
2296 $scheme = $attributes->textContent;
2300 if (($term != "") && ($scheme != "")) {
2301 $parts = explode(":", $scheme);
2302 if ((count($parts) >= 4) && (array_shift($parts) == "X-DFRN")) {
2303 $termurl = array_pop($parts);
2304 $termurl = array_pop($parts) . ':' . $termurl;
2305 Tag::store($item['uri-id'], Tag::IMPLICIT_MENTION, $term, $termurl);
2311 $links = $xpath->query("atom:link", $entry);
2313 self::parseLinks($links, $item);
2316 $item['conversation-uri'] = XML::getFirstNodeValue($xpath, 'ostatus:conversation/text()', $entry);
2318 $conv = $xpath->query('ostatus:conversation', $entry);
2319 if (is_object($conv->item(0))) {
2320 foreach ($conv->item(0)->attributes as $attributes) {
2321 if ($attributes->name == "ref") {
2322 $item['conversation-uri'] = $attributes->textContent;
2324 if ($attributes->name == "href") {
2325 $item['conversation-href'] = $attributes->textContent;
2330 // Is it a reply or a top level posting?
2331 $item['thr-parent'] = $item['uri'];
2333 $inreplyto = $xpath->query("thr:in-reply-to", $entry);
2334 if (is_object($inreplyto->item(0))) {
2335 foreach ($inreplyto->item(0)->attributes as $attributes) {
2336 if ($attributes->name == "ref") {
2337 $item['thr-parent'] = $attributes->textContent;
2342 // Check if the message is wanted
2343 if (($importer['importer_uid'] == 0) && ($item['uri'] == $item['thr-parent'])) {
2344 if (!self::isSolicitedMessage($item)) {
2345 DBA::delete('item-uri', ['uri' => $item['uri']]);
2350 // Get the type of the item (Top level post, reply or remote reply)
2351 $entrytype = self::getEntryType($importer, $item);
2353 // Now assign the rest of the values that depend on the type of the message
2354 if (in_array($entrytype, [DFRN::REPLY, DFRN::REPLY_RC])) {
2355 if (!isset($item["object-type"])) {
2356 $item["object-type"] = Activity\ObjectType::COMMENT;
2359 if ($item["contact-id"] != $owner["contact-id"]) {
2360 $item["contact-id"] = $owner["contact-id"];
2363 if (($item["network"] != $owner["network"]) && ($owner["network"] != "")) {
2364 $item["network"] = $owner["network"];
2367 if ($item["contact-id"] != $author["contact-id"]) {
2368 $item["contact-id"] = $author["contact-id"];
2371 if (($item["network"] != $author["network"]) && ($author["network"] != "")) {
2372 $item["network"] = $author["network"];
2376 // Ensure to have the correct share data
2377 $item = Item::addShareDataFromOriginal($item);
2379 if ($entrytype == DFRN::REPLY_RC) {
2381 } elseif ($entrytype == DFRN::TOP_LEVEL) {
2382 if (!isset($item["object-type"])) {
2383 $item["object-type"] = Activity\ObjectType::NOTE;
2387 if (($item["object-type"] == Activity\ObjectType::EVENT) && !$owner_unknown) {
2388 Logger::log("Item ".$item["uri"]." seems to contain an event.", Logger::DEBUG);
2389 $ev = Event::fromBBCode($item["body"]);
2390 if ((!empty($ev['desc']) || !empty($ev['summary'])) && !empty($ev['start'])) {
2391 Logger::log("Event in item ".$item["uri"]." was found.", Logger::DEBUG);
2392 $ev["cid"] = $importer["id"];
2393 $ev["uid"] = $importer["importer_uid"];
2394 $ev["uri"] = $item["uri"];
2395 $ev["edited"] = $item["edited"];
2396 $ev["private"] = $item["private"];
2397 $ev["guid"] = $item["guid"];
2398 $ev["plink"] = $item["plink"];
2399 $ev["network"] = $item["network"];
2400 $ev["protocol"] = $item["protocol"];
2401 $ev["direction"] = $item["direction"];
2402 $ev["source"] = $item["source"];
2404 $condition = ['uri' => $item["uri"], 'uid' => $importer["importer_uid"]];
2405 $event = DBA::selectFirst('event', ['id'], $condition);
2406 if (DBA::isResult($event)) {
2407 $ev["id"] = $event["id"];
2410 $event_id = Event::store($ev);
2411 Logger::log("Event ".$event_id." was stored", Logger::DEBUG);
2417 if (!self::processVerbs($entrytype, $importer, $item, $is_like)) {
2418 Logger::log("Exiting because 'processVerbs' told us so", Logger::DEBUG);
2422 // This check is done here to be able to receive connection requests in "processVerbs"
2423 if (($entrytype == DFRN::TOP_LEVEL) && $owner_unknown) {
2424 Logger::log("Item won't be stored because user " . $importer["importer_uid"] . " doesn't follow " . $item["owner-link"] . ".", Logger::DEBUG);
2429 // Update content if 'updated' changes
2430 if (DBA::isResult($current)) {
2431 if (self::updateContent($current, $item, $importer, $entrytype)) {
2432 Logger::log("Item ".$item["uri"]." was updated.", Logger::DEBUG);
2434 Logger::log("Item " . $item["uri"] . " already existed.", Logger::DEBUG);
2439 if (in_array($entrytype, [DFRN::REPLY, DFRN::REPLY_RC])) {
2440 // Will be overwritten for sharing accounts in Item::insert
2441 if (empty($item['post-reason']) && ($entrytype == DFRN::REPLY)) {
2442 $item['post-reason'] = Item::PR_COMMENT;
2445 $posted_id = Item::insert($item);
2447 Logger::log("Reply from contact ".$item["contact-id"]." was stored with id ".$posted_id, Logger::DEBUG);
2449 if ($item['uid'] == 0) {
2450 Item::distribute($posted_id);
2455 } else { // $entrytype == DFRN::TOP_LEVEL
2456 if (($importer["uid"] == 0) && ($importer["importer_uid"] != 0)) {
2457 Logger::log("Contact ".$importer["id"]." isn't known to user ".$importer["importer_uid"].". The post will be ignored.", Logger::DEBUG);
2460 if (!Strings::compareLink($item["owner-link"], $importer["url"])) {
2462 * The item owner info is not our contact. It's OK and is to be expected if this is a tgroup delivery,
2463 * but otherwise there's a possible data mixup on the sender's system.
2464 * the tgroup delivery code called from Item::insert will correct it if it's a forum,
2465 * but we're going to unconditionally correct it here so that the post will always be owned by our contact.
2467 Logger::log('Correcting item owner.', Logger::DEBUG);
2468 $item["owner-link"] = $importer["url"];
2469 $item["owner-id"] = Contact::getIdForURL($importer["url"], 0);
2472 if (($importer["rel"] == Contact::FOLLOWER) && (!self::tgroupCheck($importer["importer_uid"], $item))) {
2473 Logger::log("Contact ".$importer["id"]." is only follower and tgroup check was negative.", Logger::DEBUG);
2477 // This is my contact on another system, but it's really me.
2478 // Turn this into a wall post.
2479 $notify = Item::isRemoteSelf($importer, $item);
2481 $posted_id = Item::insert($item, $notify);
2484 $posted_id = $notify;
2487 Logger::log("Item was stored with id ".$posted_id, Logger::DEBUG);
2489 if ($item['uid'] == 0) {
2490 Item::distribute($posted_id);
2493 if (stristr($item["verb"], Activity::POKE)) {
2494 $item['id'] = $posted_id;
2495 self::doPoke($item, $importer);
2503 * @param object $xpath XPath object
2504 * @param object $deletion deletion elements
2505 * @param array $importer Record of the importer user mixed with contact of the content
2507 * @throws \Exception
2508 * @todo set proper type-hints
2510 private static function processDeletion($xpath, $deletion, $importer)
2512 Logger::log("Processing deletions");
2515 foreach ($deletion->attributes as $attributes) {
2516 if ($attributes->name == "ref") {
2517 $uri = $attributes->textContent;
2521 if (!$uri || !$importer["id"]) {
2525 $condition = ['uri' => $uri, 'uid' => $importer["importer_uid"]];
2526 $item = Post::selectFirst(['id', 'parent', 'contact-id', 'uri-id', 'deleted', 'gravity'], $condition);
2527 if (!DBA::isResult($item)) {
2528 Logger::log("Item with uri " . $uri . " for user " . $importer["importer_uid"] . " wasn't found.", Logger::DEBUG);
2532 if (DBA::exists('post-category', ['uri-id' => $item['uri-id'], 'uid' => $importer['importer_uid'], 'type' => Post\Category::FILE])) {
2533 Logger::notice("Item is filed. It won't be deleted.", ['uri' => $uri, 'uri-id' => $item['uri_id'], 'uid' => $importer["importer_uid"]]);
2537 // When it is a starting post it has to belong to the person that wants to delete it
2538 if (($item['gravity'] == GRAVITY_PARENT) && ($item['contact-id'] != $importer["id"])) {
2539 Logger::log("Item with uri " . $uri . " don't belong to contact " . $importer["id"] . " - ignoring deletion.", Logger::DEBUG);
2543 // Comments can be deleted by the thread owner or comment owner
2544 if (($item['gravity'] != GRAVITY_PARENT) && ($item['contact-id'] != $importer["id"])) {
2545 $condition = ['id' => $item['parent'], 'contact-id' => $importer["id"]];
2546 if (!Post::exists($condition)) {
2547 Logger::log("Item with uri " . $uri . " wasn't found or mustn't be deleted by contact " . $importer["id"] . " - ignoring deletion.", Logger::DEBUG);
2552 if ($item["deleted"]) {
2556 Logger::log('deleting item '.$item['id'].' uri='.$uri, Logger::DEBUG);
2558 Item::markForDeletion(['id' => $item['id']]);
2562 * Imports a DFRN message
2564 * @param string $xml The DFRN message
2565 * @param array $importer Record of the importer user mixed with contact of the content
2566 * @param int $protocol Transport protocol
2567 * @param int $direction Is the message pushed or pulled?
2568 * @return integer Import status
2569 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2570 * @throws \ImagickException
2571 * @todo set proper type-hints
2573 public static function import($xml, $importer, $protocol, $direction)
2579 $doc = new DOMDocument();
2580 @$doc->loadXML($xml);
2582 $xpath = new DOMXPath($doc);
2583 $xpath->registerNamespace("atom", ActivityNamespace::ATOM1);
2584 $xpath->registerNamespace("thr", ActivityNamespace::THREAD);
2585 $xpath->registerNamespace("at", ActivityNamespace::TOMB);
2586 $xpath->registerNamespace("media", ActivityNamespace::MEDIA);
2587 $xpath->registerNamespace("dfrn", ActivityNamespace::DFRN);
2588 $xpath->registerNamespace("activity", ActivityNamespace::ACTIVITY);
2589 $xpath->registerNamespace("georss", ActivityNamespace::GEORSS);
2590 $xpath->registerNamespace("poco", ActivityNamespace::POCO);
2591 $xpath->registerNamespace("ostatus", ActivityNamespace::OSTATUS);
2592 $xpath->registerNamespace("statusnet", ActivityNamespace::STATUSNET);
2595 $header["uid"] = $importer["importer_uid"];
2596 $header["network"] = Protocol::DFRN;
2597 $header["wall"] = 0;
2598 $header["origin"] = 0;
2599 $header["contact-id"] = $importer["id"];
2600 $header["direction"] = $direction;
2602 if ($direction === Conversation::RELAY) {
2603 $header['post-reason'] = Item::PR_RELAY;
2606 // Update the contact table if the data has changed
2608 // The "atom:author" is only present in feeds
2609 if ($xpath->query("/atom:feed/atom:author")->length > 0) {
2610 self::fetchauthor($xpath, $doc->firstChild, $importer, "atom:author", false, $xml);
2613 // Only the "dfrn:owner" in the head section contains all data
2614 if ($xpath->query("/atom:feed/dfrn:owner")->length > 0) {
2615 self::fetchauthor($xpath, $doc->firstChild, $importer, "dfrn:owner", false, $xml);
2618 Logger::log("Import DFRN message for user " . $importer["importer_uid"] . " from contact " . $importer["id"], Logger::DEBUG);
2620 if (!empty($importer['gsid'])) {
2621 if ($protocol == Conversation::PARCEL_DIASPORA_DFRN) {
2622 GServer::setProtocol($importer['gsid'], Post\DeliveryData::DFRN);
2623 } elseif ($protocol == Conversation::PARCEL_LEGACY_DFRN) {
2624 GServer::setProtocol($importer['gsid'], Post\DeliveryData::LEGACY_DFRN);
2628 // is it a public forum? Private forums aren't exposed with this method
2629 $forum = intval(XML::getFirstNodeValue($xpath, "/atom:feed/dfrn:community/text()"));
2631 // The account type is new since 3.5.1
2632 if ($xpath->query("/atom:feed/dfrn:account_type")->length > 0) {
2633 // Hint: We are using separate update calls for uid=0 and uid!=0 since a combined call is bad for the database performance
2635 $accounttype = intval(XML::getFirstNodeValue($xpath, "/atom:feed/dfrn:account_type/text()"));
2637 if ($accounttype != $importer["contact-type"]) {
2638 DBA::update('contact', ['contact-type' => $accounttype], ['id' => $importer['id']]);
2640 // Updating the public contact as well
2641 DBA::update('contact', ['contact-type' => $accounttype], ['uid' => 0, 'nurl' => $importer['nurl']]);
2643 // A forum contact can either have set "forum" or "prv" - but not both
2644 if ($accounttype == User::ACCOUNT_TYPE_COMMUNITY) {
2645 // It's a forum, so either set the public or private forum flag
2646 $condition = ['(`forum` != ? OR `prv` != ?) AND `id` = ?', $forum, !$forum, $importer['id']];
2647 DBA::update('contact', ['forum' => $forum, 'prv' => !$forum], $condition);
2649 // Updating the public contact as well
2650 $condition = ['(`forum` != ? OR `prv` != ?) AND `uid` = 0 AND `nurl` = ?', $forum, !$forum, $importer['nurl']];
2651 DBA::update('contact', ['forum' => $forum, 'prv' => !$forum], $condition);
2653 // It's not a forum, so remove the flags
2654 $condition = ['(`forum` OR `prv`) AND `id` = ?', $importer['id']];
2655 DBA::update('contact', ['forum' => false, 'prv' => false], $condition);
2657 // Updating the public contact as well
2658 $condition = ['(`forum` OR `prv`) AND `uid` = 0 AND `nurl` = ?', $importer['nurl']];
2659 DBA::update('contact', ['forum' => false, 'prv' => false], $condition);
2661 } elseif ($forum != $importer["forum"]) { // Deprecated since 3.5.1
2662 $condition = ['`forum` != ? AND `id` = ?', $forum, $importer["id"]];
2663 DBA::update('contact', ['forum' => $forum], $condition);
2665 // Updating the public contact as well
2666 $condition = ['`forum` != ? AND `uid` = 0 AND `nurl` = ?', $forum, $importer['nurl']];
2667 DBA::update('contact', ['forum' => $forum], $condition);
2671 // We are processing relocations even if we are ignoring a contact
2672 $relocations = $xpath->query("/atom:feed/dfrn:relocate");
2673 foreach ($relocations as $relocation) {
2674 self::processRelocation($xpath, $relocation, $importer);
2677 if (($importer["uid"] != 0) && !$importer["readonly"]) {
2678 $mails = $xpath->query("/atom:feed/dfrn:mail");
2679 foreach ($mails as $mail) {
2680 self::processMail($xpath, $mail, $importer);
2683 $suggestions = $xpath->query("/atom:feed/dfrn:suggest");
2684 foreach ($suggestions as $suggestion) {
2685 self::processSuggestion($xpath, $suggestion, $importer);
2689 $deletions = $xpath->query("/atom:feed/at:deleted-entry");
2690 if (!empty($deletions)) {
2691 foreach ($deletions as $deletion) {
2692 self::processDeletion($xpath, $deletion, $importer);
2694 if (count($deletions) > 0) {
2695 Logger::notice('Deletions had been processed');
2700 $entries = $xpath->query("/atom:feed/atom:entry");
2701 foreach ($entries as $entry) {
2702 self::processEntry($header, $xpath, $entry, $importer, $xml, $protocol);
2705 Logger::log("Import done for user " . $importer["importer_uid"] . " from contact " . $importer["id"], Logger::DEBUG);
2710 * Returns the activity verb
2712 * @param array $item Item array
2714 * @return string activity verb
2716 private static function constructVerb(array $item)
2718 if ($item['verb']) {
2719 return $item['verb'];
2721 return Activity::POST;
2724 private static function tgroupCheck($uid, $item)
2728 // check that the message originated elsewhere and is a top-level post
2730 if ($item['wall'] || $item['origin'] || ($item['uri'] != $item['thr-parent'])) {
2734 $user = DBA::selectFirst('user', ['page-flags', 'nickname'], ['uid' => $uid]);
2735 if (!DBA::isResult($user)) {
2739 $community_page = ($user['page-flags'] == User::PAGE_FLAGS_COMMUNITY);
2740 $prvgroup = ($user['page-flags'] == User::PAGE_FLAGS_PRVGROUP);
2742 $link = Strings::normaliseLink(DI::baseUrl() . '/profile/' . $user['nickname']);
2745 * Diaspora uses their own hardwired link URL in @-tags
2746 * instead of the one we supply with webfinger
2748 $dlink = Strings::normaliseLink(DI::baseUrl() . '/u/' . $user['nickname']);
2750 $cnt = preg_match_all('/[\@\!]\[url\=(.*?)\](.*?)\[\/url\]/ism', $item['body'], $matches, PREG_SET_ORDER);
2752 foreach ($matches as $mtch) {
2753 if (Strings::compareLink($link, $mtch[1]) || Strings::compareLink($dlink, $mtch[1])) {
2755 Logger::log('mention found: ' . $mtch[2]);
2764 return $community_page || $prvgroup;
2768 * This function returns true if $update has an edited timestamp newer
2769 * than $existing, i.e. $update contains new data which should override
2770 * what's already there. If there is no timestamp yet, the update is
2771 * assumed to be newer. If the update has no timestamp, the existing
2772 * item is assumed to be up-to-date. If the timestamps are equal it
2773 * assumes the update has been seen before and should be ignored.
2778 * @throws \Exception
2780 private static function isEditedTimestampNewer($existing, $update)
2782 if (empty($existing['edited'])) {
2785 if (empty($update['edited'])) {
2789 $existing_edited = DateTimeFormat::utc($existing['edited']);
2790 $update_edited = DateTimeFormat::utc($update['edited']);
2792 return (strcmp($existing_edited, $update_edited) < 0);
2796 * Checks if the given contact url does support DFRN
2798 * @param string $url profile url
2800 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2801 * @throws \ImagickException
2803 public static function isSupportedByContactUrl($url)
2805 $probe = Probe::uri($url, Protocol::DFRN);
2806 return $probe['network'] == Protocol::DFRN;