3 * @copyright Copyright (C) 2010-2022, 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\Content\Text\BBCode;
27 use Friendica\Core\Logger;
28 use Friendica\Core\Protocol;
29 use Friendica\Database\DBA;
31 use Friendica\Model\Contact;
32 use Friendica\Model\Conversation;
33 use Friendica\Model\Event;
34 use Friendica\Model\FContact;
35 use Friendica\Model\GServer;
36 use Friendica\Model\Item;
37 use Friendica\Model\ItemURI;
38 use Friendica\Model\Mail;
39 use Friendica\Model\Notification;
40 use Friendica\Model\Photo;
41 use Friendica\Model\Post;
42 use Friendica\Model\Profile;
43 use Friendica\Model\Tag;
44 use Friendica\Model\User;
45 use Friendica\Network\Probe;
46 use Friendica\Util\Crypto;
47 use Friendica\Util\DateTimeFormat;
48 use Friendica\Util\Images;
49 use Friendica\Util\Network;
50 use Friendica\Util\Proxy;
51 use Friendica\Util\Strings;
52 use Friendica\Util\XML;
55 * This class contain functions to create and send DFRN XML files
60 const TOP_LEVEL = 0; // Top level posting
61 const REPLY = 1; // Regular reply that is stored locally
62 const REPLY_RC = 2; // Reply that will be relayed
65 * Generates an array of contact and user for DFRN imports
67 * This array contains not only the receiver but also the sender of the message.
69 * @param integer $cid Contact id
70 * @param integer $uid User id
72 * @return array importer
75 public static function getImporter(int $cid, int $uid = 0): array
77 $condition = ['id' => $cid, 'blocked' => false, 'pending' => false];
78 $contact = DBA::selectFirst('contact', [], $condition);
79 if (!DBA::isResult($contact)) {
83 $contact['cpubkey'] = $contact['pubkey'];
84 $contact['cprvkey'] = $contact['prvkey'];
85 $contact['senderName'] = $contact['name'];
88 $condition = ['uid' => $uid, 'account_expired' => false, 'account_removed' => false];
89 $user = DBA::selectFirst('user', [], $condition);
90 if (!DBA::isResult($user)) {
94 $user['importer_uid'] = $user['uid'];
95 $user['uprvkey'] = $user['prvkey'];
97 $user = ['importer_uid' => 0, 'uprvkey' => '', 'timezone' => 'UTC',
98 'nickname' => '', 'sprvkey' => '', 'spubkey' => '',
99 'page-flags' => 0, 'account-type' => 0, 'prvnets' => 0];
102 return array_merge($contact, $user);
106 * Generates the atom entries for delivery.php
108 * This function is used whenever content is transmitted via DFRN.
110 * @param array $items Item elements
111 * @param array $owner Owner record
113 * @return string DFRN entries
114 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
115 * @throws \ImagickException
116 * @todo Find proper type-hints
118 public static function entries(array $items, array $owner): string
120 $doc = new DOMDocument('1.0', 'utf-8');
121 $doc->formatOutput = true;
123 $root = self::addHeader($doc, $owner, "dfrn:owner", "", false);
125 if (! count($items)) {
126 return trim($doc->saveXML());
129 foreach ($items as $item) {
130 // These values aren't sent when sending from the queue.
131 /// @todo Check if we can set these values from the queue or if they are needed at all.
132 $item["entry:comment-allow"] = ($item["entry:comment-allow"] ?? '') ?: true;
133 $item["entry:cid"] = $item["entry:cid"] ?? 0;
135 $entry = self::entry($doc, "text", $item, $owner, $item["entry:comment-allow"], $item["entry:cid"]);
137 $root->appendChild($entry);
141 return trim($doc->saveXML());
145 * Generate an atom entry for a given uri id and user
147 * @param int $uri_id The uri id
148 * @param int $uid The user id
149 * @param boolean $conversation Show the conversation. If false show the single post.
151 * @return string DFRN feed entry
152 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
153 * @throws \ImagickException
155 public static function itemFeed(int $uri_id, int $uid, bool $conversation = false): string
158 $condition = ['parent-uri-id' => $uri_id];
160 $condition = ['uri-id' => $uri_id];
163 $condition['uid'] = $uid;
165 $items = Post::selectToArray(Item::DELIVER_FIELDLIST, $condition);
166 if (!DBA::isResult($items)) {
172 if ($item['uid'] != 0) {
173 $owner = User::getOwnerDataById($item['uid']);
178 $owner = ['uid' => 0, 'nick' => 'feed-item'];
181 $doc = new DOMDocument('1.0', 'utf-8');
182 $doc->formatOutput = true;
186 $root = $doc->createElementNS(ActivityNamespace::ATOM1, 'feed');
187 $doc->appendChild($root);
189 $root->setAttribute("xmlns:thr", ActivityNamespace::THREAD);
190 $root->setAttribute("xmlns:at", ActivityNamespace::TOMB);
191 $root->setAttribute("xmlns:media", ActivityNamespace::MEDIA);
192 $root->setAttribute("xmlns:dfrn", ActivityNamespace::DFRN);
193 $root->setAttribute("xmlns:activity", ActivityNamespace::ACTIVITY);
194 $root->setAttribute("xmlns:georss", ActivityNamespace::GEORSS);
195 $root->setAttribute("xmlns:poco", ActivityNamespace::POCO);
196 $root->setAttribute("xmlns:ostatus", ActivityNamespace::OSTATUS);
197 $root->setAttribute("xmlns:statusnet", ActivityNamespace::STATUSNET);
199 //$root = self::addHeader($doc, $owner, "dfrn:owner", "", false);
201 foreach ($items as $item) {
202 $entry = self::entry($doc, $type, $item, $owner, true, 0);
204 $root->appendChild($entry);
208 self::entry($doc, $type, $item, $owner, true, 0, true);
211 $atom = trim($doc->saveXML());
216 * Create XML text for DFRN mails
218 * @param array $mail Mail record
219 * @param array $owner Owner record
221 * @return string DFRN mail
222 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
223 * @todo Find proper type-hints
225 public static function mail(array $mail, array $owner): string
227 $doc = new DOMDocument('1.0', 'utf-8');
228 $doc->formatOutput = true;
230 $root = self::addHeader($doc, $owner, "dfrn:owner", "", false);
232 $mailElement = $doc->createElement("dfrn:mail");
233 $senderElement = $doc->createElement("dfrn:sender");
235 XML::addElement($doc, $senderElement, "dfrn:name", $owner['name']);
236 XML::addElement($doc, $senderElement, "dfrn:uri", $owner['url']);
237 XML::addElement($doc, $senderElement, "dfrn:avatar", $owner['thumb']);
239 $mailElement->appendChild($senderElement);
241 XML::addElement($doc, $mailElement, "dfrn:id", $mail['uri']);
242 XML::addElement($doc, $mailElement, "dfrn:in-reply-to", $mail['parent-uri']);
243 XML::addElement($doc, $mailElement, "dfrn:sentdate", DateTimeFormat::utc($mail['created'] . '+00:00', DateTimeFormat::ATOM));
244 XML::addElement($doc, $mailElement, "dfrn:subject", $mail['title']);
245 XML::addElement($doc, $mailElement, "dfrn:content", $mail['body']);
247 $root->appendChild($mailElement);
249 return trim($doc->saveXML());
253 * Create XML text for DFRN friend suggestions
255 * @param array $item suggestion elements
256 * @param array $owner Owner record
258 * @return string DFRN suggestions
259 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
260 * @todo Find proper type-hints
262 public static function fsuggest(array $item, array $owner): string
264 $doc = new DOMDocument('1.0', 'utf-8');
265 $doc->formatOutput = true;
267 $root = self::addHeader($doc, $owner, "dfrn:owner", "", false);
269 $suggest = $doc->createElement("dfrn:suggest");
271 XML::addElement($doc, $suggest, "dfrn:url", $item['url']);
272 XML::addElement($doc, $suggest, "dfrn:name", $item['name']);
273 XML::addElement($doc, $suggest, "dfrn:photo", $item['photo']);
274 XML::addElement($doc, $suggest, "dfrn:request", $item['request']);
275 XML::addElement($doc, $suggest, "dfrn:note", $item['note']);
277 $root->appendChild($suggest);
279 return trim($doc->saveXML());
283 * Create XML text for DFRN relocations
285 * @param array $owner Owner record
286 * @param int $uid User ID
288 * @return string DFRN relocations
289 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
290 * @todo Find proper type-hints
292 public static function relocate(array $owner, int $uid): string
295 /* get site pubkey. this could be a new installation with no site keys*/
296 $pubkey = DI::config()->get('system', 'site_pubkey');
298 $res = Crypto::newKeypair(1024);
299 DI::config()->set('system', 'site_prvkey', $res['prvkey']);
300 DI::config()->set('system', 'site_pubkey', $res['pubkey']);
303 $profilephotos = Photo::selectToArray(['resource-id' , 'scale'], ['profile' => true, 'uid' => $uid], ['order' => ['scale']]);
306 $ext = Images::supportedTypes();
308 foreach ($profilephotos as $p) {
309 $photos[$p['scale']] = DI::baseUrl().'/photo/'.$p['resource-id'].'-'.$p['scale'].'.'.$ext[$p['type']];
313 $doc = new DOMDocument('1.0', 'utf-8');
314 $doc->formatOutput = true;
316 $root = self::addHeader($doc, $owner, "dfrn:owner", "", false);
318 $relocate = $doc->createElement("dfrn:relocate");
320 XML::addElement($doc, $relocate, "dfrn:url", $owner['url']);
321 XML::addElement($doc, $relocate, "dfrn:name", $owner['name']);
322 XML::addElement($doc, $relocate, "dfrn:addr", $owner['addr']);
323 XML::addElement($doc, $relocate, "dfrn:avatar", $owner['avatar']);
324 XML::addElement($doc, $relocate, "dfrn:photo", $photos[4]);
325 XML::addElement($doc, $relocate, "dfrn:thumb", $photos[5]);
326 XML::addElement($doc, $relocate, "dfrn:micro", $photos[6]);
327 XML::addElement($doc, $relocate, "dfrn:request", $owner['request']);
328 XML::addElement($doc, $relocate, "dfrn:confirm", $owner['confirm']);
329 XML::addElement($doc, $relocate, "dfrn:notify", $owner['notify']);
330 XML::addElement($doc, $relocate, "dfrn:poll", $owner['poll']);
331 XML::addElement($doc, $relocate, "dfrn:sitepubkey", DI::config()->get('system', 'site_pubkey'));
333 $root->appendChild($relocate);
335 return trim($doc->saveXML());
339 * Adds the header elements for the DFRN protocol
341 * @param DOMDocument $doc XML document
342 * @param array $owner Owner record
343 * @param string $authorelement Element name for the author
344 * @param string $alternatelink link to profile or category
345 * @param bool $public Is it a header for public posts?
347 * @return object XML root object
348 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
349 * @todo Find proper type-hint for returned type
351 private static function addHeader(DOMDocument $doc, array $owner, string $authorelement, string $alternatelink = "", bool $public = false)
354 if ($alternatelink == "") {
355 $alternatelink = $owner['url'];
358 $root = $doc->createElementNS(ActivityNamespace::ATOM1, 'feed');
359 $doc->appendChild($root);
361 $root->setAttribute("xmlns:thr", ActivityNamespace::THREAD);
362 $root->setAttribute("xmlns:at", ActivityNamespace::TOMB);
363 $root->setAttribute("xmlns:media", ActivityNamespace::MEDIA);
364 $root->setAttribute("xmlns:dfrn", ActivityNamespace::DFRN);
365 $root->setAttribute("xmlns:activity", ActivityNamespace::ACTIVITY);
366 $root->setAttribute("xmlns:georss", ActivityNamespace::GEORSS);
367 $root->setAttribute("xmlns:poco", ActivityNamespace::POCO);
368 $root->setAttribute("xmlns:ostatus", ActivityNamespace::OSTATUS);
369 $root->setAttribute("xmlns:statusnet", ActivityNamespace::STATUSNET);
371 XML::addElement($doc, $root, "id", DI::baseUrl()."/profile/".$owner["nick"]);
372 XML::addElement($doc, $root, "title", $owner["name"]);
374 $attributes = ["uri" => "https://friendi.ca", "version" => FRIENDICA_VERSION."-".DB_UPDATE_VERSION];
375 XML::addElement($doc, $root, "generator", FRIENDICA_PLATFORM, $attributes);
377 $attributes = ["rel" => "license", "href" => "http://creativecommons.org/licenses/by/3.0/"];
378 XML::addElement($doc, $root, "link", "", $attributes);
380 $attributes = ["rel" => "alternate", "type" => "text/html", "href" => $alternatelink];
381 XML::addElement($doc, $root, "link", "", $attributes);
385 // DFRN itself doesn't uses this. But maybe someone else wants to subscribe to the public feed.
386 OStatus::hublinks($doc, $root, $owner["nick"]);
388 $attributes = ["rel" => "salmon", "href" => DI::baseUrl()."/salmon/".$owner["nick"]];
389 XML::addElement($doc, $root, "link", "", $attributes);
391 $attributes = ["rel" => "http://salmon-protocol.org/ns/salmon-replies", "href" => DI::baseUrl()."/salmon/".$owner["nick"]];
392 XML::addElement($doc, $root, "link", "", $attributes);
394 $attributes = ["rel" => "http://salmon-protocol.org/ns/salmon-mention", "href" => DI::baseUrl()."/salmon/".$owner["nick"]];
395 XML::addElement($doc, $root, "link", "", $attributes);
398 // For backward compatibility we keep this element
399 if ($owner['page-flags'] == User::PAGE_FLAGS_COMMUNITY) {
400 XML::addElement($doc, $root, "dfrn:community", 1);
403 // The former element is replaced by this one
404 XML::addElement($doc, $root, "dfrn:account_type", $owner["account-type"]);
406 /// @todo We need a way to transmit the different page flags like "User::PAGE_FLAGS_PRVGROUP"
408 XML::addElement($doc, $root, "updated", DateTimeFormat::utcNow(DateTimeFormat::ATOM));
410 $author = self::addAuthor($doc, $owner, $authorelement, $public);
411 $root->appendChild($author);
417 * Determine the next birthday, but only if the birthday is published
418 * in the default profile. We _could_ also look for a private profile that the
419 * recipient can see, but somebody could get mad at us if they start getting
420 * public birthday greetings when they haven't made this info public.
422 * Assuming we are able to publish this info, we are then going to convert
423 * the start time from the owner's timezone to UTC.
425 * This will potentially solve the problem found with some social networks
426 * where birthdays are converted to the viewer's timezone and salutations from
427 * elsewhere in the world show up on the wrong day. We will convert it to the
428 * viewer's timezone also, but first we are going to convert it from the birthday
429 * person's timezone to GMT - so the viewer may find the birthday starting at
430 * 6:00PM the day before, but that will correspond to midnight to the birthday person.
432 * @param int $uid User id
433 * @param string $tz Time zone string, like UTC
434 * @return string Formatted birthday string
436 private static function determineNextBirthday(int $uid, string $tz): string
444 $profile = DBA::selectFirst('profile', ['dob'], ['uid' => $uid]);
445 if (DBA::isResult($profile)) {
446 $tmp_dob = substr($profile['dob'], 5);
447 if (intval($tmp_dob)) {
448 $y = DateTimeFormat::timezoneNow($tz, 'Y');
449 $bd = $y . '-' . $tmp_dob . ' 00:00';
450 $t_dob = strtotime($bd);
451 $now = strtotime(DateTimeFormat::timezoneNow($tz));
453 $bd = $y + 1 . '-' . $tmp_dob . ' 00:00';
455 $birthday = DateTimeFormat::convert($bd, 'UTC', $tz, DateTimeFormat::ATOM);
463 * Adds the author element in the header for the DFRN protocol
465 * @param DOMDocument $doc XML document
466 * @param array $owner Owner record
467 * @param string $authorelement Element name for the author
468 * @param boolean $public boolean
470 * @return \DOMElement XML author object
471 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
472 * @todo Find proper type-hints
474 private static function addAuthor(DOMDocument $doc, array $owner, string $authorelement, bool $public)
476 // Should the profile be "unsearchable" in the net? Then add the "hide" element
477 $hide = DBA::exists('profile', ['uid' => $owner['uid'], 'net-publish' => false]);
479 $author = $doc->createElement($authorelement);
481 $namdate = DateTimeFormat::utc($owner['name-date'].'+00:00', DateTimeFormat::ATOM);
482 $picdate = DateTimeFormat::utc($owner['avatar-date'].'+00:00', DateTimeFormat::ATOM);
486 if (!$public || !$hide) {
487 $attributes = ["dfrn:updated" => $namdate];
490 XML::addElement($doc, $author, "name", $owner["name"], $attributes);
491 XML::addElement($doc, $author, "uri", DI::baseUrl().'/profile/'.$owner["nickname"], $attributes);
492 XML::addElement($doc, $author, "dfrn:handle", $owner["addr"], $attributes);
494 $attributes = ["rel" => "photo", "type" => "image/jpeg",
495 "media:width" => Proxy::PIXEL_SMALL, "media:height" => Proxy::PIXEL_SMALL,
496 "href" => User::getAvatarUrl($owner, Proxy::SIZE_SMALL)];
498 if (!$public || !$hide) {
499 $attributes["dfrn:updated"] = $picdate;
502 XML::addElement($doc, $author, "link", "", $attributes);
504 $attributes["rel"] = "avatar";
505 XML::addElement($doc, $author, "link", "", $attributes);
508 XML::addElement($doc, $author, "dfrn:hide", "true");
511 // The following fields will only be generated if the data isn't meant for a public feed
516 $birthday = self::determineNextBirthday($owner['uid'], $owner['timezone']);
519 XML::addElement($doc, $author, "dfrn:birthday", $birthday);
522 // Only show contact details when we are allowed to
523 $profile = DBA::selectFirst('owner-view',
524 ['about', 'name', 'homepage', 'nickname', 'timezone', 'locality', 'region', 'country-name', 'pub_keywords', 'xmpp', 'dob'],
525 ['uid' => $owner['uid'], 'hidewall' => false]);
526 if (DBA::isResult($profile)) {
527 XML::addElement($doc, $author, "poco:displayName", $profile["name"]);
528 XML::addElement($doc, $author, "poco:updated", $namdate);
530 if (trim($profile["dob"]) > DBA::NULL_DATE) {
531 XML::addElement($doc, $author, "poco:birthday", "0000-".date("m-d", strtotime($profile["dob"])));
534 XML::addElement($doc, $author, "poco:note", $profile["about"]);
535 XML::addElement($doc, $author, "poco:preferredUsername", $profile["nickname"]);
537 XML::addElement($doc, $author, "poco:utcOffset", DateTimeFormat::timezoneNow($profile["timezone"], "P"));
539 if (trim($profile["homepage"]) != "") {
540 $urls = $doc->createElement("poco:urls");
541 XML::addElement($doc, $urls, "poco:type", "homepage");
542 XML::addElement($doc, $urls, "poco:value", $profile["homepage"]);
543 XML::addElement($doc, $urls, "poco:primary", "true");
544 $author->appendChild($urls);
547 if (trim($profile["pub_keywords"]) != "") {
548 $keywords = explode(",", $profile["pub_keywords"]);
550 foreach ($keywords as $keyword) {
551 XML::addElement($doc, $author, "poco:tags", trim($keyword));
555 if (trim($profile["xmpp"]) != "") {
556 $ims = $doc->createElement("poco:ims");
557 XML::addElement($doc, $ims, "poco:type", "xmpp");
558 XML::addElement($doc, $ims, "poco:value", $profile["xmpp"]);
559 XML::addElement($doc, $ims, "poco:primary", "true");
560 $author->appendChild($ims);
563 if (trim($profile["locality"].$profile["region"].$profile["country-name"]) != "") {
564 $element = $doc->createElement("poco:address");
566 XML::addElement($doc, $element, "poco:formatted", Profile::formatLocation($profile));
568 if (trim($profile["locality"]) != "") {
569 XML::addElement($doc, $element, "poco:locality", $profile["locality"]);
572 if (trim($profile["region"]) != "") {
573 XML::addElement($doc, $element, "poco:region", $profile["region"]);
576 if (trim($profile["country-name"]) != "") {
577 XML::addElement($doc, $element, "poco:country", $profile["country-name"]);
580 $author->appendChild($element);
588 * Adds the author elements in the "entry" elements of the DFRN protocol
590 * @param DOMDocument $doc XML document
591 * @param string $element Element name for the author
592 * @param string $contact_url Link of the contact
593 * @param array $item Item elements
595 * @return \DOMElement XML author object
596 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
597 * @todo Find proper type-hints
599 private static function addEntryAuthor(DOMDocument $doc, string $element, string $contact_url, array $item)
601 $author = $doc->createElement($element);
603 $contact = Contact::getByURLForUser($contact_url, $item["uid"], false, ['url', 'name', 'addr', 'photo']);
604 if (!empty($contact)) {
605 XML::addElement($doc, $author, "name", $contact["name"]);
606 XML::addElement($doc, $author, "uri", $contact["url"]);
607 XML::addElement($doc, $author, "dfrn:handle", $contact["addr"]);
610 /// - Check real image type and image size
611 /// - Check which of these boths elements we should use
614 "type" => "image/jpeg",
616 "media:height" => 80,
617 "href" => $contact["photo"]];
618 XML::addElement($doc, $author, "link", "", $attributes);
622 "type" => "image/jpeg",
624 "media:height" => 80,
625 "href" => $contact["photo"]];
626 XML::addElement($doc, $author, "link", "", $attributes);
633 * Adds the activity elements
635 * @param DOMDocument $doc XML document
636 * @param string $element Element name for the activity
637 * @param string $activity activity value
638 * @param int $uriid Uri-Id of the post
640 * @return \DOMElement XML activity object
641 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
642 * @todo Find proper type-hints
644 private static function createActivity(DOMDocument $doc, string $element, string $activity, int $uriid)
647 $entry = $doc->createElement($element);
649 $r = XML::parseString($activity);
655 XML::addElement($doc, $entry, "activity:object-type", $r->type);
659 XML::addElement($doc, $entry, "id", $r->id);
663 XML::addElement($doc, $entry, "title", $r->title);
667 if (substr($r->link, 0, 1) == '<') {
668 if (strstr($r->link, '&') && (! strstr($r->link, '&'))) {
669 $r->link = str_replace('&', '&', $r->link);
672 $r->link = preg_replace('/\<link(.*?)\"\>/', '<link$1"/>', $r->link);
674 // XML does need a single element as root element so we add a dummy element here
675 $data = XML::parseString("<dummy>" . $r->link . "</dummy>");
676 if (is_object($data)) {
677 foreach ($data->link as $link) {
679 foreach ($link->attributes() as $parameter => $value) {
680 $attributes[$parameter] = $value;
682 XML::addElement($doc, $entry, "link", "", $attributes);
686 $attributes = ["rel" => "alternate", "type" => "text/html", "href" => $r->link];
687 XML::addElement($doc, $entry, "link", "", $attributes);
691 XML::addElement($doc, $entry, "content", BBCode::convertForUriId($uriid, $r->content, BBCode::EXTERNAL), ["type" => "html"]);
701 * Adds the elements for attachments
703 * @param object $doc XML document
704 * @param object $root XML root
705 * @param array $item Item element
707 * @return void XML attachment object
708 * @todo Find proper type-hints
710 private static function getAttachment($doc, $root, array $item)
712 foreach (Post\Media::getByURIId($item['uri-id'], [Post\Media::DOCUMENT, Post\Media::TORRENT, Post\Media::UNKNOWN]) as $attachment) {
713 $attributes = ['rel' => 'enclosure',
714 'href' => $attachment['url'],
715 'type' => $attachment['mimetype']];
717 if (!empty($attachment['size'])) {
718 $attributes['length'] = intval($attachment['size']);
720 if (!empty($attachment['description'])) {
721 $attributes['title'] = $attachment['description'];
724 XML::addElement($doc, $root, 'link', '', $attributes);
729 * Adds the "entry" elements for the DFRN protocol
731 * @param DOMDocument $doc XML document
732 * @param string $type "text" or "html"
733 * @param array $item Item element
734 * @param array $owner Owner record
735 * @param bool $comment Trigger the sending of the "comment" element
736 * @param int $cid Contact ID of the recipient
737 * @param bool $single If set, the entry is created as an XML document with a single "entry" element
739 * @return null|\DOMElement XML entry object
740 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
741 * @throws \ImagickException
742 * @todo Find proper type-hints
744 private static function entry(DOMDocument $doc, string $type, array $item, array $owner, bool $comment = false, int $cid = 0, bool $single = false)
748 if (!$item['parent']) {
749 Logger::notice('Item without parent found.', ['type' => $type, 'item' => $item]);
753 if ($item['deleted']) {
754 $attributes = ["ref" => $item['uri'], "when" => DateTimeFormat::utc($item['edited'] . '+00:00', DateTimeFormat::ATOM)];
755 return XML::createElement($doc, "at:deleted-entry", "", $attributes);
759 $entry = $doc->createElement("entry");
761 $entry = $doc->createElementNS(ActivityNamespace::ATOM1, 'entry');
762 $doc->appendChild($entry);
764 $entry->setAttribute("xmlns:thr", ActivityNamespace::THREAD);
765 $entry->setAttribute("xmlns:at", ActivityNamespace::TOMB);
766 $entry->setAttribute("xmlns:media", ActivityNamespace::MEDIA);
767 $entry->setAttribute("xmlns:dfrn", ActivityNamespace::DFRN);
768 $entry->setAttribute("xmlns:activity", ActivityNamespace::ACTIVITY);
769 $entry->setAttribute("xmlns:georss", ActivityNamespace::GEORSS);
770 $entry->setAttribute("xmlns:poco", ActivityNamespace::POCO);
771 $entry->setAttribute("xmlns:ostatus", ActivityNamespace::OSTATUS);
772 $entry->setAttribute("xmlns:statusnet", ActivityNamespace::STATUSNET);
775 $body = Post\Media::addAttachmentsToBody($item['uri-id'], $item['body'] ?? '');
777 if ($item['private'] == Item::PRIVATE) {
778 $body = Item::fixPrivatePhotos($body, $owner['uid'], $item, $cid);
781 // Remove the abstract element. It is only locally important.
782 $body = BBCode::stripAbstract($body);
785 if ($type == 'html') {
788 if ($item['title'] != "") {
789 $htmlbody = "[b]" . $item['title'] . "[/b]\n\n" . $htmlbody;
792 $htmlbody = BBCode::convertForUriId($item['uri-id'], $htmlbody, BBCode::ACTIVITYPUB);
795 $author = self::addEntryAuthor($doc, "author", $item["author-link"], $item);
796 $entry->appendChild($author);
798 $dfrnowner = self::addEntryAuthor($doc, "dfrn:owner", $item["owner-link"], $item);
799 $entry->appendChild($dfrnowner);
801 if ($item['gravity'] != GRAVITY_PARENT) {
802 $parent = Post::selectFirst(['guid', 'plink'], ['uri' => $item['thr-parent'], 'uid' => $item['uid']]);
803 if (DBA::isResult($parent)) {
804 $attributes = ["ref" => $item['thr-parent'], "type" => "text/html",
805 "href" => $parent['plink'],
806 "dfrn:diaspora_guid" => $parent['guid']];
807 XML::addElement($doc, $entry, "thr:in-reply-to", "", $attributes);
811 // Add conversation data. This is used for OStatus
812 $conversation_href = DI::baseUrl()."/display/".$item["parent-guid"];
813 $conversation_uri = $conversation_href;
815 if (isset($parent_item)) {
816 $conversation = DBA::selectFirst('conversation', ['conversation-uri', 'conversation-href'], ['item-uri' => $item['thr-parent']]);
817 if (DBA::isResult($conversation)) {
818 if ($conversation['conversation-uri'] != '') {
819 $conversation_uri = $conversation['conversation-uri'];
821 if ($conversation['conversation-href'] != '') {
822 $conversation_href = $conversation['conversation-href'];
828 "href" => $conversation_href,
829 "ref" => $conversation_uri];
831 XML::addElement($doc, $entry, "ostatus:conversation", $conversation_uri, $attributes);
833 XML::addElement($doc, $entry, "id", $item["uri"]);
834 XML::addElement($doc, $entry, "title", $item["title"]);
836 XML::addElement($doc, $entry, "published", DateTimeFormat::utc($item["created"] . "+00:00", DateTimeFormat::ATOM));
837 XML::addElement($doc, $entry, "updated", DateTimeFormat::utc($item["edited"] . "+00:00", DateTimeFormat::ATOM));
839 // "dfrn:env" is used to read the content
840 XML::addElement($doc, $entry, "dfrn:env", Strings::base64UrlEncode($body, true));
842 // The "content" field is not read by the receiver. We could remove it when the type is "text"
843 // We keep it at the moment, maybe there is some old version that doesn't read "dfrn:env"
844 XML::addElement($doc, $entry, "content", (($type == 'html') ? $htmlbody : $body), ["type" => $type]);
846 // We save this value in "plink". Maybe we should read it from there as well?
852 ["rel" => "alternate", "type" => "text/html",
853 "href" => DI::baseUrl() . "/display/" . $item["guid"]]
856 // "comment-allow" is some old fashioned stuff for old Friendica versions.
857 // It is included in the rewritten code for completeness
859 XML::addElement($doc, $entry, "dfrn:comment-allow", 1);
862 if ($item['location']) {
863 XML::addElement($doc, $entry, "dfrn:location", $item['location']);
866 if ($item['coord']) {
867 XML::addElement($doc, $entry, "georss:point", $item['coord']);
870 if ($item['private']) {
871 // Friendica versions prior to 2020.3 can't handle "unlisted" properly. So we can only transmit public and private
872 XML::addElement($doc, $entry, "dfrn:private", ($item['private'] == Item::PRIVATE ? Item::PRIVATE : Item::PUBLIC));
873 XML::addElement($doc, $entry, "dfrn:unlisted", $item['private'] == Item::UNLISTED);
876 if ($item['extid']) {
877 XML::addElement($doc, $entry, "dfrn:extid", $item['extid']);
880 if ($item['post-type'] == Item::PT_PAGE) {
881 XML::addElement($doc, $entry, "dfrn:bookmark", "true");
885 XML::addElement($doc, $entry, "statusnet:notice_info", "", ["local_id" => $item['id'], "source" => $item['app']]);
888 XML::addElement($doc, $entry, "dfrn:diaspora_guid", $item["guid"]);
890 // The signed text contains the content in Markdown, the sender handle and the signatur for the content
891 // It is needed for relayed comments to Diaspora.
892 if ($item['signed_text']) {
893 $sign = base64_encode(json_encode(['signed_text' => $item['signed_text'],'signature' => '','signer' => '']));
894 XML::addElement($doc, $entry, "dfrn:diaspora_signature", $sign);
897 XML::addElement($doc, $entry, "activity:verb", self::constructVerb($item));
899 if ($item['object-type'] != "") {
900 XML::addElement($doc, $entry, "activity:object-type", $item['object-type']);
901 } elseif ($item['gravity'] == GRAVITY_PARENT) {
902 XML::addElement($doc, $entry, "activity:object-type", Activity\ObjectType::NOTE);
904 XML::addElement($doc, $entry, "activity:object-type", Activity\ObjectType::COMMENT);
907 $actobj = self::createActivity($doc, "activity:object", $item['object'], $item['uri-id']);
909 $entry->appendChild($actobj);
912 $actarg = self::createActivity($doc, "activity:target", $item['target'], $item['uri-id']);
914 $entry->appendChild($actarg);
917 $tags = Tag::getByURIId($item['uri-id']);
920 foreach ($tags as $tag) {
921 if (($type != 'html') || ($tag['type'] == Tag::HASHTAG)) {
922 XML::addElement($doc, $entry, "category", "", ["scheme" => "X-DFRN:" . Tag::TAG_CHARACTER[$tag['type']] . ":" . $tag['url'], "term" => $tag['name']]);
924 if ($tag['type'] != Tag::HASHTAG) {
925 $mentioned[$tag['url']] = $tag['url'];
930 foreach ($mentioned as $mention) {
931 $condition = ['uid' => $owner["uid"], 'nurl' => Strings::normaliseLink($mention)];
932 $contact = DBA::selectFirst('contact', ['contact-type'], $condition);
934 if (DBA::isResult($contact) && ($contact['contact-type'] == Contact::TYPE_COMMUNITY)) {
940 ["rel" => "mentioned",
941 "ostatus:object-type" => Activity\ObjectType::GROUP,
950 ["rel" => "mentioned",
951 "ostatus:object-type" => Activity\ObjectType::PERSON,
957 self::getAttachment($doc, $entry, $item);
963 * Transmits atom content to the contacts via the Diaspora transport layer
965 * @param array $owner Owner record
966 * @param array $contact Contact record of the receiver
967 * @param string $atom Content that will be transmitted
968 * @param bool $public_batch
969 * @return int Deliver status. Negative values mean an error.
970 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
971 * @throws \ImagickException
973 public static function transmit(array $owner, array $contact, string $atom, bool $public_batch = false)
975 if (!$public_batch) {
976 if (empty($contact['addr'])) {
977 Logger::notice('Empty contact handle for ' . $contact['id'] . ' - ' . $contact['url'] . ' - trying to update it.');
978 if (Contact::updateFromProbe($contact['id'])) {
979 $new_contact = DBA::selectFirst('contact', ['addr'], ['id' => $contact['id']]);
980 $contact['addr'] = $new_contact['addr'];
983 if (empty($contact['addr'])) {
984 Logger::notice('Unable to find contact handle for ' . $contact['id'] . ' - ' . $contact['url']);
989 $fcontact = FContact::getByURL($contact['addr']);
990 if (empty($fcontact)) {
991 Logger::notice('Unable to find contact details for ' . $contact['id'] . ' - ' . $contact['addr']);
994 $pubkey = $fcontact['pubkey'];
999 $envelope = Diaspora::buildMessage($atom, $owner, $contact, $owner['uprvkey'], $pubkey, $public_batch);
1001 // Create the endpoint for public posts. This is some WIP and should later be added to the probing
1002 if ($public_batch && empty($contact["batch"])) {
1003 $parts = parse_url($contact["notify"]);
1004 $path_parts = explode('/', $parts['path']);
1005 array_pop($path_parts);
1006 $parts['path'] = implode('/', $path_parts);
1007 $contact["batch"] = Network::unparseURL($parts);
1010 $dest_url = ($public_batch ? $contact["batch"] : $contact["notify"]);
1012 if (empty($dest_url)) {
1013 Logger::info('Empty destination', ['public' => $public_batch, 'contact' => $contact]);
1017 $content_type = ($public_batch ? "application/magic-envelope+xml" : "application/json");
1019 $postResult = DI::httpClient()->post($dest_url, $envelope, ['Content-Type' => $content_type]);
1020 $xml = $postResult->getBody();
1022 $curl_stat = $postResult->getReturnCode();
1023 if (empty($curl_stat) || empty($xml)) {
1024 Logger::notice('Empty answer from ' . $contact['id'] . ' - ' . $dest_url);
1025 return -9; // timed out
1028 if (($curl_stat == 503) && $postResult->inHeader('retry-after')) {
1032 if (strpos($xml, '<?xml') === false) {
1033 Logger::notice('No valid XML returned from ' . $contact['id'] . ' - ' . $dest_url);
1034 Logger::debug('Returned XML: ' . $xml);
1038 $res = XML::parseString($xml);
1040 if (empty($res->status)) {
1044 if (!empty($res->message)) {
1045 Logger::info('Transmit to ' . $dest_url . ' returned status '.$res->status.' - '.$res->message);
1048 return intval($res->status);
1052 * Fetch the author data from head or entry items
1054 * @param \DOMXPath $xpath XPath object
1055 * @param \DOMNode $context In which context should the data be searched
1056 * @param array $importer Record of the importer user mixed with contact of the content
1057 * @param string $element Element name from which the data is fetched
1058 * @param bool $onlyfetch Should the data only be fetched or should it update the contact record as well
1059 * @param string $xml optional, default empty
1061 * @return array Relevant data of the author
1062 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1063 * @throws \ImagickException
1064 * @todo Find good type-hints for all parameter
1066 private static function fetchauthor(\DOMXPath $xpath, \DOMNode $context, array $importer, string $element, bool $onlyfetch, string $xml = ""): array
1069 $author["name"] = XML::getFirstNodeValue($xpath, $element."/atom:name/text()", $context);
1070 $author["link"] = XML::getFirstNodeValue($xpath, $element."/atom:uri/text()", $context);
1072 $fields = ['id', 'uid', 'url', 'network', 'avatar-date', 'avatar', 'name-date', 'uri-date', 'addr',
1073 'name', 'nick', 'about', 'location', 'keywords', 'xmpp', 'bdyear', 'bd', 'hidden', 'contact-type'];
1074 $condition = ["`uid` = ? AND `nurl` = ? AND `network` != ? AND NOT `pending` AND NOT `blocked`",
1075 $importer["importer_uid"], Strings::normaliseLink($author["link"]), Protocol::STATUSNET];
1077 if ($importer['account-type'] != User::ACCOUNT_TYPE_COMMUNITY) {
1078 $condition = DBA::mergeConditions($condition, ['rel' => [Contact::SHARING, Contact::FRIEND]]);
1081 $contact_old = DBA::selectFirst('contact', $fields, $condition);
1083 if (DBA::isResult($contact_old)) {
1084 $author["contact-id"] = $contact_old["id"];
1085 $author["network"] = $contact_old["network"];
1087 Logger::info('Contact not found', ['condition' => $condition]);
1089 $author["contact-unknown"] = true;
1090 $contact = Contact::getByURL($author["link"], null, ["id", "network"]);
1091 $author["contact-id"] = $contact["id"] ?? $importer["id"];
1092 $author["network"] = $contact["network"] ?? $importer["network"];
1096 // Until now we aren't serving different sizes - but maybe later
1098 /// @todo check if "avatar" or "photo" would be the best field in the specification
1099 $avatars = $xpath->query($element . "/atom:link[@rel='avatar']", $context);
1100 foreach ($avatars as $avatar) {
1103 foreach ($avatar->attributes as $attributes) {
1104 /// @TODO Rewrite these similar if() to one switch
1105 if ($attributes->name == "href") {
1106 $href = $attributes->textContent;
1108 if ($attributes->name == "width") {
1109 $width = $attributes->textContent;
1111 if ($attributes->name == "updated") {
1112 $author["avatar-date"] = $attributes->textContent;
1115 if (($width > 0) && ($href != "")) {
1116 $avatarlist[$width] = $href;
1120 if (count($avatarlist) > 0) {
1121 krsort($avatarlist);
1122 $author["avatar"] = current($avatarlist);
1125 if (empty($author['avatar']) && !empty($author['link'])) {
1126 $cid = Contact::getIdForURL($author['link'], 0);
1128 $contact = DBA::selectFirst('contact', ['avatar'], ['id' => $cid]);
1129 if (DBA::isResult($contact)) {
1130 $author['avatar'] = $contact['avatar'];
1135 if (empty($author['avatar'])) {
1136 Logger::notice('Empty author: ' . $xml);
1137 $author['avatar'] = '';
1140 if (DBA::isResult($contact_old) && !$onlyfetch) {
1141 Logger::info("Check if contact details for contact " . $contact_old["id"] . " (" . $contact_old["nick"] . ") have to be updated.");
1143 $poco = ["url" => $contact_old["url"], "network" => $contact_old["network"]];
1145 // When was the last change to name or uri?
1146 $name_element = $xpath->query($element . "/atom:name", $context)->item(0);
1147 foreach ($name_element->attributes as $attributes) {
1148 if ($attributes->name == "updated") {
1149 $poco["name-date"] = $attributes->textContent;
1153 $link_element = $xpath->query($element . "/atom:link", $context)->item(0);
1154 foreach ($link_element->attributes as $attributes) {
1155 if ($attributes->name == "updated") {
1156 $poco["uri-date"] = $attributes->textContent;
1160 // Update contact data
1161 $value = XML::getFirstNodeValue($xpath, $element . "/dfrn:handle/text()", $context);
1163 $poco["addr"] = $value;
1166 $value = XML::getFirstNodeValue($xpath, $element . "/poco:displayName/text()", $context);
1168 $poco["name"] = $value;
1171 $value = XML::getFirstNodeValue($xpath, $element . "/poco:preferredUsername/text()", $context);
1173 $poco["nick"] = $value;
1176 $value = XML::getFirstNodeValue($xpath, $element . "/poco:note/text()", $context);
1178 $poco["about"] = $value;
1181 $value = XML::getFirstNodeValue($xpath, $element . "/poco:address/poco:formatted/text()", $context);
1183 $poco["location"] = $value;
1186 /// @todo Only search for elements with "poco:type" = "xmpp"
1187 $value = XML::getFirstNodeValue($xpath, $element . "/poco:ims/poco:value/text()", $context);
1189 $poco["xmpp"] = $value;
1192 /// @todo Add support for the following fields that we don't support by now in the contact table:
1193 /// - poco:utcOffset
1199 // If the "hide" element is present then the profile isn't searchable.
1200 $hide = intval(XML::getFirstNodeValue($xpath, $element . "/dfrn:hide/text()", $context) == "true");
1202 Logger::info("Hidden status for contact " . $contact_old["url"] . ": " . $hide);
1204 // If the contact isn't searchable then set the contact to "hidden".
1205 // Problem: This can be manually overridden by the user.
1207 $contact_old["hidden"] = true;
1210 // Save the keywords into the contact table
1212 $tagelements = $xpath->evaluate($element . "/poco:tags/text()", $context);
1213 foreach ($tagelements as $tag) {
1214 $tags[$tag->nodeValue] = $tag->nodeValue;
1218 $poco["keywords"] = implode(", ", $tags);
1221 // "dfrn:birthday" contains the birthday converted to UTC
1222 $birthday = XML::getFirstNodeValue($xpath, $element . "/dfrn:birthday/text()", $context);
1224 $birthday_date = new \DateTime($birthday);
1225 if ($birthday_date > new \DateTime()) {
1226 $poco["bdyear"] = $birthday_date->format("Y");
1228 } catch (\Exception $e) {
1232 // "poco:birthday" is the birthday in the format "yyyy-mm-dd"
1233 $value = XML::getFirstNodeValue($xpath, $element . "/poco:birthday/text()", $context);
1235 if (!in_array($value, ["", "0000-00-00", DBA::NULL_DATE])) {
1236 $bdyear = date("Y");
1237 $value = str_replace(["0000", "0001"], $bdyear, $value);
1239 if (strtotime($value) < time()) {
1240 $value = str_replace($bdyear, $bdyear + 1, $value);
1243 $poco["bd"] = $value;
1246 $contact = array_merge($contact_old, $poco);
1248 if ($contact_old["bdyear"] != $contact["bdyear"]) {
1249 Event::createBirthday($contact, $birthday);
1252 $fields = ['name' => $contact['name'], 'nick' => $contact['nick'], 'about' => $contact['about'],
1253 'location' => $contact['location'], 'addr' => $contact['addr'], 'keywords' => $contact['keywords'],
1254 'bdyear' => $contact['bdyear'], 'bd' => $contact['bd'], 'hidden' => $contact['hidden'],
1255 'xmpp' => $contact['xmpp'], 'name-date' => DateTimeFormat::utc($contact['name-date']),
1256 'unsearchable' => $contact['hidden'], 'uri-date' => DateTimeFormat::utc($contact['uri-date'])];
1258 Contact::update($fields, ['id' => $contact['id'], 'network' => $contact['network']], $contact_old);
1260 // Update the public contact. Don't set the "hidden" value, this is used differently for public contacts
1261 unset($fields['hidden']);
1262 $condition = ['uid' => 0, 'nurl' => Strings::normaliseLink($contact_old['url'])];
1263 Contact::update($fields, $condition, true);
1265 Contact::updateAvatar($contact['id'], $author['avatar']);
1267 $pcid = Contact::getIdForURL($contact_old['url']);
1268 if (!empty($pcid)) {
1269 Contact::updateAvatar($pcid, $author['avatar']);
1277 * Transforms activity objects into an XML string
1279 * @param object $xpath XPath object
1280 * @param object $activity Activity object
1281 * @param string $element element name
1283 * @return string XML string
1284 * @todo Find good type-hints for all parameter
1286 private static function transformActivity($xpath, $activity, string $element): string
1288 if (!is_object($activity)) {
1292 $obj_doc = new DOMDocument("1.0", "utf-8");
1293 $obj_doc->formatOutput = true;
1295 $obj_element = $obj_doc->createElementNS( ActivityNamespace::ATOM1, $element);
1297 $activity_type = $xpath->query("activity:object-type/text()", $activity)->item(0)->nodeValue;
1298 XML::addElement($obj_doc, $obj_element, "type", $activity_type);
1300 $id = $xpath->query("atom:id", $activity)->item(0);
1301 if (is_object($id)) {
1302 $obj_element->appendChild($obj_doc->importNode($id, true));
1305 $title = $xpath->query("atom:title", $activity)->item(0);
1306 if (is_object($title)) {
1307 $obj_element->appendChild($obj_doc->importNode($title, true));
1310 $links = $xpath->query("atom:link", $activity);
1311 if (is_object($links)) {
1312 foreach ($links as $link) {
1313 $obj_element->appendChild($obj_doc->importNode($link, true));
1317 $content = $xpath->query("atom:content", $activity)->item(0);
1318 if (is_object($content)) {
1319 $obj_element->appendChild($obj_doc->importNode($content, true));
1322 $obj_doc->appendChild($obj_element);
1324 $objxml = $obj_doc->saveXML($obj_element);
1326 /// @todo This isn't totally clean. We should find a way to transform the namespaces
1327 $objxml = str_replace("<".$element.' xmlns="http://www.w3.org/2005/Atom">', "<".$element.">", $objxml);
1332 * Processes the mail elements
1334 * @param object $xpath XPath object
1335 * @param object $mail mail elements
1336 * @param array $importer Record of the importer user mixed with contact of the content
1338 * @throws \Exception
1339 * @todo Find good type-hints for all parameter
1341 private static function processMail($xpath, $mail, array $importer)
1343 Logger::notice("Processing mails");
1346 $msg["uid"] = $importer["importer_uid"];
1347 $msg["from-name"] = XML::getFirstValue($xpath, "dfrn:sender/dfrn:name/text()", $mail);
1348 $msg["from-url"] = XML::getFirstValue($xpath, "dfrn:sender/dfrn:uri/text()", $mail);
1349 $msg["from-photo"] = XML::getFirstValue($xpath, "dfrn:sender/dfrn:avatar/text()", $mail);
1350 $msg["contact-id"] = $importer["id"];
1351 $msg["uri"] = XML::getFirstValue($xpath, "dfrn:id/text()", $mail);
1352 $msg["parent-uri"] = XML::getFirstValue($xpath, "dfrn:in-reply-to/text()", $mail);
1353 $msg["created"] = DateTimeFormat::utc(XML::getFirstValue($xpath, "dfrn:sentdate/text()", $mail));
1354 $msg["title"] = XML::getFirstValue($xpath, "dfrn:subject/text()", $mail);
1355 $msg["body"] = XML::getFirstValue($xpath, "dfrn:content/text()", $mail);
1361 * Processes the suggestion elements
1363 * @param object $xpath XPath object
1364 * @param object $suggestion suggestion elements
1365 * @param array $importer Record of the importer user mixed with contact of the content
1367 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1368 * @todo Find good type-hints for all parameter
1370 private static function processSuggestion($xpath, $suggestion, array $importer)
1372 Logger::notice('Processing suggestions');
1374 $url = $xpath->evaluate('string(dfrn:url[1]/text())', $suggestion);
1375 $cid = Contact::getIdForURL($url);
1376 $note = $xpath->evaluate('string(dfrn:note[1]/text())', $suggestion);
1378 return self::addSuggestion($importer['importer_uid'], $cid, $importer['id'], $note);
1382 * Suggest a given contact to a given user from a given contact
1384 * @param integer $uid
1385 * @param integer $cid
1386 * @param integer $from_cid
1387 * @return bool Was the adding successful?
1389 private static function addSuggestion(int $uid, int $cid, int $from_cid, string $note = ''): bool
1391 $owner = User::getOwnerDataById($uid);
1392 $contact = Contact::getById($cid);
1393 $from_contact = Contact::getById($from_cid);
1395 if (DBA::exists('contact', ['nurl' => Strings::normaliseLink($contact['url']), 'uid' => $uid])) {
1399 // Quit if we already have an introduction for this person
1400 if (DI::intro()->suggestionExistsForUser($cid, $uid)) {
1405 $suggest['uid'] = $uid;
1406 $suggest['cid'] = $from_cid;
1407 $suggest['url'] = $contact['url'];
1408 $suggest['name'] = $contact['name'];
1409 $suggest['photo'] = $contact['photo'];
1410 $suggest['request'] = $contact['request'];
1411 $suggest['title'] = '';
1412 $suggest['body'] = $note;
1414 DI::intro()->save(DI::introFactory()->createNew(
1422 DI::notify()->createFromArray([
1423 'type' => Notification\Type::SUGGEST,
1424 'otype' => Notification\ObjectType::INTRO,
1425 'verb' => Activity::REQ_FRIEND,
1426 'uid' => $owner['uid'],
1427 'cid' => $from_contact['uid'],
1429 'link' => DI::baseUrl().'/notifications/intros',
1436 * Processes the relocation elements
1438 * @param object $xpath XPath object
1439 * @param object $relocation relocation elements
1440 * @param array $importer Record of the importer user mixed with contact of the content
1442 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1443 * @throws \ImagickException
1444 * @todo Find good type-hints for all parameter
1446 private static function processRelocation($xpath, $relocation, array $importer): bool
1448 Logger::notice("Processing relocations");
1450 /// @TODO Rewrite this to one statement
1452 $relocate["uid"] = $importer["importer_uid"];
1453 $relocate["cid"] = $importer["id"];
1454 $relocate["url"] = $xpath->query("dfrn:url/text()", $relocation)->item(0)->nodeValue;
1455 $relocate["addr"] = $xpath->query("dfrn:addr/text()", $relocation)->item(0)->nodeValue;
1456 $relocate["name"] = $xpath->query("dfrn:name/text()", $relocation)->item(0)->nodeValue;
1457 $relocate["avatar"] = $xpath->query("dfrn:avatar/text()", $relocation)->item(0)->nodeValue;
1458 $relocate["photo"] = $xpath->query("dfrn:photo/text()", $relocation)->item(0)->nodeValue;
1459 $relocate["thumb"] = $xpath->query("dfrn:thumb/text()", $relocation)->item(0)->nodeValue;
1460 $relocate["micro"] = $xpath->query("dfrn:micro/text()", $relocation)->item(0)->nodeValue;
1461 $relocate["request"] = $xpath->query("dfrn:request/text()", $relocation)->item(0)->nodeValue;
1462 $relocate["confirm"] = $xpath->query("dfrn:confirm/text()", $relocation)->item(0)->nodeValue;
1463 $relocate["notify"] = $xpath->query("dfrn:notify/text()", $relocation)->item(0)->nodeValue;
1464 $relocate["poll"] = $xpath->query("dfrn:poll/text()", $relocation)->item(0)->nodeValue;
1465 $relocate["sitepubkey"] = $xpath->query("dfrn:sitepubkey/text()", $relocation)->item(0)->nodeValue;
1467 if (($relocate["avatar"] == "") && ($relocate["photo"] != "")) {
1468 $relocate["avatar"] = $relocate["photo"];
1471 if ($relocate["addr"] == "") {
1472 $relocate["addr"] = preg_replace("=(https?://)(.*)/profile/(.*)=ism", "$3@$2", $relocate["url"]);
1476 $old = Contact::selectFirst(['photo', 'url'], ['id' => $importer["id"], 'uid' => $importer["importer_uid"]]);
1478 if (!DBA::isResult($old)) {
1479 Logger::notice("Query failed to execute, no result returned in " . __FUNCTION__);
1483 // Update the contact table. We try to find every entry.
1484 $fields = ['name' => $relocate["name"], 'avatar' => $relocate["avatar"],
1485 'url' => $relocate["url"], 'nurl' => Strings::normaliseLink($relocate["url"]),
1486 'addr' => $relocate["addr"], 'request' => $relocate["request"],
1487 'confirm' => $relocate["confirm"], 'notify' => $relocate["notify"],
1488 'poll' => $relocate["poll"], 'site-pubkey' => $relocate["sitepubkey"]];
1489 $condition = ["(`id` = ?) OR (`nurl` = ?)", $importer["id"], Strings::normaliseLink($old["url"])];
1491 Contact::update($fields, $condition);
1493 Contact::updateAvatar($importer["id"], $relocate["avatar"], true);
1495 Logger::notice('Contacts are updated.');
1498 /// merge with current record, current contents have priority
1499 /// update record, set url-updated
1500 /// update profile photos
1501 /// schedule a scan?
1508 * @param array $current the current item record
1509 * @param array $item the new item record
1510 * @param array $importer Record of the importer user mixed with contact of the content
1511 * @param int $entrytype Is it a toplevel entry, a comment or a relayed comment?
1513 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1514 * @todo set proper type-hints (array?)
1516 private static function updateContent(array $current, array $item, array $importer, int $entrytype)
1520 if (self::isEditedTimestampNewer($current, $item)) {
1521 // do not accept (ignore) an earlier edit than one we currently have.
1522 if (DateTimeFormat::utc($item["edited"]) < $current["edited"]) {
1526 $fields = ['title' => $item['title'] ?? '', 'body' => $item['body'] ?? '',
1527 'changed' => DateTimeFormat::utcNow(),
1528 'edited' => DateTimeFormat::utc($item["edited"])];
1530 $condition = ["`uri` = ? AND `uid` IN (0, ?)", $item["uri"], $importer["importer_uid"]];
1531 Item::update($fields, $condition);
1539 * Detects the entry type of the item
1541 * @param array $importer Record of the importer user mixed with contact of the content
1542 * @param array $item the new item record
1544 * @return int Is it a toplevel entry, a comment or a relayed comment?
1545 * @throws \Exception
1546 * @todo set proper type-hints (array?)
1548 private static function getEntryType(array $importer, array $item): int
1550 if ($item["thr-parent"] != $item["uri"]) {
1553 if ($importer['account-type'] == User::ACCOUNT_TYPE_COMMUNITY) {
1556 Logger::notice("possible community action");
1558 $sql_extra = " AND `self` AND `wall`";
1561 // was the top-level post for this action written by somebody on this site?
1562 // Specifically, the recipient?
1563 $parent = Post::selectFirst(['wall'],
1564 ["`uri` = ? AND `uid` = ?" . $sql_extra, $item["thr-parent"], $importer["importer_uid"]]);
1566 $is_a_remote_action = DBA::isResult($parent);
1568 if ($is_a_remote_action) {
1569 return DFRN::REPLY_RC;
1574 return DFRN::TOP_LEVEL;
1581 * @param array $item The new item record
1582 * @param array $importer Record of the importer user mixed with contact of the content
1584 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1585 * @todo set proper type-hints (array?)
1587 private static function doPoke(array $item, array $importer)
1589 $verb = urldecode(substr($item["verb"], strpos($item["verb"], "#")+1));
1593 $xo = XML::parseString($item["object"]);
1595 if (($xo->type == Activity\ObjectType::PERSON) && ($xo->id)) {
1596 // somebody was poked/prodded. Was it me?
1598 foreach ($xo->link as $l) {
1599 $atts = $l->attributes();
1600 switch ($atts["rel"]) {
1602 $Blink = $atts["href"];
1609 if ($Blink && Strings::compareLink($Blink, DI::baseUrl() . "/profile/" . $importer["nickname"])) {
1610 $author = DBA::selectFirst('contact', ['id', 'name', 'thumb', 'url'], ['id' => $item['author-id']]);
1612 $parent = Post::selectFirst(['id'], ['uri' => $item['thr-parent'], 'uid' => $importer["importer_uid"]]);
1613 $item['parent'] = $parent['id'];
1615 // send a notification
1616 DI::notify()->createFromArray(
1618 "type" => Notification\Type::POKE,
1619 "otype" => Notification\ObjectType::PERSON,
1620 "activity" => $verb,
1621 "verb" => $item["verb"],
1622 "uid" => $importer["importer_uid"],
1623 "cid" => $author["id"],
1625 "link" => DI::baseUrl() . "/display/" . urlencode($item['guid']),
1633 * Processes several actions, depending on the verb
1635 * @param int $entrytype Is it a toplevel entry, a comment or a relayed comment?
1636 * @param array $importer Record of the importer user mixed with contact of the content
1637 * @param array $item the new item record
1638 * @param bool $is_like Is the verb a "like"?
1640 * @return bool Should the processing of the entries be continued?
1641 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1642 * @todo set proper type-hints (array?)
1644 private static function processVerbs(int $entrytype, array $importer, array &$item, bool &$is_like)
1646 Logger::info("Process verb ".$item["verb"]." and object-type ".$item["object-type"]." for entrytype ".$entrytype);
1648 if (($entrytype == DFRN::TOP_LEVEL) && !empty($importer['id'])) {
1649 // The filling of the the "contact" variable is done for legcy reasons
1650 // The functions below are partly used by ostatus.php as well - where we have this variable
1651 $contact = Contact::selectFirst([], ['id' => $importer['id']]);
1653 $activity = DI::activity();
1655 // Big question: Do we need these functions? They were part of the "consume_feed" function.
1656 // This function once was responsible for DFRN and OStatus.
1657 if ($activity->match($item["verb"], Activity::FOLLOW)) {
1658 Logger::notice("New follower");
1659 Contact::addRelationship($importer, $contact, $item);
1662 if ($activity->match($item["verb"], Activity::UNFOLLOW)) {
1663 Logger::notice("Lost follower");
1664 Contact::removeFollower($contact);
1667 if ($activity->match($item["verb"], Activity::REQ_FRIEND)) {
1668 Logger::notice("New friend request");
1669 Contact::addRelationship($importer, $contact, $item, true);
1672 if ($activity->match($item["verb"], Activity::UNFRIEND)) {
1673 Logger::notice("Lost sharer");
1674 Contact::removeSharer($contact);
1678 if (($item["verb"] == Activity::LIKE)
1679 || ($item["verb"] == Activity::DISLIKE)
1680 || ($item["verb"] == Activity::ATTEND)
1681 || ($item["verb"] == Activity::ATTENDNO)
1682 || ($item["verb"] == Activity::ATTENDMAYBE)
1683 || ($item["verb"] == Activity::ANNOUNCE)
1686 $item["gravity"] = GRAVITY_ACTIVITY;
1687 // only one like or dislike per person
1688 // split into two queries for performance issues
1689 $condition = ['uid' => $item["uid"], 'author-id' => $item["author-id"], 'gravity' => GRAVITY_ACTIVITY,
1690 'verb' => $item['verb'], 'parent-uri' => $item['thr-parent']];
1691 if (Post::exists($condition)) {
1695 $condition = ['uid' => $item["uid"], 'author-id' => $item["author-id"], 'gravity' => GRAVITY_ACTIVITY,
1696 'verb' => $item['verb'], 'thr-parent' => $item['thr-parent']];
1697 if (Post::exists($condition)) {
1701 // The owner of an activity must be the author
1702 $item["owner-name"] = $item["author-name"];
1703 $item["owner-link"] = $item["author-link"];
1704 $item["owner-avatar"] = $item["author-avatar"];
1705 $item["owner-id"] = $item["author-id"];
1710 if (($item["verb"] == Activity::TAG) && ($item["object-type"] == Activity\ObjectType::TAGTERM)) {
1711 $xo = XML::parseString($item["object"]);
1712 $xt = XML::parseString($item["target"]);
1714 if ($xt->type == Activity\ObjectType::NOTE) {
1715 $item_tag = Post::selectFirst(['id', 'uri-id'], ['uri' => $xt->id, 'uid' => $importer["importer_uid"]]);
1717 if (!DBA::isResult($item_tag)) {
1718 Logger::notice("Query failed to execute, no result returned in " . __FUNCTION__);
1722 // extract tag, if not duplicate, add to parent item
1724 Tag::store($item_tag['uri-id'], Tag::HASHTAG, $xo->content);
1733 * Processes the link elements
1735 * @param object $links link elements
1736 * @param array $item the item record
1738 * @todo set proper type-hints
1740 private static function parseLinks($links, array &$item)
1747 foreach ($links as $link) {
1748 foreach ($link->attributes as $attributes) {
1749 switch ($attributes->name) {
1750 case "href" : $href = $attributes->textContent; break;
1751 case "rel" : $rel = $attributes->textContent; break;
1752 case "type" : $type = $attributes->textContent; break;
1753 case "length": $length = $attributes->textContent; break;
1754 case "title" : $title = $attributes->textContent; break;
1757 if (($rel != "") && ($href != "")) {
1760 $item["plink"] = $href;
1763 Post\Media::insert(['uri-id' => $item['uri-id'], 'type' => Post\Media::DOCUMENT,
1764 'url' => $href, 'mimetype' => $type, 'size' => $length, 'description' => $title]);
1772 * Checks if an incoming message is wanted
1774 * @param array $item
1775 * @param array $imporer
1776 * @return boolean Is the message wanted?
1778 private static function isSolicitedMessage(array $item, array $importer): bool
1780 if (DBA::exists('contact', ["`nurl` = ? AND `uid` != ? AND `rel` IN (?, ?)",
1781 Strings::normaliseLink($item["author-link"]), 0, Contact::FRIEND, Contact::SHARING])) {
1782 Logger::debug('Author has got followers - accepted', ['uri-id' => $item['uri-id'], 'guid' => $item['guid'], 'url' => $item['uri'], 'author' => $item["author-link"]]);
1786 if ($importer['importer_uid'] != 0) {
1787 Logger::debug('Message is directed to a user - accepted', ['uri-id' => $item['uri-id'], 'guid' => $item['guid'], 'url' => $item['uri'], 'importer' => $importer['importer_uid']]);
1791 if ($item['uri'] != $item['thr-parent']) {
1792 Logger::debug('Message is no parent - accepted', ['uri-id' => $item['uri-id'], 'guid' => $item['guid'], 'url' => $item['uri']]);
1796 $tags = array_column(Tag::getByURIId($item['uri-id'], [Tag::HASHTAG]), 'name');
1797 if (Relay::isSolicitedPost($tags, $item['body'], $item['author-id'], $item['uri'], Protocol::DFRN)) {
1798 Logger::debug('Post is accepted because of the relay settings', ['uri-id' => $item['uri-id'], 'guid' => $item['guid'], 'url' => $item['uri'], 'author' => $item["author-link"]]);
1806 * Processes the entry elements which contain the items and comments
1808 * @param array $header Array of the header elements that always stay the same
1809 * @param object $xpath XPath object
1810 * @param object $entry entry elements
1811 * @param array $importer Record of the importer user mixed with contact of the content
1812 * @param string $xml xml
1813 * @param int $protocol Protocol
1815 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1816 * @throws \ImagickException
1817 * @todo Add type-hints
1819 private static function processEntry(array $header, $xpath, $entry, array $importer, string $xml, int $protocol)
1821 Logger::notice("Processing entries");
1825 $item["protocol"] = $protocol;
1827 $item["source"] = $xml;
1830 $item["uri"] = XML::getFirstNodeValue($xpath, "atom:id/text()", $entry);
1832 $item["edited"] = XML::getFirstNodeValue($xpath, "atom:updated/text()", $entry);
1834 $current = Post::selectFirst(['id', 'uid', 'edited', 'body'],
1835 ['uri' => $item["uri"], 'uid' => $importer["importer_uid"]]
1837 // Is there an existing item?
1838 if (DBA::isResult($current) && !self::isEditedTimestampNewer($current, $item)) {
1839 Logger::info("Item ".$item["uri"]." (".$item['edited'].") already existed.");
1844 $owner = self::fetchauthor($xpath, $entry, $importer, "dfrn:owner", true, $xml);
1846 $owner_unknown = (isset($owner["contact-unknown"]) && $owner["contact-unknown"]);
1848 $item["owner-name"] = $owner["name"];
1849 $item["owner-link"] = $owner["link"];
1850 $item["owner-avatar"] = $owner["avatar"];
1851 $item["owner-id"] = Contact::getIdForURL($owner["link"], 0);
1854 $author = self::fetchauthor($xpath, $entry, $importer, "atom:author", true, $xml);
1856 $item["author-name"] = $author["name"];
1857 $item["author-link"] = $author["link"];
1858 $item["author-avatar"] = $author["avatar"];
1859 $item["author-id"] = Contact::getIdForURL($author["link"], 0);
1861 $item["title"] = XML::getFirstNodeValue($xpath, "atom:title/text()", $entry);
1863 if (!empty($item["title"])) {
1864 $item["post-type"] = Item::PT_ARTICLE;
1866 $item["post-type"] = Item::PT_NOTE;
1869 $item["created"] = XML::getFirstNodeValue($xpath, "atom:published/text()", $entry);
1871 $item["body"] = XML::getFirstNodeValue($xpath, "dfrn:env/text()", $entry);
1872 $item["body"] = str_replace([' ',"\t","\r","\n"], ['','','',''], $item["body"]);
1874 $item["body"] = Strings::base64UrlDecode($item["body"]);
1876 $item["body"] = BBCode::limitBodySize($item["body"]);
1878 /// @todo We should check for a repeated post and if we know the repeated author.
1880 // We don't need the content element since "dfrn:env" is always present
1881 //$item["body"] = $xpath->query("atom:content/text()", $entry)->item(0)->nodeValue;
1883 $item["location"] = XML::getFirstNodeValue($xpath, "dfrn:location/text()", $entry);
1885 $item["coord"] = XML::getFirstNodeValue($xpath, "georss:point", $entry);
1887 $item["private"] = XML::getFirstNodeValue($xpath, "dfrn:private/text()", $entry);
1889 $unlisted = XML::getFirstNodeValue($xpath, "dfrn:unlisted/text()", $entry);
1890 if (!empty($unlisted) && ($item['private'] != Item::PRIVATE)) {
1891 $item['private'] = Item::UNLISTED;
1894 $item["extid"] = XML::getFirstNodeValue($xpath, "dfrn:extid/text()", $entry);
1896 if (XML::getFirstNodeValue($xpath, "dfrn:bookmark/text()", $entry) == "true") {
1897 $item["post-type"] = Item::PT_PAGE;
1900 $notice_info = $xpath->query("statusnet:notice_info", $entry);
1901 if ($notice_info && ($notice_info->length > 0)) {
1902 foreach ($notice_info->item(0)->attributes as $attributes) {
1903 if ($attributes->name == "source") {
1904 $item["app"] = strip_tags($attributes->textContent);
1909 $item["guid"] = XML::getFirstNodeValue($xpath, "dfrn:diaspora_guid/text()", $entry);
1911 $item['uri-id'] = ItemURI::insert(['uri' => $item['uri'], 'guid' => $item['guid']]);
1913 $item["body"] = Item::improveSharedDataInBody($item);
1915 Tag::storeFromBody($item['uri-id'], $item["body"]);
1917 // We store the data from "dfrn:diaspora_signature" in a different table, this is done in "Item::insert"
1918 $dsprsig = XML::unescape(XML::getFirstNodeValue($xpath, "dfrn:diaspora_signature/text()", $entry));
1919 if ($dsprsig != "") {
1920 $signature = json_decode(base64_decode($dsprsig));
1921 // We don't store the old style signatures anymore that also contained the "signature" and "signer"
1922 if (!empty($signature->signed_text) && empty($signature->signature) && empty($signature->signer)) {
1923 $item["diaspora_signed_text"] = $signature->signed_text;
1927 $item["verb"] = XML::getFirstNodeValue($xpath, "activity:verb/text()", $entry);
1929 if (XML::getFirstNodeValue($xpath, "activity:object-type/text()", $entry) != "") {
1930 $item["object-type"] = XML::getFirstNodeValue($xpath, "activity:object-type/text()", $entry);
1933 $object = $xpath->query("activity:object", $entry)->item(0);
1934 $item["object"] = self::transformActivity($xpath, $object, "object");
1936 if (trim($item["object"]) != "") {
1937 $r = XML::parseString($item["object"]);
1938 if (isset($r->type)) {
1939 $item["object-type"] = $r->type;
1943 $target = $xpath->query("activity:target", $entry)->item(0);
1944 $item["target"] = self::transformActivity($xpath, $target, "target");
1946 $categories = $xpath->query("atom:category", $entry);
1948 foreach ($categories as $category) {
1951 foreach ($category->attributes as $attributes) {
1952 if ($attributes->name == "term") {
1953 $term = $attributes->textContent;
1956 if ($attributes->name == "scheme") {
1957 $scheme = $attributes->textContent;
1961 if (($term != "") && ($scheme != "")) {
1962 $parts = explode(":", $scheme);
1963 if ((count($parts) >= 4) && (array_shift($parts) == "X-DFRN")) {
1964 $termurl = array_pop($parts);
1965 $termurl = array_pop($parts) . ':' . $termurl;
1966 Tag::store($item['uri-id'], Tag::IMPLICIT_MENTION, $term, $termurl);
1972 $links = $xpath->query("atom:link", $entry);
1974 self::parseLinks($links, $item);
1977 $item['conversation-uri'] = XML::getFirstNodeValue($xpath, 'ostatus:conversation/text()', $entry);
1979 $conv = $xpath->query('ostatus:conversation', $entry);
1980 if (is_object($conv->item(0))) {
1981 foreach ($conv->item(0)->attributes as $attributes) {
1982 if ($attributes->name == "ref") {
1983 $item['conversation-uri'] = $attributes->textContent;
1985 if ($attributes->name == "href") {
1986 $item['conversation-href'] = $attributes->textContent;
1991 // Is it a reply or a top level posting?
1992 $item['thr-parent'] = $item['uri'];
1994 $inreplyto = $xpath->query("thr:in-reply-to", $entry);
1995 if (is_object($inreplyto->item(0))) {
1996 foreach ($inreplyto->item(0)->attributes as $attributes) {
1997 if ($attributes->name == "ref") {
1998 $item['thr-parent'] = $attributes->textContent;
2003 // Check if the message is wanted
2004 if (!self::isSolicitedMessage($item, $importer)) {
2005 DBA::delete('item-uri', ['uri' => $item['uri']]);
2009 // Get the type of the item (Top level post, reply or remote reply)
2010 $entrytype = self::getEntryType($importer, $item);
2012 // Now assign the rest of the values that depend on the type of the message
2013 if (in_array($entrytype, [DFRN::REPLY, DFRN::REPLY_RC])) {
2014 if (!isset($item["object-type"])) {
2015 $item["object-type"] = Activity\ObjectType::COMMENT;
2018 if ($item["contact-id"] != $owner["contact-id"]) {
2019 $item["contact-id"] = $owner["contact-id"];
2022 if (($item["network"] != $owner["network"]) && ($owner["network"] != "")) {
2023 $item["network"] = $owner["network"];
2026 if ($item["contact-id"] != $author["contact-id"]) {
2027 $item["contact-id"] = $author["contact-id"];
2030 if (($item["network"] != $author["network"]) && ($author["network"] != "")) {
2031 $item["network"] = $author["network"];
2035 // Ensure to have the correct share data
2036 $item = Item::addShareDataFromOriginal($item);
2038 if ($entrytype == DFRN::REPLY_RC) {
2040 } elseif ($entrytype == DFRN::TOP_LEVEL) {
2041 if (!isset($item["object-type"])) {
2042 $item["object-type"] = Activity\ObjectType::NOTE;
2046 if (($item["object-type"] == Activity\ObjectType::EVENT) && !$owner_unknown) {
2047 Logger::info("Item ".$item["uri"]." seems to contain an event.");
2048 $ev = Event::fromBBCode($item["body"]);
2049 if ((!empty($ev['desc']) || !empty($ev['summary'])) && !empty($ev['start'])) {
2050 Logger::info("Event in item ".$item["uri"]." was found.");
2051 $ev["cid"] = $importer["id"];
2052 $ev["uid"] = $importer["importer_uid"];
2053 $ev["uri"] = $item["uri"];
2054 $ev["edited"] = $item["edited"];
2055 $ev["private"] = $item["private"];
2056 $ev["guid"] = $item["guid"];
2057 $ev["plink"] = $item["plink"];
2058 $ev["network"] = $item["network"];
2059 $ev["protocol"] = $item["protocol"];
2060 $ev["direction"] = $item["direction"];
2061 $ev["source"] = $item["source"];
2063 $condition = ['uri' => $item["uri"], 'uid' => $importer["importer_uid"]];
2064 $event = DBA::selectFirst('event', ['id'], $condition);
2065 if (DBA::isResult($event)) {
2066 $ev["id"] = $event["id"];
2069 $event_id = Event::store($ev);
2070 Logger::info('Event was stored', ['id' => $event_id]);
2072 $item = Event::getItemArrayForImportedId($event_id, $item);
2077 if (!self::processVerbs($entrytype, $importer, $item, $is_like)) {
2078 Logger::info("Exiting because 'processVerbs' told us so");
2082 // This check is done here to be able to receive connection requests in "processVerbs"
2083 if (($entrytype == DFRN::TOP_LEVEL) && $owner_unknown) {
2084 Logger::info("Item won't be stored because user " . $importer["importer_uid"] . " doesn't follow " . $item["owner-link"] . ".");
2089 // Update content if 'updated' changes
2090 if (DBA::isResult($current)) {
2091 if (self::updateContent($current, $item, $importer, $entrytype)) {
2092 Logger::info("Item ".$item["uri"]." was updated.");
2094 Logger::info("Item " . $item["uri"] . " already existed.");
2099 if (in_array($entrytype, [DFRN::REPLY, DFRN::REPLY_RC])) {
2100 // Will be overwritten for sharing accounts in Item::insert
2101 if (empty($item['post-reason']) && ($entrytype == DFRN::REPLY)) {
2102 $item['post-reason'] = Item::PR_COMMENT;
2105 $posted_id = Item::insert($item);
2107 Logger::info("Reply from contact ".$item["contact-id"]." was stored with id ".$posted_id);
2109 if ($item['uid'] == 0) {
2110 Item::distribute($posted_id);
2115 } else { // $entrytype == DFRN::TOP_LEVEL
2116 if (($importer["uid"] == 0) && ($importer["importer_uid"] != 0)) {
2117 Logger::info("Contact ".$importer["id"]." isn't known to user ".$importer["importer_uid"].". The post will be ignored.");
2120 if (!Strings::compareLink($item["owner-link"], $importer["url"])) {
2122 * The item owner info is not our contact. It's OK and is to be expected if this is a tgroup delivery,
2123 * but otherwise there's a possible data mixup on the sender's system.
2124 * the tgroup delivery code called from Item::insert will correct it if it's a forum,
2125 * but we're going to unconditionally correct it here so that the post will always be owned by our contact.
2127 Logger::info('Correcting item owner.');
2128 $item["owner-link"] = $importer["url"];
2129 $item["owner-id"] = Contact::getIdForURL($importer["url"], 0);
2132 if (($importer["rel"] == Contact::FOLLOWER) && (!self::tgroupCheck($importer["importer_uid"], $item))) {
2133 Logger::info("Contact ".$importer["id"]." is only follower and tgroup check was negative.");
2137 // This is my contact on another system, but it's really me.
2138 // Turn this into a wall post.
2139 $notify = Item::isRemoteSelf($importer, $item);
2141 $posted_id = Item::insert($item, $notify);
2144 $posted_id = $notify;
2147 Logger::info("Item was stored with id ".$posted_id);
2149 if ($item['uid'] == 0) {
2150 Item::distribute($posted_id);
2153 if (stristr($item["verb"], Activity::POKE)) {
2154 $item['id'] = $posted_id;
2155 self::doPoke($item, $importer);
2163 * @param object $xpath XPath object
2164 * @param object $deletion deletion elements
2165 * @param array $importer Record of the importer user mixed with contact of the content
2167 * @throws \Exception
2168 * @todo set proper type-hints
2170 private static function processDeletion($xpath, $deletion, array $importer)
2172 Logger::notice("Processing deletions");
2175 foreach ($deletion->attributes as $attributes) {
2176 if ($attributes->name == "ref") {
2177 $uri = $attributes->textContent;
2181 if (!$uri || !$importer["id"]) {
2185 $condition = ['uri' => $uri, 'uid' => $importer["importer_uid"]];
2186 $item = Post::selectFirst(['id', 'parent', 'contact-id', 'uri-id', 'deleted', 'gravity'], $condition);
2187 if (!DBA::isResult($item)) {
2188 Logger::info("Item with uri " . $uri . " for user " . $importer["importer_uid"] . " wasn't found.");
2192 if (DBA::exists('post-category', ['uri-id' => $item['uri-id'], 'uid' => $importer['importer_uid'], 'type' => Post\Category::FILE])) {
2193 Logger::notice("Item is filed. It won't be deleted.", ['uri' => $uri, 'uri-id' => $item['uri_id'], 'uid' => $importer["importer_uid"]]);
2197 // When it is a starting post it has to belong to the person that wants to delete it
2198 if (($item['gravity'] == GRAVITY_PARENT) && ($item['contact-id'] != $importer["id"])) {
2199 Logger::info("Item with uri " . $uri . " don't belong to contact " . $importer["id"] . " - ignoring deletion.");
2203 // Comments can be deleted by the thread owner or comment owner
2204 if (($item['gravity'] != GRAVITY_PARENT) && ($item['contact-id'] != $importer["id"])) {
2205 $condition = ['id' => $item['parent'], 'contact-id' => $importer["id"]];
2206 if (!Post::exists($condition)) {
2207 Logger::info("Item with uri " . $uri . " wasn't found or mustn't be deleted by contact " . $importer["id"] . " - ignoring deletion.");
2212 if ($item["deleted"]) {
2216 Logger::info('deleting item '.$item['id'].' uri='.$uri);
2218 Item::markForDeletion(['id' => $item['id']]);
2222 * Imports a DFRN message
2224 * @param string $xml The DFRN message
2225 * @param array $importer Record of the importer user mixed with contact of the content
2226 * @param int $protocol Transport protocol
2227 * @param int $direction Is the message pushed or pulled?
2228 * @return integer Import status
2229 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2230 * @throws \ImagickException
2232 public static function import(string $xml, array $importer, int $protocol, int $direction): int
2238 $doc = new DOMDocument();
2239 @$doc->loadXML($xml);
2241 $xpath = new DOMXPath($doc);
2242 $xpath->registerNamespace("atom", ActivityNamespace::ATOM1);
2243 $xpath->registerNamespace("thr", ActivityNamespace::THREAD);
2244 $xpath->registerNamespace("at", ActivityNamespace::TOMB);
2245 $xpath->registerNamespace("media", ActivityNamespace::MEDIA);
2246 $xpath->registerNamespace("dfrn", ActivityNamespace::DFRN);
2247 $xpath->registerNamespace("activity", ActivityNamespace::ACTIVITY);
2248 $xpath->registerNamespace("georss", ActivityNamespace::GEORSS);
2249 $xpath->registerNamespace("poco", ActivityNamespace::POCO);
2250 $xpath->registerNamespace("ostatus", ActivityNamespace::OSTATUS);
2251 $xpath->registerNamespace("statusnet", ActivityNamespace::STATUSNET);
2254 $header["uid"] = $importer["importer_uid"];
2255 $header["network"] = Protocol::DFRN;
2256 $header["wall"] = 0;
2257 $header["origin"] = 0;
2258 $header["contact-id"] = $importer["id"];
2259 $header["direction"] = $direction;
2261 if ($direction === Conversation::RELAY) {
2262 $header['post-reason'] = Item::PR_RELAY;
2265 // Update the contact table if the data has changed
2267 // The "atom:author" is only present in feeds
2268 if ($xpath->query("/atom:feed/atom:author")->length > 0) {
2269 self::fetchauthor($xpath, $doc->firstChild, $importer, "atom:author", false, $xml);
2272 // Only the "dfrn:owner" in the head section contains all data
2273 if ($xpath->query("/atom:feed/dfrn:owner")->length > 0) {
2274 self::fetchauthor($xpath, $doc->firstChild, $importer, "dfrn:owner", false, $xml);
2277 Logger::info("Import DFRN message for user " . $importer["importer_uid"] . " from contact " . $importer["id"]);
2279 if (!empty($importer['gsid']) && ($protocol == Conversation::PARCEL_DIASPORA_DFRN)) {
2280 GServer::setProtocol($importer['gsid'], Post\DeliveryData::DFRN);
2283 // is it a public forum? Private forums aren't exposed with this method
2284 $forum = intval(XML::getFirstNodeValue($xpath, "/atom:feed/dfrn:community/text()"));
2286 // The account type is new since 3.5.1
2287 if ($xpath->query("/atom:feed/dfrn:account_type")->length > 0) {
2288 // Hint: We are using separate update calls for uid=0 and uid!=0 since a combined call is bad for the database performance
2290 $accounttype = intval(XML::getFirstNodeValue($xpath, "/atom:feed/dfrn:account_type/text()"));
2292 if ($accounttype != $importer["contact-type"]) {
2293 Contact::update(['contact-type' => $accounttype], ['id' => $importer['id']]);
2295 // Updating the public contact as well
2296 Contact::update(['contact-type' => $accounttype], ['uid' => 0, 'nurl' => $importer['nurl']]);
2298 // A forum contact can either have set "forum" or "prv" - but not both
2299 if ($accounttype == User::ACCOUNT_TYPE_COMMUNITY) {
2300 // It's a forum, so either set the public or private forum flag
2301 $condition = ['(`forum` != ? OR `prv` != ?) AND `id` = ?', $forum, !$forum, $importer['id']];
2302 Contact::update(['forum' => $forum, 'prv' => !$forum], $condition);
2304 // Updating the public contact as well
2305 $condition = ['(`forum` != ? OR `prv` != ?) AND `uid` = 0 AND `nurl` = ?', $forum, !$forum, $importer['nurl']];
2306 Contact::update(['forum' => $forum, 'prv' => !$forum], $condition);
2308 // It's not a forum, so remove the flags
2309 $condition = ['(`forum` OR `prv`) AND `id` = ?', $importer['id']];
2310 Contact::update(['forum' => false, 'prv' => false], $condition);
2312 // Updating the public contact as well
2313 $condition = ['(`forum` OR `prv`) AND `uid` = 0 AND `nurl` = ?', $importer['nurl']];
2314 Contact::update(['forum' => false, 'prv' => false], $condition);
2316 } elseif ($forum != $importer["forum"]) { // Deprecated since 3.5.1
2317 $condition = ['`forum` != ? AND `id` = ?', $forum, $importer["id"]];
2318 Contact::update(['forum' => $forum], $condition);
2320 // Updating the public contact as well
2321 $condition = ['`forum` != ? AND `uid` = 0 AND `nurl` = ?', $forum, $importer['nurl']];
2322 Contact::update(['forum' => $forum], $condition);
2326 // We are processing relocations even if we are ignoring a contact
2327 $relocations = $xpath->query("/atom:feed/dfrn:relocate");
2328 foreach ($relocations as $relocation) {
2329 self::processRelocation($xpath, $relocation, $importer);
2332 if (($importer["uid"] != 0) && !$importer["readonly"]) {
2333 $mails = $xpath->query("/atom:feed/dfrn:mail");
2334 foreach ($mails as $mail) {
2335 self::processMail($xpath, $mail, $importer);
2338 $suggestions = $xpath->query("/atom:feed/dfrn:suggest");
2339 foreach ($suggestions as $suggestion) {
2340 self::processSuggestion($xpath, $suggestion, $importer);
2344 $deletions = $xpath->query("/atom:feed/at:deleted-entry");
2345 if (!empty($deletions)) {
2346 foreach ($deletions as $deletion) {
2347 self::processDeletion($xpath, $deletion, $importer);
2349 if (count($deletions) > 0) {
2350 Logger::notice('Deletions had been processed');
2355 $entries = $xpath->query("/atom:feed/atom:entry");
2356 foreach ($entries as $entry) {
2357 self::processEntry($header, $xpath, $entry, $importer, $xml, $protocol);
2360 Logger::info("Import done for user " . $importer["importer_uid"] . " from contact " . $importer["id"]);
2365 * Returns the activity verb
2367 * @param array $item Item array
2369 * @return string activity verb
2371 private static function constructVerb(array $item): string
2373 if ($item['verb']) {
2374 return $item['verb'];
2376 return Activity::POST;
2379 // @TODO Documentation missing
2380 private static function tgroupCheck(int $uid, array $item): bool
2384 // check that the message originated elsewhere and is a top-level post
2386 if ($item['wall'] || $item['origin'] || ($item['uri'] != $item['thr-parent'])) {
2390 $user = DBA::selectFirst('user', ['account-type', 'nickname'], ['uid' => $uid]);
2391 if (!DBA::isResult($user)) {
2395 $link = Strings::normaliseLink(DI::baseUrl() . '/profile/' . $user['nickname']);
2398 * Diaspora uses their own hardwired link URL in @-tags
2399 * instead of the one we supply with webfinger
2401 $dlink = Strings::normaliseLink(DI::baseUrl() . '/u/' . $user['nickname']);
2403 $cnt = preg_match_all('/[\@\!]\[url\=(.*?)\](.*?)\[\/url\]/ism', $item['body'], $matches, PREG_SET_ORDER);
2405 foreach ($matches as $mtch) {
2406 if (Strings::compareLink($link, $mtch[1]) || Strings::compareLink($dlink, $mtch[1])) {
2408 Logger::notice('mention found: ' . $mtch[2]);
2417 return ($user['account-type'] == User::ACCOUNT_TYPE_COMMUNITY);
2421 * This function returns true if $update has an edited timestamp newer
2422 * than $existing, i.e. $update contains new data which should override
2423 * what's already there. If there is no timestamp yet, the update is
2424 * assumed to be newer. If the update has no timestamp, the existing
2425 * item is assumed to be up-to-date. If the timestamps are equal it
2426 * assumes the update has been seen before and should be ignored.
2428 * @param array $existing
2429 * @param array $update
2431 * @throws \Exception
2433 private static function isEditedTimestampNewer(array $existing, array $update): bool
2435 if (empty($existing['edited'])) {
2438 if (empty($update['edited'])) {
2442 $existing_edited = DateTimeFormat::utc($existing['edited']);
2443 $update_edited = DateTimeFormat::utc($update['edited']);
2445 return (strcmp($existing_edited, $update_edited) < 0);
2449 * Checks if the given contact url does support DFRN
2451 * @param string $url profile url
2453 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2454 * @throws \ImagickException
2456 public static function isSupportedByContactUrl(string $url): bool
2458 $probe = Probe::uri($url, Protocol::DFRN);
2459 return $probe['network'] == Protocol::DFRN;