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
768 * @param int $uriid Uri-Id of the post
770 * @return \DOMElement XML activity object
771 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
772 * @todo Find proper type-hints
774 private static function createActivity(DOMDocument $doc, $element, $activity, $uriid)
777 $entry = $doc->createElement($element);
779 $r = XML::parseString($activity);
785 XML::addElement($doc, $entry, "activity:object-type", $r->type);
789 XML::addElement($doc, $entry, "id", $r->id);
793 XML::addElement($doc, $entry, "title", $r->title);
797 if (substr($r->link, 0, 1) == '<') {
798 if (strstr($r->link, '&') && (! strstr($r->link, '&'))) {
799 $r->link = str_replace('&', '&', $r->link);
802 $r->link = preg_replace('/\<link(.*?)\"\>/', '<link$1"/>', $r->link);
804 // XML does need a single element as root element so we add a dummy element here
805 $data = XML::parseString("<dummy>" . $r->link . "</dummy>");
806 if (is_object($data)) {
807 foreach ($data->link as $link) {
809 foreach ($link->attributes() as $parameter => $value) {
810 $attributes[$parameter] = $value;
812 XML::addElement($doc, $entry, "link", "", $attributes);
816 $attributes = ["rel" => "alternate", "type" => "text/html", "href" => $r->link];
817 XML::addElement($doc, $entry, "link", "", $attributes);
821 XML::addElement($doc, $entry, "content", BBCode::convertForUriId($uriid, $r->content, BBCode::EXTERNAL), ["type" => "html"]);
831 * Adds the elements for attachments
833 * @param object $doc XML document
834 * @param object $root XML root
835 * @param array $item Item element
837 * @return void XML attachment object
838 * @todo Find proper type-hints
840 private static function getAttachment($doc, $root, $item)
842 foreach (Post\Media::getByURIId($item['uri-id'], [Post\Media::DOCUMENT, Post\Media::TORRENT, Post\Media::UNKNOWN]) as $attachment) {
843 $attributes = ['rel' => 'enclosure',
844 'href' => $attachment['url'],
845 'type' => $attachment['mimetype']];
847 if (!empty($attachment['size'])) {
848 $attributes['length'] = intval($attachment['size']);
850 if (!empty($attachment['description'])) {
851 $attributes['title'] = $attachment['description'];
854 XML::addElement($doc, $root, 'link', '', $attributes);
859 * Adds the "entry" elements for the DFRN protocol
861 * @param DOMDocument $doc XML document
862 * @param string $type "text" or "html"
863 * @param array $item Item element
864 * @param array $owner Owner record
865 * @param bool $comment Trigger the sending of the "comment" element
866 * @param int $cid Contact ID of the recipient
867 * @param bool $single If set, the entry is created as an XML document with a single "entry" element
869 * @return null|\DOMElement XML entry object
870 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
871 * @throws \ImagickException
872 * @todo Find proper type-hints
874 private static function entry(DOMDocument $doc, $type, array $item, array $owner, $comment = false, $cid = 0, $single = false)
878 if (!$item['parent']) {
879 Logger::notice('Item without parent found.', ['type' => $type, 'item' => $item]);
883 if ($item['deleted']) {
884 $attributes = ["ref" => $item['uri'], "when" => DateTimeFormat::utc($item['edited'] . '+00:00', DateTimeFormat::ATOM)];
885 return XML::createElement($doc, "at:deleted-entry", "", $attributes);
889 $entry = $doc->createElement("entry");
891 $entry = $doc->createElementNS(ActivityNamespace::ATOM1, 'entry');
892 $doc->appendChild($entry);
894 $entry->setAttribute("xmlns:thr", ActivityNamespace::THREAD);
895 $entry->setAttribute("xmlns:at", ActivityNamespace::TOMB);
896 $entry->setAttribute("xmlns:media", ActivityNamespace::MEDIA);
897 $entry->setAttribute("xmlns:dfrn", ActivityNamespace::DFRN);
898 $entry->setAttribute("xmlns:activity", ActivityNamespace::ACTIVITY);
899 $entry->setAttribute("xmlns:georss", ActivityNamespace::GEORSS);
900 $entry->setAttribute("xmlns:poco", ActivityNamespace::POCO);
901 $entry->setAttribute("xmlns:ostatus", ActivityNamespace::OSTATUS);
902 $entry->setAttribute("xmlns:statusnet", ActivityNamespace::STATUSNET);
905 $body = Post\Media::addAttachmentsToBody($item['uri-id'], $item['body'] ?? '');
907 if ($item['private'] == Item::PRIVATE) {
908 $body = Item::fixPrivatePhotos($body, $owner['uid'], $item, $cid);
911 // Remove the abstract element. It is only locally important.
912 $body = BBCode::stripAbstract($body);
915 if ($type == 'html') {
918 if ($item['title'] != "") {
919 $htmlbody = "[b]" . $item['title'] . "[/b]\n\n" . $htmlbody;
922 $htmlbody = BBCode::convertForUriId($item['uri-id'], $htmlbody, BBCode::ACTIVITYPUB);
925 $author = self::addEntryAuthor($doc, "author", $item["author-link"], $item);
926 $entry->appendChild($author);
928 $dfrnowner = self::addEntryAuthor($doc, "dfrn:owner", $item["owner-link"], $item);
929 $entry->appendChild($dfrnowner);
931 if ($item['gravity'] != GRAVITY_PARENT) {
932 $parent = Post::selectFirst(['guid', 'plink'], ['uri' => $item['thr-parent'], 'uid' => $item['uid']]);
933 if (DBA::isResult($parent)) {
934 $attributes = ["ref" => $item['thr-parent'], "type" => "text/html",
935 "href" => $parent['plink'],
936 "dfrn:diaspora_guid" => $parent['guid']];
937 XML::addElement($doc, $entry, "thr:in-reply-to", "", $attributes);
941 // Add conversation data. This is used for OStatus
942 $conversation_href = DI::baseUrl()."/display/".$item["parent-guid"];
943 $conversation_uri = $conversation_href;
945 if (isset($parent_item)) {
946 $conversation = DBA::selectFirst('conversation', ['conversation-uri', 'conversation-href'], ['item-uri' => $item['thr-parent']]);
947 if (DBA::isResult($conversation)) {
948 if ($conversation['conversation-uri'] != '') {
949 $conversation_uri = $conversation['conversation-uri'];
951 if ($conversation['conversation-href'] != '') {
952 $conversation_href = $conversation['conversation-href'];
958 "href" => $conversation_href,
959 "ref" => $conversation_uri];
961 XML::addElement($doc, $entry, "ostatus:conversation", $conversation_uri, $attributes);
963 XML::addElement($doc, $entry, "id", $item["uri"]);
964 XML::addElement($doc, $entry, "title", $item["title"]);
966 XML::addElement($doc, $entry, "published", DateTimeFormat::utc($item["created"] . "+00:00", DateTimeFormat::ATOM));
967 XML::addElement($doc, $entry, "updated", DateTimeFormat::utc($item["edited"] . "+00:00", DateTimeFormat::ATOM));
969 // "dfrn:env" is used to read the content
970 XML::addElement($doc, $entry, "dfrn:env", Strings::base64UrlEncode($body, true));
972 // The "content" field is not read by the receiver. We could remove it when the type is "text"
973 // We keep it at the moment, maybe there is some old version that doesn't read "dfrn:env"
974 XML::addElement($doc, $entry, "content", (($type == 'html') ? $htmlbody : $body), ["type" => $type]);
976 // We save this value in "plink". Maybe we should read it from there as well?
982 ["rel" => "alternate", "type" => "text/html",
983 "href" => DI::baseUrl() . "/display/" . $item["guid"]]
986 // "comment-allow" is some old fashioned stuff for old Friendica versions.
987 // It is included in the rewritten code for completeness
989 XML::addElement($doc, $entry, "dfrn:comment-allow", 1);
992 if ($item['location']) {
993 XML::addElement($doc, $entry, "dfrn:location", $item['location']);
996 if ($item['coord']) {
997 XML::addElement($doc, $entry, "georss:point", $item['coord']);
1000 if ($item['private']) {
1001 // Friendica versions prior to 2020.3 can't handle "unlisted" properly. So we can only transmit public and private
1002 XML::addElement($doc, $entry, "dfrn:private", ($item['private'] == Item::PRIVATE ? Item::PRIVATE : Item::PUBLIC));
1003 XML::addElement($doc, $entry, "dfrn:unlisted", $item['private'] == Item::UNLISTED);
1006 if ($item['extid']) {
1007 XML::addElement($doc, $entry, "dfrn:extid", $item['extid']);
1010 if ($item['post-type'] == Item::PT_PAGE) {
1011 XML::addElement($doc, $entry, "dfrn:bookmark", "true");
1015 XML::addElement($doc, $entry, "statusnet:notice_info", "", ["local_id" => $item['id'], "source" => $item['app']]);
1018 XML::addElement($doc, $entry, "dfrn:diaspora_guid", $item["guid"]);
1020 // The signed text contains the content in Markdown, the sender handle and the signatur for the content
1021 // It is needed for relayed comments to Diaspora.
1022 if ($item['signed_text']) {
1023 $sign = base64_encode(json_encode(['signed_text' => $item['signed_text'],'signature' => '','signer' => '']));
1024 XML::addElement($doc, $entry, "dfrn:diaspora_signature", $sign);
1027 XML::addElement($doc, $entry, "activity:verb", self::constructVerb($item));
1029 if ($item['object-type'] != "") {
1030 XML::addElement($doc, $entry, "activity:object-type", $item['object-type']);
1031 } elseif ($item['gravity'] == GRAVITY_PARENT) {
1032 XML::addElement($doc, $entry, "activity:object-type", Activity\ObjectType::NOTE);
1034 XML::addElement($doc, $entry, "activity:object-type", Activity\ObjectType::COMMENT);
1037 $actobj = self::createActivity($doc, "activity:object", $item['object'], $item['uri-id']);
1039 $entry->appendChild($actobj);
1042 $actarg = self::createActivity($doc, "activity:target", $item['target'], $item['uri-id']);
1044 $entry->appendChild($actarg);
1047 $tags = Tag::getByURIId($item['uri-id']);
1050 foreach ($tags as $tag) {
1051 if (($type != 'html') || ($tag['type'] == Tag::HASHTAG)) {
1052 XML::addElement($doc, $entry, "category", "", ["scheme" => "X-DFRN:" . Tag::TAG_CHARACTER[$tag['type']] . ":" . $tag['url'], "term" => $tag['name']]);
1054 if ($tag['type'] != Tag::HASHTAG) {
1055 $mentioned[$tag['url']] = $tag['url'];
1060 foreach ($mentioned as $mention) {
1061 $condition = ['uid' => $owner["uid"], 'nurl' => Strings::normaliseLink($mention)];
1062 $contact = DBA::selectFirst('contact', ['forum', 'prv'], $condition);
1064 if (DBA::isResult($contact) && ($contact["forum"] || $contact["prv"])) {
1070 ["rel" => "mentioned",
1071 "ostatus:object-type" => Activity\ObjectType::GROUP,
1080 ["rel" => "mentioned",
1081 "ostatus:object-type" => Activity\ObjectType::PERSON,
1087 self::getAttachment($doc, $entry, $item);
1093 * encrypts data via AES
1095 * @param string $data The data that is to be encrypted
1096 * @param string $key The AES key
1098 * @return string encrypted data
1100 private static function aesEncrypt($data, $key)
1102 return openssl_encrypt($data, 'aes-128-ecb', $key, OPENSSL_RAW_DATA);
1106 * decrypts data via AES
1108 * @param string $encrypted The encrypted data
1109 * @param string $key The AES key
1111 * @return string decrypted data
1113 public static function aesDecrypt($encrypted, $key)
1115 return openssl_decrypt($encrypted, 'aes-128-ecb', $key, OPENSSL_RAW_DATA);
1119 * Delivers the atom content to the contacts
1121 * @param array $owner Owner record
1122 * @param array $contact Contact record of the receiver
1123 * @param string $atom Content that will be transmitted
1124 * @param bool $dissolve (to be documented)
1126 * @return int Deliver status. Negative values mean an error.
1127 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1128 * @throws \ImagickException
1129 * @todo Add array type-hint for $owner, $contact
1131 public static function deliver($owner, $contact, $atom, $dissolve = false)
1133 $idtosend = $orig_id = (($contact['dfrn-id']) ? $contact['dfrn-id'] : $contact['issued-id']);
1135 if ($contact['duplex'] && $contact['dfrn-id']) {
1136 $idtosend = '0:' . $orig_id;
1138 if ($contact['duplex'] && $contact['issued-id']) {
1139 $idtosend = '1:' . $orig_id;
1142 $rino = DI::config()->get('system', 'rino_encrypt');
1143 $rino = intval($rino);
1145 Logger::log("Local rino version: ". $rino, Logger::DEBUG);
1147 $ssl_val = intval(DI::config()->get('system', 'ssl_policy'));
1150 case BaseURL::SSL_POLICY_FULL:
1151 $ssl_policy = 'full';
1153 case BaseURL::SSL_POLICY_SELFSIGN:
1154 $ssl_policy = 'self';
1156 case BaseURL::SSL_POLICY_NONE:
1158 $ssl_policy = 'none';
1162 $url = $contact['notify'] . '&dfrn_id=' . $idtosend . '&dfrn_version=' . DFRN_PROTOCOL_VERSION . (($rino) ? '&rino='.$rino : '');
1164 Logger::log('dfrn_deliver: ' . $url);
1166 $curlResult = DI::httpRequest()->get($url);
1168 if ($curlResult->isTimeout()) {
1169 return -2; // timed out
1172 $xml = $curlResult->getBody();
1174 $curl_stat = $curlResult->getReturnCode();
1175 if (empty($curl_stat)) {
1176 return -3; // timed out
1179 Logger::log('dfrn_deliver: ' . $xml, Logger::DATA);
1185 if (strpos($xml, '<?xml') === false) {
1186 Logger::log('dfrn_deliver: no valid XML returned');
1187 Logger::log('dfrn_deliver: returned XML: ' . $xml, Logger::DATA);
1191 $res = XML::parseString($xml);
1193 if (!is_object($res) || (intval($res->status) != 0) || !strlen($res->challenge) || !strlen($res->dfrn_id)) {
1194 if (empty($res->status)) {
1197 $status = $res->status;
1204 $sent_dfrn_id = hex2bin((string) $res->dfrn_id);
1205 $challenge = hex2bin((string) $res->challenge);
1206 $perm = (($res->perm) ? $res->perm : null);
1207 $dfrn_version = floatval($res->dfrn_version ?: 2.0);
1208 $rino_remote_version = intval($res->rino);
1209 $page = (($owner['page-flags'] == User::PAGE_FLAGS_COMMUNITY) ? 1 : 0);
1211 Logger::log("Remote rino version: ".$rino_remote_version." for ".$contact["url"], Logger::DEBUG);
1213 if ($owner['page-flags'] == User::PAGE_FLAGS_PRVGROUP) {
1217 $final_dfrn_id = '';
1220 if ((($perm == 'rw') && !intval($contact['writable']))
1221 || (($perm == 'r') && intval($contact['writable']))
1223 DBA::update('contact', ['writable' => ($perm == 'rw')], ['id' => $contact['id']]);
1225 $contact['writable'] = (string) 1 - intval($contact['writable']);
1229 if (($contact['duplex'] && strlen($contact['pubkey']))
1230 || ($owner['page-flags'] == User::PAGE_FLAGS_COMMUNITY && strlen($contact['pubkey']))
1231 || ($contact['rel'] == Contact::SHARING && strlen($contact['pubkey']))
1233 openssl_public_decrypt($sent_dfrn_id, $final_dfrn_id, $contact['pubkey']);
1234 openssl_public_decrypt($challenge, $postvars['challenge'], $contact['pubkey']);
1236 openssl_private_decrypt($sent_dfrn_id, $final_dfrn_id, $contact['prvkey']);
1237 openssl_private_decrypt($challenge, $postvars['challenge'], $contact['prvkey']);
1240 $final_dfrn_id = substr($final_dfrn_id, 0, strpos($final_dfrn_id, '.'));
1242 if (strpos($final_dfrn_id, ':') == 1) {
1243 $final_dfrn_id = substr($final_dfrn_id, 2);
1246 if ($final_dfrn_id != $orig_id) {
1247 Logger::log('dfrn_deliver: wrong dfrn_id.');
1248 // did not decode properly - cannot trust this site
1252 $postvars['dfrn_id'] = $idtosend;
1253 $postvars['dfrn_version'] = DFRN_PROTOCOL_VERSION;
1255 $postvars['dissolve'] = '1';
1258 if ((($contact['rel']) && ($contact['rel'] != Contact::SHARING) && (! $contact['blocked'])) || ($owner['page-flags'] == User::PAGE_FLAGS_COMMUNITY)) {
1259 $postvars['data'] = $atom;
1260 $postvars['perm'] = 'rw';
1262 $postvars['data'] = str_replace('<dfrn:comment-allow>1', '<dfrn:comment-allow>0', $atom);
1263 $postvars['perm'] = 'r';
1266 $postvars['ssl_policy'] = $ssl_policy;
1269 $postvars['page'] = $page;
1273 if ($rino > 0 && $rino_remote_version > 0 && (! $dissolve)) {
1274 Logger::log('rino version: '. $rino_remote_version);
1276 switch ($rino_remote_version) {
1278 $key = random_bytes(16);
1279 $data = self::aesEncrypt($postvars['data'], $key);
1283 Logger::log("rino: invalid requested version '$rino_remote_version'");
1287 $postvars['rino'] = $rino_remote_version;
1288 $postvars['data'] = bin2hex($data);
1290 if ($dfrn_version >= 2.1) {
1291 if (($contact['duplex'] && strlen($contact['pubkey']))
1292 || ($owner['page-flags'] == User::PAGE_FLAGS_COMMUNITY && strlen($contact['pubkey']))
1293 || ($contact['rel'] == Contact::SHARING && strlen($contact['pubkey']))
1295 openssl_public_encrypt($key, $postvars['key'], $contact['pubkey']);
1297 openssl_private_encrypt($key, $postvars['key'], $contact['prvkey']);
1300 if (($contact['duplex'] && strlen($contact['prvkey'])) || ($owner['page-flags'] == User::PAGE_FLAGS_COMMUNITY)) {
1301 openssl_private_encrypt($key, $postvars['key'], $contact['prvkey']);
1303 openssl_public_encrypt($key, $postvars['key'], $contact['pubkey']);
1307 Logger::log('md5 rawkey ' . md5($postvars['key']));
1309 $postvars['key'] = bin2hex($postvars['key']);
1313 Logger::debug('dfrn_deliver', ['post' => $postvars]);
1315 $postResult = DI::httpRequest()->post($contact['notify'], $postvars);
1317 $xml = $postResult->getBody();
1319 Logger::log('dfrn_deliver: ' . "RECEIVED: " . $xml, Logger::DATA);
1321 $curl_stat = $postResult->getReturnCode();
1322 if (empty($curl_stat) || empty($xml)) {
1323 return -9; // timed out
1326 if (($curl_stat == 503) && stristr($postResult->getHeader(), 'retry-after')) {
1330 if (strpos($xml, '<?xml') === false) {
1331 Logger::log('dfrn_deliver: phase 2: no valid XML returned');
1332 Logger::log('dfrn_deliver: phase 2: returned XML: ' . $xml, Logger::DATA);
1336 $res = XML::parseString($xml);
1338 if (!isset($res->status)) {
1342 // Possibly old servers had returned an empty value when everything was okay
1343 if (empty($res->status)) {
1347 if (!empty($res->message)) {
1348 Logger::log('Delivery returned status '.$res->status.' - '.$res->message, Logger::DEBUG);
1351 return intval($res->status);
1355 * Transmits atom content to the contacts via the Diaspora transport layer
1357 * @param array $owner Owner record
1358 * @param array $contact Contact record of the receiver
1359 * @param string $atom Content that will be transmitted
1361 * @param bool $public_batch
1362 * @return int Deliver status. Negative values mean an error.
1363 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1364 * @throws \ImagickException
1366 public static function transmit($owner, $contact, $atom, $public_batch = false)
1368 if (!$public_batch) {
1369 if (empty($contact['addr'])) {
1370 Logger::log('Empty contact handle for ' . $contact['id'] . ' - ' . $contact['url'] . ' - trying to update it.');
1371 if (Contact::updateFromProbe($contact['id'])) {
1372 $new_contact = DBA::selectFirst('contact', ['addr'], ['id' => $contact['id']]);
1373 $contact['addr'] = $new_contact['addr'];
1376 if (empty($contact['addr'])) {
1377 Logger::log('Unable to find contact handle for ' . $contact['id'] . ' - ' . $contact['url']);
1382 $fcontact = FContact::getByURL($contact['addr']);
1383 if (empty($fcontact)) {
1384 Logger::log('Unable to find contact details for ' . $contact['id'] . ' - ' . $contact['addr']);
1387 $pubkey = $fcontact['pubkey'];
1392 $envelope = Diaspora::buildMessage($atom, $owner, $contact, $owner['uprvkey'], $pubkey, $public_batch);
1394 // Create the endpoint for public posts. This is some WIP and should later be added to the probing
1395 if ($public_batch && empty($contact["batch"])) {
1396 $parts = parse_url($contact["notify"]);
1397 $path_parts = explode('/', $parts['path']);
1398 array_pop($path_parts);
1399 $parts['path'] = implode('/', $path_parts);
1400 $contact["batch"] = Network::unparseURL($parts);
1403 $dest_url = ($public_batch ? $contact["batch"] : $contact["notify"]);
1405 if (empty($dest_url)) {
1406 Logger::info('Empty destination', ['public' => $public_batch, 'contact' => $contact]);
1410 $content_type = ($public_batch ? "application/magic-envelope+xml" : "application/json");
1412 $postResult = DI::httpRequest()->post($dest_url, $envelope, ["Content-Type: " . $content_type]);
1413 $xml = $postResult->getBody();
1415 $curl_stat = $postResult->getReturnCode();
1416 if (empty($curl_stat) || empty($xml)) {
1417 Logger::log('Empty answer from ' . $contact['id'] . ' - ' . $dest_url);
1418 return -9; // timed out
1421 if (($curl_stat == 503) && (stristr($postResult->getHeader(), 'retry-after'))) {
1425 if (strpos($xml, '<?xml') === false) {
1426 Logger::log('No valid XML returned from ' . $contact['id'] . ' - ' . $dest_url);
1427 Logger::log('Returned XML: ' . $xml, Logger::DATA);
1431 $res = XML::parseString($xml);
1433 if (empty($res->status)) {
1437 if (!empty($res->message)) {
1438 Logger::log('Transmit to ' . $dest_url . ' returned status '.$res->status.' - '.$res->message, Logger::DEBUG);
1441 return intval($res->status);
1445 * Fetch the author data from head or entry items
1447 * @param \DOMXPath $xpath XPath object
1448 * @param \DOMNode $context In which context should the data be searched
1449 * @param array $importer Record of the importer user mixed with contact of the content
1450 * @param string $element Element name from which the data is fetched
1451 * @param bool $onlyfetch Should the data only be fetched or should it update the contact record as well
1452 * @param string $xml optional, default empty
1454 * @return array Relevant data of the author
1455 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1456 * @throws \ImagickException
1457 * @todo Find good type-hints for all parameter
1459 private static function fetchauthor(\DOMXPath $xpath, \DOMNode $context, $importer, $element, $onlyfetch, $xml = "")
1462 $author["name"] = XML::getFirstNodeValue($xpath, $element."/atom:name/text()", $context);
1463 $author["link"] = XML::getFirstNodeValue($xpath, $element."/atom:uri/text()", $context);
1465 $fields = ['id', 'uid', 'url', 'network', 'avatar-date', 'avatar', 'name-date', 'uri-date', 'addr',
1466 'name', 'nick', 'about', 'location', 'keywords', 'xmpp', 'bdyear', 'bd', 'hidden', 'contact-type'];
1467 $condition = ["`uid` = ? AND `nurl` = ? AND `network` != ? AND NOT `pending` AND NOT `blocked`",
1468 $importer["importer_uid"], Strings::normaliseLink($author["link"]), Protocol::STATUSNET];
1470 if ($importer['account-type'] != User::ACCOUNT_TYPE_COMMUNITY) {
1471 $condition = DBA::mergeConditions($condition, ['rel' => [Contact::SHARING, Contact::FRIEND]]);
1474 $contact_old = DBA::selectFirst('contact', $fields, $condition);
1476 if (DBA::isResult($contact_old)) {
1477 $author["contact-id"] = $contact_old["id"];
1478 $author["network"] = $contact_old["network"];
1480 Logger::info('Contact not found', ['condition' => $condition]);
1482 $author["contact-unknown"] = true;
1483 $contact = Contact::getByURL($author["link"], null, ["id", "network"]);
1484 $author["contact-id"] = $contact["id"] ?? $importer["id"];
1485 $author["network"] = $contact["network"] ?? $importer["network"];
1489 // Until now we aren't serving different sizes - but maybe later
1491 /// @todo check if "avatar" or "photo" would be the best field in the specification
1492 $avatars = $xpath->query($element . "/atom:link[@rel='avatar']", $context);
1493 foreach ($avatars as $avatar) {
1496 foreach ($avatar->attributes as $attributes) {
1497 /// @TODO Rewrite these similar if() to one switch
1498 if ($attributes->name == "href") {
1499 $href = $attributes->textContent;
1501 if ($attributes->name == "width") {
1502 $width = $attributes->textContent;
1504 if ($attributes->name == "updated") {
1505 $author["avatar-date"] = $attributes->textContent;
1508 if (($width > 0) && ($href != "")) {
1509 $avatarlist[$width] = $href;
1513 if (count($avatarlist) > 0) {
1514 krsort($avatarlist);
1515 $author["avatar"] = current($avatarlist);
1518 if (empty($author['avatar']) && !empty($author['link'])) {
1519 $cid = Contact::getIdForURL($author['link'], 0);
1521 $contact = DBA::selectFirst('contact', ['avatar'], ['id' => $cid]);
1522 if (DBA::isResult($contact)) {
1523 $author['avatar'] = $contact['avatar'];
1528 if (empty($author['avatar'])) {
1529 Logger::log('Empty author: ' . $xml);
1530 $author['avatar'] = '';
1533 if (DBA::isResult($contact_old) && !$onlyfetch) {
1534 Logger::log("Check if contact details for contact " . $contact_old["id"] . " (" . $contact_old["nick"] . ") have to be updated.", Logger::DEBUG);
1536 $poco = ["url" => $contact_old["url"], "network" => $contact_old["network"]];
1538 // When was the last change to name or uri?
1539 $name_element = $xpath->query($element . "/atom:name", $context)->item(0);
1540 foreach ($name_element->attributes as $attributes) {
1541 if ($attributes->name == "updated") {
1542 $poco["name-date"] = $attributes->textContent;
1546 $link_element = $xpath->query($element . "/atom:link", $context)->item(0);
1547 foreach ($link_element->attributes as $attributes) {
1548 if ($attributes->name == "updated") {
1549 $poco["uri-date"] = $attributes->textContent;
1553 // Update contact data
1554 $value = XML::getFirstNodeValue($xpath, $element . "/dfrn:handle/text()", $context);
1556 $poco["addr"] = $value;
1559 $value = XML::getFirstNodeValue($xpath, $element . "/poco:displayName/text()", $context);
1561 $poco["name"] = $value;
1564 $value = XML::getFirstNodeValue($xpath, $element . "/poco:preferredUsername/text()", $context);
1566 $poco["nick"] = $value;
1569 $value = XML::getFirstNodeValue($xpath, $element . "/poco:note/text()", $context);
1571 $poco["about"] = $value;
1574 $value = XML::getFirstNodeValue($xpath, $element . "/poco:address/poco:formatted/text()", $context);
1576 $poco["location"] = $value;
1579 /// @todo Only search for elements with "poco:type" = "xmpp"
1580 $value = XML::getFirstNodeValue($xpath, $element . "/poco:ims/poco:value/text()", $context);
1582 $poco["xmpp"] = $value;
1585 /// @todo Add support for the following fields that we don't support by now in the contact table:
1586 /// - poco:utcOffset
1592 // If the "hide" element is present then the profile isn't searchable.
1593 $hide = intval(XML::getFirstNodeValue($xpath, $element . "/dfrn:hide/text()", $context) == "true");
1595 Logger::log("Hidden status for contact " . $contact_old["url"] . ": " . $hide, Logger::DEBUG);
1597 // If the contact isn't searchable then set the contact to "hidden".
1598 // Problem: This can be manually overridden by the user.
1600 $contact_old["hidden"] = true;
1603 // Save the keywords into the contact table
1605 $tagelements = $xpath->evaluate($element . "/poco:tags/text()", $context);
1606 foreach ($tagelements as $tag) {
1607 $tags[$tag->nodeValue] = $tag->nodeValue;
1611 $poco["keywords"] = implode(", ", $tags);
1614 // "dfrn:birthday" contains the birthday converted to UTC
1615 $birthday = XML::getFirstNodeValue($xpath, $element . "/dfrn:birthday/text()", $context);
1617 $birthday_date = new \DateTime($birthday);
1618 if ($birthday_date > new \DateTime()) {
1619 $poco["bdyear"] = $birthday_date->format("Y");
1621 } catch (\Exception $e) {
1625 // "poco:birthday" is the birthday in the format "yyyy-mm-dd"
1626 $value = XML::getFirstNodeValue($xpath, $element . "/poco:birthday/text()", $context);
1628 if (!in_array($value, ["", "0000-00-00", DBA::NULL_DATE])) {
1629 $bdyear = date("Y");
1630 $value = str_replace(["0000", "0001"], $bdyear, $value);
1632 if (strtotime($value) < time()) {
1633 $value = str_replace($bdyear, $bdyear + 1, $value);
1636 $poco["bd"] = $value;
1639 $contact = array_merge($contact_old, $poco);
1641 if ($contact_old["bdyear"] != $contact["bdyear"]) {
1642 Event::createBirthday($contact, $birthday);
1645 $fields = ['name' => $contact['name'], 'nick' => $contact['nick'], 'about' => $contact['about'],
1646 'location' => $contact['location'], 'addr' => $contact['addr'], 'keywords' => $contact['keywords'],
1647 'bdyear' => $contact['bdyear'], 'bd' => $contact['bd'], 'hidden' => $contact['hidden'],
1648 'xmpp' => $contact['xmpp'], 'name-date' => DateTimeFormat::utc($contact['name-date']),
1649 'unsearchable' => $contact['hidden'], 'uri-date' => DateTimeFormat::utc($contact['uri-date'])];
1651 DBA::update('contact', $fields, ['id' => $contact['id'], 'network' => $contact['network']], $contact_old);
1653 // Update the public contact. Don't set the "hidden" value, this is used differently for public contacts
1654 unset($fields['hidden']);
1655 $condition = ['uid' => 0, 'nurl' => Strings::normaliseLink($contact_old['url'])];
1656 DBA::update('contact', $fields, $condition, true);
1658 Contact::updateAvatar($contact['id'], $author['avatar']);
1660 $pcid = Contact::getIdForURL($contact_old['url']);
1661 if (!empty($pcid)) {
1662 Contact::updateAvatar($pcid, $author['avatar']);
1670 * Transforms activity objects into an XML string
1672 * @param object $xpath XPath object
1673 * @param object $activity Activity object
1674 * @param string $element element name
1676 * @return string XML string
1677 * @todo Find good type-hints for all parameter
1679 private static function transformActivity($xpath, $activity, $element)
1681 if (!is_object($activity)) {
1685 $obj_doc = new DOMDocument("1.0", "utf-8");
1686 $obj_doc->formatOutput = true;
1688 $obj_element = $obj_doc->createElementNS( ActivityNamespace::ATOM1, $element);
1690 $activity_type = $xpath->query("activity:object-type/text()", $activity)->item(0)->nodeValue;
1691 XML::addElement($obj_doc, $obj_element, "type", $activity_type);
1693 $id = $xpath->query("atom:id", $activity)->item(0);
1694 if (is_object($id)) {
1695 $obj_element->appendChild($obj_doc->importNode($id, true));
1698 $title = $xpath->query("atom:title", $activity)->item(0);
1699 if (is_object($title)) {
1700 $obj_element->appendChild($obj_doc->importNode($title, true));
1703 $links = $xpath->query("atom:link", $activity);
1704 if (is_object($links)) {
1705 foreach ($links as $link) {
1706 $obj_element->appendChild($obj_doc->importNode($link, true));
1710 $content = $xpath->query("atom:content", $activity)->item(0);
1711 if (is_object($content)) {
1712 $obj_element->appendChild($obj_doc->importNode($content, true));
1715 $obj_doc->appendChild($obj_element);
1717 $objxml = $obj_doc->saveXML($obj_element);
1719 /// @todo This isn't totally clean. We should find a way to transform the namespaces
1720 $objxml = str_replace("<".$element.' xmlns="http://www.w3.org/2005/Atom">', "<".$element.">", $objxml);
1725 * Processes the mail elements
1727 * @param object $xpath XPath object
1728 * @param object $mail mail elements
1729 * @param array $importer Record of the importer user mixed with contact of the content
1731 * @throws \Exception
1732 * @todo Find good type-hints for all parameter
1734 private static function processMail($xpath, $mail, $importer)
1736 Logger::log("Processing mails");
1739 $msg["uid"] = $importer["importer_uid"];
1740 $msg["from-name"] = XML::getFirstValue($xpath, "dfrn:sender/dfrn:name/text()", $mail);
1741 $msg["from-url"] = XML::getFirstValue($xpath, "dfrn:sender/dfrn:uri/text()", $mail);
1742 $msg["from-photo"] = XML::getFirstValue($xpath, "dfrn:sender/dfrn:avatar/text()", $mail);
1743 $msg["contact-id"] = $importer["id"];
1744 $msg["uri"] = XML::getFirstValue($xpath, "dfrn:id/text()", $mail);
1745 $msg["parent-uri"] = XML::getFirstValue($xpath, "dfrn:in-reply-to/text()", $mail);
1746 $msg["created"] = DateTimeFormat::utc(XML::getFirstValue($xpath, "dfrn:sentdate/text()", $mail));
1747 $msg["title"] = XML::getFirstValue($xpath, "dfrn:subject/text()", $mail);
1748 $msg["body"] = XML::getFirstValue($xpath, "dfrn:content/text()", $mail);
1754 * Processes the suggestion elements
1756 * @param object $xpath XPath object
1757 * @param object $suggestion suggestion elements
1758 * @param array $importer Record of the importer user mixed with contact of the content
1760 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1761 * @todo Find good type-hints for all parameter
1763 private static function processSuggestion($xpath, $suggestion, $importer)
1765 Logger::notice('Processing suggestions');
1767 $url = $xpath->evaluate('string(dfrn:url[1]/text())', $suggestion);
1768 $cid = Contact::getIdForURL($url);
1769 $note = $xpath->evaluate('string(dfrn:note[1]/text())', $suggestion);
1771 return FContact::addSuggestion($importer['importer_uid'], $cid, $importer['id'], $note);
1775 * Processes the relocation elements
1777 * @param object $xpath XPath object
1778 * @param object $relocation relocation elements
1779 * @param array $importer Record of the importer user mixed with contact of the content
1781 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1782 * @throws \ImagickException
1783 * @todo Find good type-hints for all parameter
1785 private static function processRelocation($xpath, $relocation, $importer)
1787 Logger::log("Processing relocations");
1789 /// @TODO Rewrite this to one statement
1791 $relocate["uid"] = $importer["importer_uid"];
1792 $relocate["cid"] = $importer["id"];
1793 $relocate["url"] = $xpath->query("dfrn:url/text()", $relocation)->item(0)->nodeValue;
1794 $relocate["addr"] = $xpath->query("dfrn:addr/text()", $relocation)->item(0)->nodeValue;
1795 $relocate["name"] = $xpath->query("dfrn:name/text()", $relocation)->item(0)->nodeValue;
1796 $relocate["avatar"] = $xpath->query("dfrn:avatar/text()", $relocation)->item(0)->nodeValue;
1797 $relocate["photo"] = $xpath->query("dfrn:photo/text()", $relocation)->item(0)->nodeValue;
1798 $relocate["thumb"] = $xpath->query("dfrn:thumb/text()", $relocation)->item(0)->nodeValue;
1799 $relocate["micro"] = $xpath->query("dfrn:micro/text()", $relocation)->item(0)->nodeValue;
1800 $relocate["request"] = $xpath->query("dfrn:request/text()", $relocation)->item(0)->nodeValue;
1801 $relocate["confirm"] = $xpath->query("dfrn:confirm/text()", $relocation)->item(0)->nodeValue;
1802 $relocate["notify"] = $xpath->query("dfrn:notify/text()", $relocation)->item(0)->nodeValue;
1803 $relocate["poll"] = $xpath->query("dfrn:poll/text()", $relocation)->item(0)->nodeValue;
1804 $relocate["sitepubkey"] = $xpath->query("dfrn:sitepubkey/text()", $relocation)->item(0)->nodeValue;
1806 if (($relocate["avatar"] == "") && ($relocate["photo"] != "")) {
1807 $relocate["avatar"] = $relocate["photo"];
1810 if ($relocate["addr"] == "") {
1811 $relocate["addr"] = preg_replace("=(https?://)(.*)/profile/(.*)=ism", "$3@$2", $relocate["url"]);
1816 "SELECT `photo`, `url` FROM `contact` WHERE `id` = %d AND `uid` = %d",
1817 intval($importer["id"]),
1818 intval($importer["importer_uid"])
1821 if (!DBA::isResult($r)) {
1822 Logger::log("Query failed to execute, no result returned in " . __FUNCTION__);
1828 // Update the contact table. We try to find every entry.
1829 $fields = ['name' => $relocate["name"], 'avatar' => $relocate["avatar"],
1830 'url' => $relocate["url"], 'nurl' => Strings::normaliseLink($relocate["url"]),
1831 'addr' => $relocate["addr"], 'request' => $relocate["request"],
1832 'confirm' => $relocate["confirm"], 'notify' => $relocate["notify"],
1833 'poll' => $relocate["poll"], 'site-pubkey' => $relocate["sitepubkey"]];
1834 $condition = ["(`id` = ?) OR (`nurl` = ?)", $importer["id"], Strings::normaliseLink($old["url"])];
1836 DBA::update('contact', $fields, $condition);
1838 Contact::updateAvatar($importer["id"], $relocate["avatar"], true);
1840 Logger::log('Contacts are updated.');
1843 /// merge with current record, current contents have priority
1844 /// update record, set url-updated
1845 /// update profile photos
1846 /// schedule a scan?
1853 * @param array $current the current item record
1854 * @param array $item the new item record
1855 * @param array $importer Record of the importer user mixed with contact of the content
1856 * @param int $entrytype Is it a toplevel entry, a comment or a relayed comment?
1858 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1859 * @todo set proper type-hints (array?)
1861 private static function updateContent($current, $item, $importer, $entrytype)
1865 if (self::isEditedTimestampNewer($current, $item)) {
1866 // do not accept (ignore) an earlier edit than one we currently have.
1867 if (DateTimeFormat::utc($item["edited"]) < $current["edited"]) {
1871 $fields = ['title' => $item['title'] ?? '', 'body' => $item['body'] ?? '',
1872 'changed' => DateTimeFormat::utcNow(),
1873 'edited' => DateTimeFormat::utc($item["edited"])];
1875 $condition = ["`uri` = ? AND `uid` IN (0, ?)", $item["uri"], $importer["importer_uid"]];
1876 Item::update($fields, $condition);
1884 * Detects the entry type of the item
1886 * @param array $importer Record of the importer user mixed with contact of the content
1887 * @param array $item the new item record
1889 * @return int Is it a toplevel entry, a comment or a relayed comment?
1890 * @throws \Exception
1891 * @todo set proper type-hints (array?)
1893 private static function getEntryType($importer, $item)
1895 if ($item["thr-parent"] != $item["uri"]) {
1898 if ($importer["page-flags"] == User::PAGE_FLAGS_COMMUNITY || $importer["page-flags"] == User::PAGE_FLAGS_PRVGROUP) {
1901 Logger::log("possible community action");
1903 $sql_extra = " AND `self` AND `wall`";
1906 // was the top-level post for this action written by somebody on this site?
1907 // Specifically, the recipient?
1908 $parent = Post::selectFirst(['forum_mode', 'wall'],
1909 ["`uri` = ? AND `uid` = ?" . $sql_extra, $item["thr-parent"], $importer["importer_uid"]]);
1911 $is_a_remote_action = DBA::isResult($parent);
1914 * Does this have the characteristics of a community or private group action?
1915 * If it's an action to a wall post on a community/prvgroup page it's a
1916 * valid community action. Also forum_mode makes it valid for sure.
1917 * If neither, it's not.
1919 if ($is_a_remote_action && $community && (!$parent["forum_mode"]) && (!$parent["wall"])) {
1920 $is_a_remote_action = false;
1921 Logger::log("not a community action");
1924 if ($is_a_remote_action) {
1925 return DFRN::REPLY_RC;
1930 return DFRN::TOP_LEVEL;
1937 * @param array $item The new item record
1938 * @param array $importer Record of the importer user mixed with contact of the content
1940 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1941 * @todo set proper type-hints (array?)
1943 private static function doPoke(array $item, array $importer)
1945 $verb = urldecode(substr($item["verb"], strpos($item["verb"], "#")+1));
1949 $xo = XML::parseString($item["object"]);
1951 if (($xo->type == Activity\ObjectType::PERSON) && ($xo->id)) {
1952 // somebody was poked/prodded. Was it me?
1954 foreach ($xo->link as $l) {
1955 $atts = $l->attributes();
1956 switch ($atts["rel"]) {
1958 $Blink = $atts["href"];
1965 if ($Blink && Strings::compareLink($Blink, DI::baseUrl() . "/profile/" . $importer["nickname"])) {
1966 $author = DBA::selectFirst('contact', ['id', 'name', 'thumb', 'url'], ['id' => $item['author-id']]);
1968 $parent = Post::selectFirst(['id'], ['uri' => $item['thr-parent'], 'uid' => $importer["importer_uid"]]);
1969 $item['parent'] = $parent['id'];
1971 // send a notification
1974 "type" => Notification\Type::POKE,
1975 "otype" => Notification\ObjectType::PERSON,
1976 "activity" => $verb,
1977 "verb" => $item["verb"],
1978 "uid" => $importer["importer_uid"],
1979 "cid" => $author["id"],
1981 "link" => DI::baseUrl() . "/display/" . urlencode($item['guid']),
1989 * Processes several actions, depending on the verb
1991 * @param int $entrytype Is it a toplevel entry, a comment or a relayed comment?
1992 * @param array $importer Record of the importer user mixed with contact of the content
1993 * @param array $item the new item record
1994 * @param bool $is_like Is the verb a "like"?
1996 * @return bool Should the processing of the entries be continued?
1997 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1998 * @todo set proper type-hints (array?)
2000 private static function processVerbs($entrytype, $importer, &$item, &$is_like)
2002 Logger::log("Process verb ".$item["verb"]." and object-type ".$item["object-type"]." for entrytype ".$entrytype, Logger::DEBUG);
2004 if (($entrytype == DFRN::TOP_LEVEL) && !empty($importer['id'])) {
2005 // The filling of the the "contact" variable is done for legcy reasons
2006 // The functions below are partly used by ostatus.php as well - where we have this variable
2007 $contact = Contact::selectFirst([], ['id' => $importer['id']]);
2009 $activity = DI::activity();
2011 // Big question: Do we need these functions? They were part of the "consume_feed" function.
2012 // This function once was responsible for DFRN and OStatus.
2013 if ($activity->match($item["verb"], Activity::FOLLOW)) {
2014 Logger::log("New follower");
2015 Contact::addRelationship($importer, $contact, $item);
2018 if ($activity->match($item["verb"], Activity::UNFOLLOW)) {
2019 Logger::log("Lost follower");
2020 Contact::removeFollower($importer, $contact, $item);
2023 if ($activity->match($item["verb"], Activity::REQ_FRIEND)) {
2024 Logger::log("New friend request");
2025 Contact::addRelationship($importer, $contact, $item, true);
2028 if ($activity->match($item["verb"], Activity::UNFRIEND)) {
2029 Logger::log("Lost sharer");
2030 Contact::removeSharer($importer, $contact, $item);
2034 if (($item["verb"] == Activity::LIKE)
2035 || ($item["verb"] == Activity::DISLIKE)
2036 || ($item["verb"] == Activity::ATTEND)
2037 || ($item["verb"] == Activity::ATTENDNO)
2038 || ($item["verb"] == Activity::ATTENDMAYBE)
2039 || ($item["verb"] == Activity::ANNOUNCE)
2042 $item["gravity"] = GRAVITY_ACTIVITY;
2043 // only one like or dislike per person
2044 // split into two queries for performance issues
2045 $condition = ['uid' => $item["uid"], 'author-id' => $item["author-id"], 'gravity' => GRAVITY_ACTIVITY,
2046 'verb' => $item['verb'], 'parent-uri' => $item['thr-parent']];
2047 if (Post::exists($condition)) {
2051 $condition = ['uid' => $item["uid"], 'author-id' => $item["author-id"], 'gravity' => GRAVITY_ACTIVITY,
2052 'verb' => $item['verb'], 'thr-parent' => $item['thr-parent']];
2053 if (Post::exists($condition)) {
2057 // The owner of an activity must be the author
2058 $item["owner-name"] = $item["author-name"];
2059 $item["owner-link"] = $item["author-link"];
2060 $item["owner-avatar"] = $item["author-avatar"];
2061 $item["owner-id"] = $item["author-id"];
2066 if (($item["verb"] == Activity::TAG) && ($item["object-type"] == Activity\ObjectType::TAGTERM)) {
2067 $xo = XML::parseString($item["object"]);
2068 $xt = XML::parseString($item["target"]);
2070 if ($xt->type == Activity\ObjectType::NOTE) {
2071 $item_tag = Post::selectFirst(['id', 'uri-id'], ['uri' => $xt->id, 'uid' => $importer["importer_uid"]]);
2073 if (!DBA::isResult($item_tag)) {
2074 Logger::log("Query failed to execute, no result returned in " . __FUNCTION__);
2078 // extract tag, if not duplicate, add to parent item
2080 Tag::store($item_tag['uri-id'], Tag::HASHTAG, $xo->content);
2089 * Processes the link elements
2091 * @param object $links link elements
2092 * @param array $item the item record
2094 * @todo set proper type-hints
2096 private static function parseLinks($links, &$item)
2103 foreach ($links as $link) {
2104 foreach ($link->attributes as $attributes) {
2105 switch ($attributes->name) {
2106 case "href" : $href = $attributes->textContent; break;
2107 case "rel" : $rel = $attributes->textContent; break;
2108 case "type" : $type = $attributes->textContent; break;
2109 case "length": $length = $attributes->textContent; break;
2110 case "title" : $title = $attributes->textContent; break;
2113 if (($rel != "") && ($href != "")) {
2116 $item["plink"] = $href;
2119 Post\Media::insert(['uri-id' => $item['uri-id'], 'type' => Post\Media::DOCUMENT,
2120 'url' => $href, 'mimetype' => $type, 'size' => $length, 'description' => $title]);
2128 * Checks if an incoming message is wanted
2130 * @param array $item
2131 * @return boolean Is the message wanted?
2133 private static function isSolicitedMessage(array $item)
2135 if (DBA::exists('contact', ["`nurl` = ? AND `uid` != ? AND `rel` IN (?, ?)",
2136 Strings::normaliseLink($item["author-link"]), 0, Contact::FRIEND, Contact::SHARING])) {
2137 Logger::info('Author has got followers - accepted', ['uri' => $item['uri'], 'author' => $item["author-link"]]);
2141 $taglist = Tag::getByURIId($item['uri-id'], [Tag::HASHTAG]);
2142 $tags = array_column($taglist, 'name');
2143 return Relay::isSolicitedPost($tags, $item['body'], $item['author-id'], $item['uri'], Protocol::DFRN);
2147 * Processes the entry elements which contain the items and comments
2149 * @param array $header Array of the header elements that always stay the same
2150 * @param object $xpath XPath object
2151 * @param object $entry entry elements
2152 * @param array $importer Record of the importer user mixed with contact of the content
2153 * @param string $xml xml
2155 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2156 * @throws \ImagickException
2157 * @todo Add type-hints
2159 private static function processEntry($header, $xpath, $entry, $importer, $xml, $protocol)
2161 Logger::log("Processing entries");
2165 $item["protocol"] = $protocol;
2167 $item["source"] = $xml;
2170 $item["uri"] = XML::getFirstNodeValue($xpath, "atom:id/text()", $entry);
2172 $item["edited"] = XML::getFirstNodeValue($xpath, "atom:updated/text()", $entry);
2174 $current = Post::selectFirst(['id', 'uid', 'edited', 'body'],
2175 ['uri' => $item["uri"], 'uid' => $importer["importer_uid"]]
2177 // Is there an existing item?
2178 if (DBA::isResult($current) && !self::isEditedTimestampNewer($current, $item)) {
2179 Logger::log("Item ".$item["uri"]." (".$item['edited'].") already existed.", Logger::DEBUG);
2184 $owner = self::fetchauthor($xpath, $entry, $importer, "dfrn:owner", true, $xml);
2186 $owner_unknown = (isset($owner["contact-unknown"]) && $owner["contact-unknown"]);
2188 $item["owner-name"] = $owner["name"];
2189 $item["owner-link"] = $owner["link"];
2190 $item["owner-avatar"] = $owner["avatar"];
2191 $item["owner-id"] = Contact::getIdForURL($owner["link"], 0);
2194 $author = self::fetchauthor($xpath, $entry, $importer, "atom:author", true, $xml);
2196 $item["author-name"] = $author["name"];
2197 $item["author-link"] = $author["link"];
2198 $item["author-avatar"] = $author["avatar"];
2199 $item["author-id"] = Contact::getIdForURL($author["link"], 0);
2201 $item["title"] = XML::getFirstNodeValue($xpath, "atom:title/text()", $entry);
2203 if (!empty($item["title"])) {
2204 $item["post-type"] = Item::PT_ARTICLE;
2206 $item["post-type"] = Item::PT_NOTE;
2209 $item["created"] = XML::getFirstNodeValue($xpath, "atom:published/text()", $entry);
2211 $item["body"] = XML::getFirstNodeValue($xpath, "dfrn:env/text()", $entry);
2212 $item["body"] = str_replace([' ',"\t","\r","\n"], ['','','',''], $item["body"]);
2214 $item["body"] = Strings::base64UrlDecode($item["body"]);
2216 $item["body"] = BBCode::limitBodySize($item["body"]);
2218 /// @todo We should check for a repeated post and if we know the repeated author.
2220 // We don't need the content element since "dfrn:env" is always present
2221 //$item["body"] = $xpath->query("atom:content/text()", $entry)->item(0)->nodeValue;
2223 $item["location"] = XML::getFirstNodeValue($xpath, "dfrn:location/text()", $entry);
2225 $item["coord"] = XML::getFirstNodeValue($xpath, "georss:point", $entry);
2227 $item["private"] = XML::getFirstNodeValue($xpath, "dfrn:private/text()", $entry);
2229 $unlisted = XML::getFirstNodeValue($xpath, "dfrn:unlisted/text()", $entry);
2230 if (!empty($unlisted) && ($item['private'] != Item::PRIVATE)) {
2231 $item['private'] = Item::UNLISTED;
2234 $item["extid"] = XML::getFirstNodeValue($xpath, "dfrn:extid/text()", $entry);
2236 if (XML::getFirstNodeValue($xpath, "dfrn:bookmark/text()", $entry) == "true") {
2237 $item["post-type"] = Item::PT_PAGE;
2240 $notice_info = $xpath->query("statusnet:notice_info", $entry);
2241 if ($notice_info && ($notice_info->length > 0)) {
2242 foreach ($notice_info->item(0)->attributes as $attributes) {
2243 if ($attributes->name == "source") {
2244 $item["app"] = strip_tags($attributes->textContent);
2249 $item["guid"] = XML::getFirstNodeValue($xpath, "dfrn:diaspora_guid/text()", $entry);
2251 $item['uri-id'] = ItemURI::insert(['uri' => $item['uri'], 'guid' => $item['guid']]);
2253 $item["body"] = Item::improveSharedDataInBody($item);
2255 Tag::storeFromBody($item['uri-id'], $item["body"]);
2257 // We store the data from "dfrn:diaspora_signature" in a different table, this is done in "Item::insert"
2258 $dsprsig = XML::unescape(XML::getFirstNodeValue($xpath, "dfrn:diaspora_signature/text()", $entry));
2259 if ($dsprsig != "") {
2260 $signature = json_decode(base64_decode($dsprsig));
2261 // We don't store the old style signatures anymore that also contained the "signature" and "signer"
2262 if (!empty($signature->signed_text) && empty($signature->signature) && empty($signature->signer)) {
2263 $item["diaspora_signed_text"] = $signature->signed_text;
2267 $item["verb"] = XML::getFirstNodeValue($xpath, "activity:verb/text()", $entry);
2269 if (XML::getFirstNodeValue($xpath, "activity:object-type/text()", $entry) != "") {
2270 $item["object-type"] = XML::getFirstNodeValue($xpath, "activity:object-type/text()", $entry);
2273 $object = $xpath->query("activity:object", $entry)->item(0);
2274 $item["object"] = self::transformActivity($xpath, $object, "object");
2276 if (trim($item["object"]) != "") {
2277 $r = XML::parseString($item["object"]);
2278 if (isset($r->type)) {
2279 $item["object-type"] = $r->type;
2283 $target = $xpath->query("activity:target", $entry)->item(0);
2284 $item["target"] = self::transformActivity($xpath, $target, "target");
2286 $categories = $xpath->query("atom:category", $entry);
2288 foreach ($categories as $category) {
2291 foreach ($category->attributes as $attributes) {
2292 if ($attributes->name == "term") {
2293 $term = $attributes->textContent;
2296 if ($attributes->name == "scheme") {
2297 $scheme = $attributes->textContent;
2301 if (($term != "") && ($scheme != "")) {
2302 $parts = explode(":", $scheme);
2303 if ((count($parts) >= 4) && (array_shift($parts) == "X-DFRN")) {
2304 $termurl = array_pop($parts);
2305 $termurl = array_pop($parts) . ':' . $termurl;
2306 Tag::store($item['uri-id'], Tag::IMPLICIT_MENTION, $term, $termurl);
2312 $links = $xpath->query("atom:link", $entry);
2314 self::parseLinks($links, $item);
2317 $item['conversation-uri'] = XML::getFirstNodeValue($xpath, 'ostatus:conversation/text()', $entry);
2319 $conv = $xpath->query('ostatus:conversation', $entry);
2320 if (is_object($conv->item(0))) {
2321 foreach ($conv->item(0)->attributes as $attributes) {
2322 if ($attributes->name == "ref") {
2323 $item['conversation-uri'] = $attributes->textContent;
2325 if ($attributes->name == "href") {
2326 $item['conversation-href'] = $attributes->textContent;
2331 // Is it a reply or a top level posting?
2332 $item['thr-parent'] = $item['uri'];
2334 $inreplyto = $xpath->query("thr:in-reply-to", $entry);
2335 if (is_object($inreplyto->item(0))) {
2336 foreach ($inreplyto->item(0)->attributes as $attributes) {
2337 if ($attributes->name == "ref") {
2338 $item['thr-parent'] = $attributes->textContent;
2343 // Check if the message is wanted
2344 if (($importer['importer_uid'] == 0) && ($item['uri'] == $item['thr-parent'])) {
2345 if (!self::isSolicitedMessage($item)) {
2346 DBA::delete('item-uri', ['uri' => $item['uri']]);
2351 // Get the type of the item (Top level post, reply or remote reply)
2352 $entrytype = self::getEntryType($importer, $item);
2354 // Now assign the rest of the values that depend on the type of the message
2355 if (in_array($entrytype, [DFRN::REPLY, DFRN::REPLY_RC])) {
2356 if (!isset($item["object-type"])) {
2357 $item["object-type"] = Activity\ObjectType::COMMENT;
2360 if ($item["contact-id"] != $owner["contact-id"]) {
2361 $item["contact-id"] = $owner["contact-id"];
2364 if (($item["network"] != $owner["network"]) && ($owner["network"] != "")) {
2365 $item["network"] = $owner["network"];
2368 if ($item["contact-id"] != $author["contact-id"]) {
2369 $item["contact-id"] = $author["contact-id"];
2372 if (($item["network"] != $author["network"]) && ($author["network"] != "")) {
2373 $item["network"] = $author["network"];
2377 // Ensure to have the correct share data
2378 $item = Item::addShareDataFromOriginal($item);
2380 if ($entrytype == DFRN::REPLY_RC) {
2382 } elseif ($entrytype == DFRN::TOP_LEVEL) {
2383 if (!isset($item["object-type"])) {
2384 $item["object-type"] = Activity\ObjectType::NOTE;
2388 if (($item["object-type"] == Activity\ObjectType::EVENT) && !$owner_unknown) {
2389 Logger::log("Item ".$item["uri"]." seems to contain an event.", Logger::DEBUG);
2390 $ev = Event::fromBBCode($item["body"]);
2391 if ((!empty($ev['desc']) || !empty($ev['summary'])) && !empty($ev['start'])) {
2392 Logger::log("Event in item ".$item["uri"]." was found.", Logger::DEBUG);
2393 $ev["cid"] = $importer["id"];
2394 $ev["uid"] = $importer["importer_uid"];
2395 $ev["uri"] = $item["uri"];
2396 $ev["edited"] = $item["edited"];
2397 $ev["private"] = $item["private"];
2398 $ev["guid"] = $item["guid"];
2399 $ev["plink"] = $item["plink"];
2400 $ev["network"] = $item["network"];
2401 $ev["protocol"] = $item["protocol"];
2402 $ev["direction"] = $item["direction"];
2403 $ev["source"] = $item["source"];
2405 $condition = ['uri' => $item["uri"], 'uid' => $importer["importer_uid"]];
2406 $event = DBA::selectFirst('event', ['id'], $condition);
2407 if (DBA::isResult($event)) {
2408 $ev["id"] = $event["id"];
2411 $event_id = Event::store($ev);
2412 Logger::log("Event ".$event_id." was stored", Logger::DEBUG);
2418 if (!self::processVerbs($entrytype, $importer, $item, $is_like)) {
2419 Logger::log("Exiting because 'processVerbs' told us so", Logger::DEBUG);
2423 // This check is done here to be able to receive connection requests in "processVerbs"
2424 if (($entrytype == DFRN::TOP_LEVEL) && $owner_unknown) {
2425 Logger::log("Item won't be stored because user " . $importer["importer_uid"] . " doesn't follow " . $item["owner-link"] . ".", Logger::DEBUG);
2430 // Update content if 'updated' changes
2431 if (DBA::isResult($current)) {
2432 if (self::updateContent($current, $item, $importer, $entrytype)) {
2433 Logger::log("Item ".$item["uri"]." was updated.", Logger::DEBUG);
2435 Logger::log("Item " . $item["uri"] . " already existed.", Logger::DEBUG);
2440 if (in_array($entrytype, [DFRN::REPLY, DFRN::REPLY_RC])) {
2441 // Will be overwritten for sharing accounts in Item::insert
2442 if (empty($item['post-reason']) && ($entrytype == DFRN::REPLY)) {
2443 $item['post-reason'] = Item::PR_COMMENT;
2446 $posted_id = Item::insert($item);
2448 Logger::log("Reply from contact ".$item["contact-id"]." was stored with id ".$posted_id, Logger::DEBUG);
2450 if ($item['uid'] == 0) {
2451 Item::distribute($posted_id);
2456 } else { // $entrytype == DFRN::TOP_LEVEL
2457 if (($importer["uid"] == 0) && ($importer["importer_uid"] != 0)) {
2458 Logger::log("Contact ".$importer["id"]." isn't known to user ".$importer["importer_uid"].". The post will be ignored.", Logger::DEBUG);
2461 if (!Strings::compareLink($item["owner-link"], $importer["url"])) {
2463 * The item owner info is not our contact. It's OK and is to be expected if this is a tgroup delivery,
2464 * but otherwise there's a possible data mixup on the sender's system.
2465 * the tgroup delivery code called from Item::insert will correct it if it's a forum,
2466 * but we're going to unconditionally correct it here so that the post will always be owned by our contact.
2468 Logger::log('Correcting item owner.', Logger::DEBUG);
2469 $item["owner-link"] = $importer["url"];
2470 $item["owner-id"] = Contact::getIdForURL($importer["url"], 0);
2473 if (($importer["rel"] == Contact::FOLLOWER) && (!self::tgroupCheck($importer["importer_uid"], $item))) {
2474 Logger::log("Contact ".$importer["id"]." is only follower and tgroup check was negative.", Logger::DEBUG);
2478 // This is my contact on another system, but it's really me.
2479 // Turn this into a wall post.
2480 $notify = Item::isRemoteSelf($importer, $item);
2482 $posted_id = Item::insert($item, $notify);
2485 $posted_id = $notify;
2488 Logger::log("Item was stored with id ".$posted_id, Logger::DEBUG);
2490 if ($item['uid'] == 0) {
2491 Item::distribute($posted_id);
2494 if (stristr($item["verb"], Activity::POKE)) {
2495 $item['id'] = $posted_id;
2496 self::doPoke($item, $importer);
2504 * @param object $xpath XPath object
2505 * @param object $deletion deletion elements
2506 * @param array $importer Record of the importer user mixed with contact of the content
2508 * @throws \Exception
2509 * @todo set proper type-hints
2511 private static function processDeletion($xpath, $deletion, $importer)
2513 Logger::log("Processing deletions");
2516 foreach ($deletion->attributes as $attributes) {
2517 if ($attributes->name == "ref") {
2518 $uri = $attributes->textContent;
2522 if (!$uri || !$importer["id"]) {
2526 $condition = ['uri' => $uri, 'uid' => $importer["importer_uid"]];
2527 $item = Post::selectFirst(['id', 'parent', 'contact-id', 'uri-id', 'deleted', 'gravity'], $condition);
2528 if (!DBA::isResult($item)) {
2529 Logger::log("Item with uri " . $uri . " for user " . $importer["importer_uid"] . " wasn't found.", Logger::DEBUG);
2533 if (DBA::exists('post-category', ['uri-id' => $item['uri-id'], 'uid' => $importer['importer_uid'], 'type' => Post\Category::FILE])) {
2534 Logger::notice("Item is filed. It won't be deleted.", ['uri' => $uri, 'uri-id' => $item['uri_id'], 'uid' => $importer["importer_uid"]]);
2538 // When it is a starting post it has to belong to the person that wants to delete it
2539 if (($item['gravity'] == GRAVITY_PARENT) && ($item['contact-id'] != $importer["id"])) {
2540 Logger::log("Item with uri " . $uri . " don't belong to contact " . $importer["id"] . " - ignoring deletion.", Logger::DEBUG);
2544 // Comments can be deleted by the thread owner or comment owner
2545 if (($item['gravity'] != GRAVITY_PARENT) && ($item['contact-id'] != $importer["id"])) {
2546 $condition = ['id' => $item['parent'], 'contact-id' => $importer["id"]];
2547 if (!Post::exists($condition)) {
2548 Logger::log("Item with uri " . $uri . " wasn't found or mustn't be deleted by contact " . $importer["id"] . " - ignoring deletion.", Logger::DEBUG);
2553 if ($item["deleted"]) {
2557 Logger::log('deleting item '.$item['id'].' uri='.$uri, Logger::DEBUG);
2559 Item::markForDeletion(['id' => $item['id']]);
2563 * Imports a DFRN message
2565 * @param string $xml The DFRN message
2566 * @param array $importer Record of the importer user mixed with contact of the content
2567 * @param int $protocol Transport protocol
2568 * @param int $direction Is the message pushed or pulled?
2569 * @return integer Import status
2570 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2571 * @throws \ImagickException
2572 * @todo set proper type-hints
2574 public static function import($xml, $importer, $protocol, $direction)
2580 $doc = new DOMDocument();
2581 @$doc->loadXML($xml);
2583 $xpath = new DOMXPath($doc);
2584 $xpath->registerNamespace("atom", ActivityNamespace::ATOM1);
2585 $xpath->registerNamespace("thr", ActivityNamespace::THREAD);
2586 $xpath->registerNamespace("at", ActivityNamespace::TOMB);
2587 $xpath->registerNamespace("media", ActivityNamespace::MEDIA);
2588 $xpath->registerNamespace("dfrn", ActivityNamespace::DFRN);
2589 $xpath->registerNamespace("activity", ActivityNamespace::ACTIVITY);
2590 $xpath->registerNamespace("georss", ActivityNamespace::GEORSS);
2591 $xpath->registerNamespace("poco", ActivityNamespace::POCO);
2592 $xpath->registerNamespace("ostatus", ActivityNamespace::OSTATUS);
2593 $xpath->registerNamespace("statusnet", ActivityNamespace::STATUSNET);
2596 $header["uid"] = $importer["importer_uid"];
2597 $header["network"] = Protocol::DFRN;
2598 $header["wall"] = 0;
2599 $header["origin"] = 0;
2600 $header["contact-id"] = $importer["id"];
2601 $header["direction"] = $direction;
2603 if ($direction === Conversation::RELAY) {
2604 $header['post-reason'] = Item::PR_RELAY;
2607 // Update the contact table if the data has changed
2609 // The "atom:author" is only present in feeds
2610 if ($xpath->query("/atom:feed/atom:author")->length > 0) {
2611 self::fetchauthor($xpath, $doc->firstChild, $importer, "atom:author", false, $xml);
2614 // Only the "dfrn:owner" in the head section contains all data
2615 if ($xpath->query("/atom:feed/dfrn:owner")->length > 0) {
2616 self::fetchauthor($xpath, $doc->firstChild, $importer, "dfrn:owner", false, $xml);
2619 Logger::log("Import DFRN message for user " . $importer["importer_uid"] . " from contact " . $importer["id"], Logger::DEBUG);
2621 if (!empty($importer['gsid'])) {
2622 if ($protocol == Conversation::PARCEL_DIASPORA_DFRN) {
2623 GServer::setProtocol($importer['gsid'], Post\DeliveryData::DFRN);
2624 } elseif ($protocol == Conversation::PARCEL_LEGACY_DFRN) {
2625 GServer::setProtocol($importer['gsid'], Post\DeliveryData::LEGACY_DFRN);
2629 // is it a public forum? Private forums aren't exposed with this method
2630 $forum = intval(XML::getFirstNodeValue($xpath, "/atom:feed/dfrn:community/text()"));
2632 // The account type is new since 3.5.1
2633 if ($xpath->query("/atom:feed/dfrn:account_type")->length > 0) {
2634 // Hint: We are using separate update calls for uid=0 and uid!=0 since a combined call is bad for the database performance
2636 $accounttype = intval(XML::getFirstNodeValue($xpath, "/atom:feed/dfrn:account_type/text()"));
2638 if ($accounttype != $importer["contact-type"]) {
2639 DBA::update('contact', ['contact-type' => $accounttype], ['id' => $importer['id']]);
2641 // Updating the public contact as well
2642 DBA::update('contact', ['contact-type' => $accounttype], ['uid' => 0, 'nurl' => $importer['nurl']]);
2644 // A forum contact can either have set "forum" or "prv" - but not both
2645 if ($accounttype == User::ACCOUNT_TYPE_COMMUNITY) {
2646 // It's a forum, so either set the public or private forum flag
2647 $condition = ['(`forum` != ? OR `prv` != ?) AND `id` = ?', $forum, !$forum, $importer['id']];
2648 DBA::update('contact', ['forum' => $forum, 'prv' => !$forum], $condition);
2650 // Updating the public contact as well
2651 $condition = ['(`forum` != ? OR `prv` != ?) AND `uid` = 0 AND `nurl` = ?', $forum, !$forum, $importer['nurl']];
2652 DBA::update('contact', ['forum' => $forum, 'prv' => !$forum], $condition);
2654 // It's not a forum, so remove the flags
2655 $condition = ['(`forum` OR `prv`) AND `id` = ?', $importer['id']];
2656 DBA::update('contact', ['forum' => false, 'prv' => false], $condition);
2658 // Updating the public contact as well
2659 $condition = ['(`forum` OR `prv`) AND `uid` = 0 AND `nurl` = ?', $importer['nurl']];
2660 DBA::update('contact', ['forum' => false, 'prv' => false], $condition);
2662 } elseif ($forum != $importer["forum"]) { // Deprecated since 3.5.1
2663 $condition = ['`forum` != ? AND `id` = ?', $forum, $importer["id"]];
2664 DBA::update('contact', ['forum' => $forum], $condition);
2666 // Updating the public contact as well
2667 $condition = ['`forum` != ? AND `uid` = 0 AND `nurl` = ?', $forum, $importer['nurl']];
2668 DBA::update('contact', ['forum' => $forum], $condition);
2672 // We are processing relocations even if we are ignoring a contact
2673 $relocations = $xpath->query("/atom:feed/dfrn:relocate");
2674 foreach ($relocations as $relocation) {
2675 self::processRelocation($xpath, $relocation, $importer);
2678 if (($importer["uid"] != 0) && !$importer["readonly"]) {
2679 $mails = $xpath->query("/atom:feed/dfrn:mail");
2680 foreach ($mails as $mail) {
2681 self::processMail($xpath, $mail, $importer);
2684 $suggestions = $xpath->query("/atom:feed/dfrn:suggest");
2685 foreach ($suggestions as $suggestion) {
2686 self::processSuggestion($xpath, $suggestion, $importer);
2690 $deletions = $xpath->query("/atom:feed/at:deleted-entry");
2691 if (!empty($deletions)) {
2692 foreach ($deletions as $deletion) {
2693 self::processDeletion($xpath, $deletion, $importer);
2695 if (count($deletions) > 0) {
2696 Logger::notice('Deletions had been processed');
2701 $entries = $xpath->query("/atom:feed/atom:entry");
2702 foreach ($entries as $entry) {
2703 self::processEntry($header, $xpath, $entry, $importer, $xml, $protocol);
2706 Logger::log("Import done for user " . $importer["importer_uid"] . " from contact " . $importer["id"], Logger::DEBUG);
2711 * Returns the activity verb
2713 * @param array $item Item array
2715 * @return string activity verb
2717 private static function constructVerb(array $item)
2719 if ($item['verb']) {
2720 return $item['verb'];
2722 return Activity::POST;
2725 private static function tgroupCheck($uid, $item)
2729 // check that the message originated elsewhere and is a top-level post
2731 if ($item['wall'] || $item['origin'] || ($item['uri'] != $item['thr-parent'])) {
2735 $user = DBA::selectFirst('user', ['page-flags', 'nickname'], ['uid' => $uid]);
2736 if (!DBA::isResult($user)) {
2740 $community_page = ($user['page-flags'] == User::PAGE_FLAGS_COMMUNITY);
2741 $prvgroup = ($user['page-flags'] == User::PAGE_FLAGS_PRVGROUP);
2743 $link = Strings::normaliseLink(DI::baseUrl() . '/profile/' . $user['nickname']);
2746 * Diaspora uses their own hardwired link URL in @-tags
2747 * instead of the one we supply with webfinger
2749 $dlink = Strings::normaliseLink(DI::baseUrl() . '/u/' . $user['nickname']);
2751 $cnt = preg_match_all('/[\@\!]\[url\=(.*?)\](.*?)\[\/url\]/ism', $item['body'], $matches, PREG_SET_ORDER);
2753 foreach ($matches as $mtch) {
2754 if (Strings::compareLink($link, $mtch[1]) || Strings::compareLink($dlink, $mtch[1])) {
2756 Logger::log('mention found: ' . $mtch[2]);
2765 return $community_page || $prvgroup;
2769 * This function returns true if $update has an edited timestamp newer
2770 * than $existing, i.e. $update contains new data which should override
2771 * what's already there. If there is no timestamp yet, the update is
2772 * assumed to be newer. If the update has no timestamp, the existing
2773 * item is assumed to be up-to-date. If the timestamps are equal it
2774 * assumes the update has been seen before and should be ignored.
2779 * @throws \Exception
2781 private static function isEditedTimestampNewer($existing, $update)
2783 if (empty($existing['edited'])) {
2786 if (empty($update['edited'])) {
2790 $existing_edited = DateTimeFormat::utc($existing['edited']);
2791 $update_edited = DateTimeFormat::utc($update['edited']);
2793 return (strcmp($existing_edited, $update_edited) < 0);
2797 * Checks if the given contact url does support DFRN
2799 * @param string $url profile url
2801 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2802 * @throws \ImagickException
2804 public static function isSupportedByContactUrl($url)
2806 $probe = Probe::uri($url, Protocol::DFRN);
2807 return $probe['network'] == Protocol::DFRN;