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\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($cid, $uid = 0)
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($items, $owner)
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)
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)
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($item, $owner)
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($owner, $uid)
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-hints
351 private static function addHeader(DOMDocument $doc, $owner, $authorelement, $alternatelink = "", $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 * Adds the author element in the header for the DFRN protocol
419 * @param DOMDocument $doc XML document
420 * @param array $owner Owner record
421 * @param string $authorelement Element name for the author
422 * @param boolean $public boolean
424 * @return \DOMElement XML author object
425 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
426 * @todo Find proper type-hints
428 private static function addAuthor(DOMDocument $doc, array $owner, $authorelement, $public)
430 // Should the profile be "unsearchable" in the net? Then add the "hide" element
431 $hide = DBA::exists('profile', ['uid' => $owner['uid'], 'net-publish' => false]);
433 $author = $doc->createElement($authorelement);
435 $namdate = DateTimeFormat::utc($owner['name-date'].'+00:00', DateTimeFormat::ATOM);
436 $picdate = DateTimeFormat::utc($owner['avatar-date'].'+00:00', DateTimeFormat::ATOM);
440 if (!$public || !$hide) {
441 $attributes = ["dfrn:updated" => $namdate];
444 XML::addElement($doc, $author, "name", $owner["name"], $attributes);
445 XML::addElement($doc, $author, "uri", DI::baseUrl().'/profile/'.$owner["nickname"], $attributes);
446 XML::addElement($doc, $author, "dfrn:handle", $owner["addr"], $attributes);
448 $attributes = ["rel" => "photo", "type" => "image/jpeg",
449 "media:width" => Proxy::PIXEL_SMALL, "media:height" => Proxy::PIXEL_SMALL,
450 "href" => User::getAvatarUrl($owner, Proxy::SIZE_SMALL)];
452 if (!$public || !$hide) {
453 $attributes["dfrn:updated"] = $picdate;
456 XML::addElement($doc, $author, "link", "", $attributes);
458 $attributes["rel"] = "avatar";
459 XML::addElement($doc, $author, "link", "", $attributes);
462 XML::addElement($doc, $author, "dfrn:hide", "true");
465 // The following fields will only be generated if the data isn't meant for a public feed
470 $birthday = feed_birthday($owner['uid'], $owner['timezone']);
473 XML::addElement($doc, $author, "dfrn:birthday", $birthday);
476 // Only show contact details when we are allowed to
477 $profile = DBA::selectFirst('owner-view',
478 ['about', 'name', 'homepage', 'nickname', 'timezone', 'locality', 'region', 'country-name', 'pub_keywords', 'xmpp', 'dob'],
479 ['uid' => $owner['uid'], 'hidewall' => false]);
480 if (DBA::isResult($profile)) {
481 XML::addElement($doc, $author, "poco:displayName", $profile["name"]);
482 XML::addElement($doc, $author, "poco:updated", $namdate);
484 if (trim($profile["dob"]) > DBA::NULL_DATE) {
485 XML::addElement($doc, $author, "poco:birthday", "0000-".date("m-d", strtotime($profile["dob"])));
488 XML::addElement($doc, $author, "poco:note", $profile["about"]);
489 XML::addElement($doc, $author, "poco:preferredUsername", $profile["nickname"]);
491 XML::addElement($doc, $author, "poco:utcOffset", DateTimeFormat::timezoneNow($profile["timezone"], "P"));
493 if (trim($profile["homepage"]) != "") {
494 $urls = $doc->createElement("poco:urls");
495 XML::addElement($doc, $urls, "poco:type", "homepage");
496 XML::addElement($doc, $urls, "poco:value", $profile["homepage"]);
497 XML::addElement($doc, $urls, "poco:primary", "true");
498 $author->appendChild($urls);
501 if (trim($profile["pub_keywords"]) != "") {
502 $keywords = explode(",", $profile["pub_keywords"]);
504 foreach ($keywords as $keyword) {
505 XML::addElement($doc, $author, "poco:tags", trim($keyword));
509 if (trim($profile["xmpp"]) != "") {
510 $ims = $doc->createElement("poco:ims");
511 XML::addElement($doc, $ims, "poco:type", "xmpp");
512 XML::addElement($doc, $ims, "poco:value", $profile["xmpp"]);
513 XML::addElement($doc, $ims, "poco:primary", "true");
514 $author->appendChild($ims);
517 if (trim($profile["locality"].$profile["region"].$profile["country-name"]) != "") {
518 $element = $doc->createElement("poco:address");
520 XML::addElement($doc, $element, "poco:formatted", Profile::formatLocation($profile));
522 if (trim($profile["locality"]) != "") {
523 XML::addElement($doc, $element, "poco:locality", $profile["locality"]);
526 if (trim($profile["region"]) != "") {
527 XML::addElement($doc, $element, "poco:region", $profile["region"]);
530 if (trim($profile["country-name"]) != "") {
531 XML::addElement($doc, $element, "poco:country", $profile["country-name"]);
534 $author->appendChild($element);
542 * Adds the author elements in the "entry" elements of the DFRN protocol
544 * @param DOMDocument $doc XML document
545 * @param string $element Element name for the author
546 * @param string $contact_url Link of the contact
547 * @param array $item Item elements
549 * @return \DOMElement XML author object
550 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
551 * @todo Find proper type-hints
553 private static function addEntryAuthor(DOMDocument $doc, $element, $contact_url, $item)
555 $author = $doc->createElement($element);
557 $contact = Contact::getByURLForUser($contact_url, $item["uid"], false, ['url', 'name', 'addr', 'photo']);
558 if (!empty($contact)) {
559 XML::addElement($doc, $author, "name", $contact["name"]);
560 XML::addElement($doc, $author, "uri", $contact["url"]);
561 XML::addElement($doc, $author, "dfrn:handle", $contact["addr"]);
564 /// - Check real image type and image size
565 /// - Check which of these boths elements we should use
568 "type" => "image/jpeg",
570 "media:height" => 80,
571 "href" => $contact["photo"]];
572 XML::addElement($doc, $author, "link", "", $attributes);
576 "type" => "image/jpeg",
578 "media:height" => 80,
579 "href" => $contact["photo"]];
580 XML::addElement($doc, $author, "link", "", $attributes);
587 * Adds the activity elements
589 * @param DOMDocument $doc XML document
590 * @param string $element Element name for the activity
591 * @param string $activity activity value
592 * @param int $uriid Uri-Id of the post
594 * @return \DOMElement XML activity object
595 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
596 * @todo Find proper type-hints
598 private static function createActivity(DOMDocument $doc, $element, $activity, $uriid)
601 $entry = $doc->createElement($element);
603 $r = XML::parseString($activity);
609 XML::addElement($doc, $entry, "activity:object-type", $r->type);
613 XML::addElement($doc, $entry, "id", $r->id);
617 XML::addElement($doc, $entry, "title", $r->title);
621 if (substr($r->link, 0, 1) == '<') {
622 if (strstr($r->link, '&') && (! strstr($r->link, '&'))) {
623 $r->link = str_replace('&', '&', $r->link);
626 $r->link = preg_replace('/\<link(.*?)\"\>/', '<link$1"/>', $r->link);
628 // XML does need a single element as root element so we add a dummy element here
629 $data = XML::parseString("<dummy>" . $r->link . "</dummy>");
630 if (is_object($data)) {
631 foreach ($data->link as $link) {
633 foreach ($link->attributes() as $parameter => $value) {
634 $attributes[$parameter] = $value;
636 XML::addElement($doc, $entry, "link", "", $attributes);
640 $attributes = ["rel" => "alternate", "type" => "text/html", "href" => $r->link];
641 XML::addElement($doc, $entry, "link", "", $attributes);
645 XML::addElement($doc, $entry, "content", BBCode::convertForUriId($uriid, $r->content, BBCode::EXTERNAL), ["type" => "html"]);
655 * Adds the elements for attachments
657 * @param object $doc XML document
658 * @param object $root XML root
659 * @param array $item Item element
661 * @return void XML attachment object
662 * @todo Find proper type-hints
664 private static function getAttachment($doc, $root, $item)
666 foreach (Post\Media::getByURIId($item['uri-id'], [Post\Media::DOCUMENT, Post\Media::TORRENT, Post\Media::UNKNOWN]) as $attachment) {
667 $attributes = ['rel' => 'enclosure',
668 'href' => $attachment['url'],
669 'type' => $attachment['mimetype']];
671 if (!empty($attachment['size'])) {
672 $attributes['length'] = intval($attachment['size']);
674 if (!empty($attachment['description'])) {
675 $attributes['title'] = $attachment['description'];
678 XML::addElement($doc, $root, 'link', '', $attributes);
683 * Adds the "entry" elements for the DFRN protocol
685 * @param DOMDocument $doc XML document
686 * @param string $type "text" or "html"
687 * @param array $item Item element
688 * @param array $owner Owner record
689 * @param bool $comment Trigger the sending of the "comment" element
690 * @param int $cid Contact ID of the recipient
691 * @param bool $single If set, the entry is created as an XML document with a single "entry" element
693 * @return null|\DOMElement XML entry object
694 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
695 * @throws \ImagickException
696 * @todo Find proper type-hints
698 private static function entry(DOMDocument $doc, $type, array $item, array $owner, $comment = false, $cid = 0, $single = false)
702 if (!$item['parent']) {
703 Logger::notice('Item without parent found.', ['type' => $type, 'item' => $item]);
707 if ($item['deleted']) {
708 $attributes = ["ref" => $item['uri'], "when" => DateTimeFormat::utc($item['edited'] . '+00:00', DateTimeFormat::ATOM)];
709 return XML::createElement($doc, "at:deleted-entry", "", $attributes);
713 $entry = $doc->createElement("entry");
715 $entry = $doc->createElementNS(ActivityNamespace::ATOM1, 'entry');
716 $doc->appendChild($entry);
718 $entry->setAttribute("xmlns:thr", ActivityNamespace::THREAD);
719 $entry->setAttribute("xmlns:at", ActivityNamespace::TOMB);
720 $entry->setAttribute("xmlns:media", ActivityNamespace::MEDIA);
721 $entry->setAttribute("xmlns:dfrn", ActivityNamespace::DFRN);
722 $entry->setAttribute("xmlns:activity", ActivityNamespace::ACTIVITY);
723 $entry->setAttribute("xmlns:georss", ActivityNamespace::GEORSS);
724 $entry->setAttribute("xmlns:poco", ActivityNamespace::POCO);
725 $entry->setAttribute("xmlns:ostatus", ActivityNamespace::OSTATUS);
726 $entry->setAttribute("xmlns:statusnet", ActivityNamespace::STATUSNET);
729 $body = Post\Media::addAttachmentsToBody($item['uri-id'], $item['body'] ?? '');
731 if ($item['private'] == Item::PRIVATE) {
732 $body = Item::fixPrivatePhotos($body, $owner['uid'], $item, $cid);
735 // Remove the abstract element. It is only locally important.
736 $body = BBCode::stripAbstract($body);
739 if ($type == 'html') {
742 if ($item['title'] != "") {
743 $htmlbody = "[b]" . $item['title'] . "[/b]\n\n" . $htmlbody;
746 $htmlbody = BBCode::convertForUriId($item['uri-id'], $htmlbody, BBCode::ACTIVITYPUB);
749 $author = self::addEntryAuthor($doc, "author", $item["author-link"], $item);
750 $entry->appendChild($author);
752 $dfrnowner = self::addEntryAuthor($doc, "dfrn:owner", $item["owner-link"], $item);
753 $entry->appendChild($dfrnowner);
755 if ($item['gravity'] != GRAVITY_PARENT) {
756 $parent = Post::selectFirst(['guid', 'plink'], ['uri' => $item['thr-parent'], 'uid' => $item['uid']]);
757 if (DBA::isResult($parent)) {
758 $attributes = ["ref" => $item['thr-parent'], "type" => "text/html",
759 "href" => $parent['plink'],
760 "dfrn:diaspora_guid" => $parent['guid']];
761 XML::addElement($doc, $entry, "thr:in-reply-to", "", $attributes);
765 // Add conversation data. This is used for OStatus
766 $conversation_href = DI::baseUrl()."/display/".$item["parent-guid"];
767 $conversation_uri = $conversation_href;
769 if (isset($parent_item)) {
770 $conversation = DBA::selectFirst('conversation', ['conversation-uri', 'conversation-href'], ['item-uri' => $item['thr-parent']]);
771 if (DBA::isResult($conversation)) {
772 if ($conversation['conversation-uri'] != '') {
773 $conversation_uri = $conversation['conversation-uri'];
775 if ($conversation['conversation-href'] != '') {
776 $conversation_href = $conversation['conversation-href'];
782 "href" => $conversation_href,
783 "ref" => $conversation_uri];
785 XML::addElement($doc, $entry, "ostatus:conversation", $conversation_uri, $attributes);
787 XML::addElement($doc, $entry, "id", $item["uri"]);
788 XML::addElement($doc, $entry, "title", $item["title"]);
790 XML::addElement($doc, $entry, "published", DateTimeFormat::utc($item["created"] . "+00:00", DateTimeFormat::ATOM));
791 XML::addElement($doc, $entry, "updated", DateTimeFormat::utc($item["edited"] . "+00:00", DateTimeFormat::ATOM));
793 // "dfrn:env" is used to read the content
794 XML::addElement($doc, $entry, "dfrn:env", Strings::base64UrlEncode($body, true));
796 // The "content" field is not read by the receiver. We could remove it when the type is "text"
797 // We keep it at the moment, maybe there is some old version that doesn't read "dfrn:env"
798 XML::addElement($doc, $entry, "content", (($type == 'html') ? $htmlbody : $body), ["type" => $type]);
800 // We save this value in "plink". Maybe we should read it from there as well?
806 ["rel" => "alternate", "type" => "text/html",
807 "href" => DI::baseUrl() . "/display/" . $item["guid"]]
810 // "comment-allow" is some old fashioned stuff for old Friendica versions.
811 // It is included in the rewritten code for completeness
813 XML::addElement($doc, $entry, "dfrn:comment-allow", 1);
816 if ($item['location']) {
817 XML::addElement($doc, $entry, "dfrn:location", $item['location']);
820 if ($item['coord']) {
821 XML::addElement($doc, $entry, "georss:point", $item['coord']);
824 if ($item['private']) {
825 // Friendica versions prior to 2020.3 can't handle "unlisted" properly. So we can only transmit public and private
826 XML::addElement($doc, $entry, "dfrn:private", ($item['private'] == Item::PRIVATE ? Item::PRIVATE : Item::PUBLIC));
827 XML::addElement($doc, $entry, "dfrn:unlisted", $item['private'] == Item::UNLISTED);
830 if ($item['extid']) {
831 XML::addElement($doc, $entry, "dfrn:extid", $item['extid']);
834 if ($item['post-type'] == Item::PT_PAGE) {
835 XML::addElement($doc, $entry, "dfrn:bookmark", "true");
839 XML::addElement($doc, $entry, "statusnet:notice_info", "", ["local_id" => $item['id'], "source" => $item['app']]);
842 XML::addElement($doc, $entry, "dfrn:diaspora_guid", $item["guid"]);
844 // The signed text contains the content in Markdown, the sender handle and the signatur for the content
845 // It is needed for relayed comments to Diaspora.
846 if ($item['signed_text']) {
847 $sign = base64_encode(json_encode(['signed_text' => $item['signed_text'],'signature' => '','signer' => '']));
848 XML::addElement($doc, $entry, "dfrn:diaspora_signature", $sign);
851 XML::addElement($doc, $entry, "activity:verb", self::constructVerb($item));
853 if ($item['object-type'] != "") {
854 XML::addElement($doc, $entry, "activity:object-type", $item['object-type']);
855 } elseif ($item['gravity'] == GRAVITY_PARENT) {
856 XML::addElement($doc, $entry, "activity:object-type", Activity\ObjectType::NOTE);
858 XML::addElement($doc, $entry, "activity:object-type", Activity\ObjectType::COMMENT);
861 $actobj = self::createActivity($doc, "activity:object", $item['object'], $item['uri-id']);
863 $entry->appendChild($actobj);
866 $actarg = self::createActivity($doc, "activity:target", $item['target'], $item['uri-id']);
868 $entry->appendChild($actarg);
871 $tags = Tag::getByURIId($item['uri-id']);
874 foreach ($tags as $tag) {
875 if (($type != 'html') || ($tag['type'] == Tag::HASHTAG)) {
876 XML::addElement($doc, $entry, "category", "", ["scheme" => "X-DFRN:" . Tag::TAG_CHARACTER[$tag['type']] . ":" . $tag['url'], "term" => $tag['name']]);
878 if ($tag['type'] != Tag::HASHTAG) {
879 $mentioned[$tag['url']] = $tag['url'];
884 foreach ($mentioned as $mention) {
885 $condition = ['uid' => $owner["uid"], 'nurl' => Strings::normaliseLink($mention)];
886 $contact = DBA::selectFirst('contact', ['forum', 'prv'], $condition);
888 if (DBA::isResult($contact) && ($contact["forum"] || $contact["prv"])) {
894 ["rel" => "mentioned",
895 "ostatus:object-type" => Activity\ObjectType::GROUP,
904 ["rel" => "mentioned",
905 "ostatus:object-type" => Activity\ObjectType::PERSON,
911 self::getAttachment($doc, $entry, $item);
917 * Transmits atom content to the contacts via the Diaspora transport layer
919 * @param array $owner Owner record
920 * @param array $contact Contact record of the receiver
921 * @param string $atom Content that will be transmitted
923 * @param bool $public_batch
924 * @return int Deliver status. Negative values mean an error.
925 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
926 * @throws \ImagickException
928 public static function transmit($owner, $contact, $atom, $public_batch = false)
930 if (!$public_batch) {
931 if (empty($contact['addr'])) {
932 Logger::log('Empty contact handle for ' . $contact['id'] . ' - ' . $contact['url'] . ' - trying to update it.');
933 if (Contact::updateFromProbe($contact['id'])) {
934 $new_contact = DBA::selectFirst('contact', ['addr'], ['id' => $contact['id']]);
935 $contact['addr'] = $new_contact['addr'];
938 if (empty($contact['addr'])) {
939 Logger::log('Unable to find contact handle for ' . $contact['id'] . ' - ' . $contact['url']);
944 $fcontact = FContact::getByURL($contact['addr']);
945 if (empty($fcontact)) {
946 Logger::log('Unable to find contact details for ' . $contact['id'] . ' - ' . $contact['addr']);
949 $pubkey = $fcontact['pubkey'];
954 $envelope = Diaspora::buildMessage($atom, $owner, $contact, $owner['uprvkey'], $pubkey, $public_batch);
956 // Create the endpoint for public posts. This is some WIP and should later be added to the probing
957 if ($public_batch && empty($contact["batch"])) {
958 $parts = parse_url($contact["notify"]);
959 $path_parts = explode('/', $parts['path']);
960 array_pop($path_parts);
961 $parts['path'] = implode('/', $path_parts);
962 $contact["batch"] = Network::unparseURL($parts);
965 $dest_url = ($public_batch ? $contact["batch"] : $contact["notify"]);
967 if (empty($dest_url)) {
968 Logger::info('Empty destination', ['public' => $public_batch, 'contact' => $contact]);
972 $content_type = ($public_batch ? "application/magic-envelope+xml" : "application/json");
974 $postResult = DI::httpClient()->post($dest_url, $envelope, ['Content-Type' => $content_type]);
975 $xml = $postResult->getBody();
977 $curl_stat = $postResult->getReturnCode();
978 if (empty($curl_stat) || empty($xml)) {
979 Logger::log('Empty answer from ' . $contact['id'] . ' - ' . $dest_url);
980 return -9; // timed out
983 if (($curl_stat == 503) && $postResult->inHeader('retry-after')) {
987 if (strpos($xml, '<?xml') === false) {
988 Logger::log('No valid XML returned from ' . $contact['id'] . ' - ' . $dest_url);
989 Logger::log('Returned XML: ' . $xml, Logger::DATA);
993 $res = XML::parseString($xml);
995 if (empty($res->status)) {
999 if (!empty($res->message)) {
1000 Logger::log('Transmit to ' . $dest_url . ' returned status '.$res->status.' - '.$res->message, Logger::DEBUG);
1003 return intval($res->status);
1007 * Fetch the author data from head or entry items
1009 * @param \DOMXPath $xpath XPath object
1010 * @param \DOMNode $context In which context should the data be searched
1011 * @param array $importer Record of the importer user mixed with contact of the content
1012 * @param string $element Element name from which the data is fetched
1013 * @param bool $onlyfetch Should the data only be fetched or should it update the contact record as well
1014 * @param string $xml optional, default empty
1016 * @return array Relevant data of the author
1017 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1018 * @throws \ImagickException
1019 * @todo Find good type-hints for all parameter
1021 private static function fetchauthor(\DOMXPath $xpath, \DOMNode $context, $importer, $element, $onlyfetch, $xml = "")
1024 $author["name"] = XML::getFirstNodeValue($xpath, $element."/atom:name/text()", $context);
1025 $author["link"] = XML::getFirstNodeValue($xpath, $element."/atom:uri/text()", $context);
1027 $fields = ['id', 'uid', 'url', 'network', 'avatar-date', 'avatar', 'name-date', 'uri-date', 'addr',
1028 'name', 'nick', 'about', 'location', 'keywords', 'xmpp', 'bdyear', 'bd', 'hidden', 'contact-type'];
1029 $condition = ["`uid` = ? AND `nurl` = ? AND `network` != ? AND NOT `pending` AND NOT `blocked`",
1030 $importer["importer_uid"], Strings::normaliseLink($author["link"]), Protocol::STATUSNET];
1032 if ($importer['account-type'] != User::ACCOUNT_TYPE_COMMUNITY) {
1033 $condition = DBA::mergeConditions($condition, ['rel' => [Contact::SHARING, Contact::FRIEND]]);
1036 $contact_old = DBA::selectFirst('contact', $fields, $condition);
1038 if (DBA::isResult($contact_old)) {
1039 $author["contact-id"] = $contact_old["id"];
1040 $author["network"] = $contact_old["network"];
1042 Logger::info('Contact not found', ['condition' => $condition]);
1044 $author["contact-unknown"] = true;
1045 $contact = Contact::getByURL($author["link"], null, ["id", "network"]);
1046 $author["contact-id"] = $contact["id"] ?? $importer["id"];
1047 $author["network"] = $contact["network"] ?? $importer["network"];
1051 // Until now we aren't serving different sizes - but maybe later
1053 /// @todo check if "avatar" or "photo" would be the best field in the specification
1054 $avatars = $xpath->query($element . "/atom:link[@rel='avatar']", $context);
1055 foreach ($avatars as $avatar) {
1058 foreach ($avatar->attributes as $attributes) {
1059 /// @TODO Rewrite these similar if() to one switch
1060 if ($attributes->name == "href") {
1061 $href = $attributes->textContent;
1063 if ($attributes->name == "width") {
1064 $width = $attributes->textContent;
1066 if ($attributes->name == "updated") {
1067 $author["avatar-date"] = $attributes->textContent;
1070 if (($width > 0) && ($href != "")) {
1071 $avatarlist[$width] = $href;
1075 if (count($avatarlist) > 0) {
1076 krsort($avatarlist);
1077 $author["avatar"] = current($avatarlist);
1080 if (empty($author['avatar']) && !empty($author['link'])) {
1081 $cid = Contact::getIdForURL($author['link'], 0);
1083 $contact = DBA::selectFirst('contact', ['avatar'], ['id' => $cid]);
1084 if (DBA::isResult($contact)) {
1085 $author['avatar'] = $contact['avatar'];
1090 if (empty($author['avatar'])) {
1091 Logger::log('Empty author: ' . $xml);
1092 $author['avatar'] = '';
1095 if (DBA::isResult($contact_old) && !$onlyfetch) {
1096 Logger::log("Check if contact details for contact " . $contact_old["id"] . " (" . $contact_old["nick"] . ") have to be updated.", Logger::DEBUG);
1098 $poco = ["url" => $contact_old["url"], "network" => $contact_old["network"]];
1100 // When was the last change to name or uri?
1101 $name_element = $xpath->query($element . "/atom:name", $context)->item(0);
1102 foreach ($name_element->attributes as $attributes) {
1103 if ($attributes->name == "updated") {
1104 $poco["name-date"] = $attributes->textContent;
1108 $link_element = $xpath->query($element . "/atom:link", $context)->item(0);
1109 foreach ($link_element->attributes as $attributes) {
1110 if ($attributes->name == "updated") {
1111 $poco["uri-date"] = $attributes->textContent;
1115 // Update contact data
1116 $value = XML::getFirstNodeValue($xpath, $element . "/dfrn:handle/text()", $context);
1118 $poco["addr"] = $value;
1121 $value = XML::getFirstNodeValue($xpath, $element . "/poco:displayName/text()", $context);
1123 $poco["name"] = $value;
1126 $value = XML::getFirstNodeValue($xpath, $element . "/poco:preferredUsername/text()", $context);
1128 $poco["nick"] = $value;
1131 $value = XML::getFirstNodeValue($xpath, $element . "/poco:note/text()", $context);
1133 $poco["about"] = $value;
1136 $value = XML::getFirstNodeValue($xpath, $element . "/poco:address/poco:formatted/text()", $context);
1138 $poco["location"] = $value;
1141 /// @todo Only search for elements with "poco:type" = "xmpp"
1142 $value = XML::getFirstNodeValue($xpath, $element . "/poco:ims/poco:value/text()", $context);
1144 $poco["xmpp"] = $value;
1147 /// @todo Add support for the following fields that we don't support by now in the contact table:
1148 /// - poco:utcOffset
1154 // If the "hide" element is present then the profile isn't searchable.
1155 $hide = intval(XML::getFirstNodeValue($xpath, $element . "/dfrn:hide/text()", $context) == "true");
1157 Logger::log("Hidden status for contact " . $contact_old["url"] . ": " . $hide, Logger::DEBUG);
1159 // If the contact isn't searchable then set the contact to "hidden".
1160 // Problem: This can be manually overridden by the user.
1162 $contact_old["hidden"] = true;
1165 // Save the keywords into the contact table
1167 $tagelements = $xpath->evaluate($element . "/poco:tags/text()", $context);
1168 foreach ($tagelements as $tag) {
1169 $tags[$tag->nodeValue] = $tag->nodeValue;
1173 $poco["keywords"] = implode(", ", $tags);
1176 // "dfrn:birthday" contains the birthday converted to UTC
1177 $birthday = XML::getFirstNodeValue($xpath, $element . "/dfrn:birthday/text()", $context);
1179 $birthday_date = new \DateTime($birthday);
1180 if ($birthday_date > new \DateTime()) {
1181 $poco["bdyear"] = $birthday_date->format("Y");
1183 } catch (\Exception $e) {
1187 // "poco:birthday" is the birthday in the format "yyyy-mm-dd"
1188 $value = XML::getFirstNodeValue($xpath, $element . "/poco:birthday/text()", $context);
1190 if (!in_array($value, ["", "0000-00-00", DBA::NULL_DATE])) {
1191 $bdyear = date("Y");
1192 $value = str_replace(["0000", "0001"], $bdyear, $value);
1194 if (strtotime($value) < time()) {
1195 $value = str_replace($bdyear, $bdyear + 1, $value);
1198 $poco["bd"] = $value;
1201 $contact = array_merge($contact_old, $poco);
1203 if ($contact_old["bdyear"] != $contact["bdyear"]) {
1204 Event::createBirthday($contact, $birthday);
1207 $fields = ['name' => $contact['name'], 'nick' => $contact['nick'], 'about' => $contact['about'],
1208 'location' => $contact['location'], 'addr' => $contact['addr'], 'keywords' => $contact['keywords'],
1209 'bdyear' => $contact['bdyear'], 'bd' => $contact['bd'], 'hidden' => $contact['hidden'],
1210 'xmpp' => $contact['xmpp'], 'name-date' => DateTimeFormat::utc($contact['name-date']),
1211 'unsearchable' => $contact['hidden'], 'uri-date' => DateTimeFormat::utc($contact['uri-date'])];
1213 Contact::update($fields, ['id' => $contact['id'], 'network' => $contact['network']], $contact_old);
1215 // Update the public contact. Don't set the "hidden" value, this is used differently for public contacts
1216 unset($fields['hidden']);
1217 $condition = ['uid' => 0, 'nurl' => Strings::normaliseLink($contact_old['url'])];
1218 Contact::update($fields, $condition, true);
1220 Contact::updateAvatar($contact['id'], $author['avatar']);
1222 $pcid = Contact::getIdForURL($contact_old['url']);
1223 if (!empty($pcid)) {
1224 Contact::updateAvatar($pcid, $author['avatar']);
1232 * Transforms activity objects into an XML string
1234 * @param object $xpath XPath object
1235 * @param object $activity Activity object
1236 * @param string $element element name
1238 * @return string XML string
1239 * @todo Find good type-hints for all parameter
1241 private static function transformActivity($xpath, $activity, $element)
1243 if (!is_object($activity)) {
1247 $obj_doc = new DOMDocument("1.0", "utf-8");
1248 $obj_doc->formatOutput = true;
1250 $obj_element = $obj_doc->createElementNS( ActivityNamespace::ATOM1, $element);
1252 $activity_type = $xpath->query("activity:object-type/text()", $activity)->item(0)->nodeValue;
1253 XML::addElement($obj_doc, $obj_element, "type", $activity_type);
1255 $id = $xpath->query("atom:id", $activity)->item(0);
1256 if (is_object($id)) {
1257 $obj_element->appendChild($obj_doc->importNode($id, true));
1260 $title = $xpath->query("atom:title", $activity)->item(0);
1261 if (is_object($title)) {
1262 $obj_element->appendChild($obj_doc->importNode($title, true));
1265 $links = $xpath->query("atom:link", $activity);
1266 if (is_object($links)) {
1267 foreach ($links as $link) {
1268 $obj_element->appendChild($obj_doc->importNode($link, true));
1272 $content = $xpath->query("atom:content", $activity)->item(0);
1273 if (is_object($content)) {
1274 $obj_element->appendChild($obj_doc->importNode($content, true));
1277 $obj_doc->appendChild($obj_element);
1279 $objxml = $obj_doc->saveXML($obj_element);
1281 /// @todo This isn't totally clean. We should find a way to transform the namespaces
1282 $objxml = str_replace("<".$element.' xmlns="http://www.w3.org/2005/Atom">', "<".$element.">", $objxml);
1287 * Processes the mail elements
1289 * @param object $xpath XPath object
1290 * @param object $mail mail elements
1291 * @param array $importer Record of the importer user mixed with contact of the content
1293 * @throws \Exception
1294 * @todo Find good type-hints for all parameter
1296 private static function processMail($xpath, $mail, $importer)
1298 Logger::log("Processing mails");
1301 $msg["uid"] = $importer["importer_uid"];
1302 $msg["from-name"] = XML::getFirstValue($xpath, "dfrn:sender/dfrn:name/text()", $mail);
1303 $msg["from-url"] = XML::getFirstValue($xpath, "dfrn:sender/dfrn:uri/text()", $mail);
1304 $msg["from-photo"] = XML::getFirstValue($xpath, "dfrn:sender/dfrn:avatar/text()", $mail);
1305 $msg["contact-id"] = $importer["id"];
1306 $msg["uri"] = XML::getFirstValue($xpath, "dfrn:id/text()", $mail);
1307 $msg["parent-uri"] = XML::getFirstValue($xpath, "dfrn:in-reply-to/text()", $mail);
1308 $msg["created"] = DateTimeFormat::utc(XML::getFirstValue($xpath, "dfrn:sentdate/text()", $mail));
1309 $msg["title"] = XML::getFirstValue($xpath, "dfrn:subject/text()", $mail);
1310 $msg["body"] = XML::getFirstValue($xpath, "dfrn:content/text()", $mail);
1316 * Processes the suggestion elements
1318 * @param object $xpath XPath object
1319 * @param object $suggestion suggestion elements
1320 * @param array $importer Record of the importer user mixed with contact of the content
1322 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1323 * @todo Find good type-hints for all parameter
1325 private static function processSuggestion($xpath, $suggestion, $importer)
1327 Logger::notice('Processing suggestions');
1329 $url = $xpath->evaluate('string(dfrn:url[1]/text())', $suggestion);
1330 $cid = Contact::getIdForURL($url);
1331 $note = $xpath->evaluate('string(dfrn:note[1]/text())', $suggestion);
1333 return FContact::addSuggestion($importer['importer_uid'], $cid, $importer['id'], $note);
1337 * Processes the relocation elements
1339 * @param object $xpath XPath object
1340 * @param object $relocation relocation elements
1341 * @param array $importer Record of the importer user mixed with contact of the content
1343 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1344 * @throws \ImagickException
1345 * @todo Find good type-hints for all parameter
1347 private static function processRelocation($xpath, $relocation, $importer)
1349 Logger::log("Processing relocations");
1351 /// @TODO Rewrite this to one statement
1353 $relocate["uid"] = $importer["importer_uid"];
1354 $relocate["cid"] = $importer["id"];
1355 $relocate["url"] = $xpath->query("dfrn:url/text()", $relocation)->item(0)->nodeValue;
1356 $relocate["addr"] = $xpath->query("dfrn:addr/text()", $relocation)->item(0)->nodeValue;
1357 $relocate["name"] = $xpath->query("dfrn:name/text()", $relocation)->item(0)->nodeValue;
1358 $relocate["avatar"] = $xpath->query("dfrn:avatar/text()", $relocation)->item(0)->nodeValue;
1359 $relocate["photo"] = $xpath->query("dfrn:photo/text()", $relocation)->item(0)->nodeValue;
1360 $relocate["thumb"] = $xpath->query("dfrn:thumb/text()", $relocation)->item(0)->nodeValue;
1361 $relocate["micro"] = $xpath->query("dfrn:micro/text()", $relocation)->item(0)->nodeValue;
1362 $relocate["request"] = $xpath->query("dfrn:request/text()", $relocation)->item(0)->nodeValue;
1363 $relocate["confirm"] = $xpath->query("dfrn:confirm/text()", $relocation)->item(0)->nodeValue;
1364 $relocate["notify"] = $xpath->query("dfrn:notify/text()", $relocation)->item(0)->nodeValue;
1365 $relocate["poll"] = $xpath->query("dfrn:poll/text()", $relocation)->item(0)->nodeValue;
1366 $relocate["sitepubkey"] = $xpath->query("dfrn:sitepubkey/text()", $relocation)->item(0)->nodeValue;
1368 if (($relocate["avatar"] == "") && ($relocate["photo"] != "")) {
1369 $relocate["avatar"] = $relocate["photo"];
1372 if ($relocate["addr"] == "") {
1373 $relocate["addr"] = preg_replace("=(https?://)(.*)/profile/(.*)=ism", "$3@$2", $relocate["url"]);
1377 $old = Contact::selectFirst(['photo', 'url'], ['id' => $importer["id"], 'uid' => $importer["importer_uid"]]);
1379 if (!DBA::isResult($old)) {
1380 Logger::notice("Query failed to execute, no result returned in " . __FUNCTION__);
1384 // Update the contact table. We try to find every entry.
1385 $fields = ['name' => $relocate["name"], 'avatar' => $relocate["avatar"],
1386 'url' => $relocate["url"], 'nurl' => Strings::normaliseLink($relocate["url"]),
1387 'addr' => $relocate["addr"], 'request' => $relocate["request"],
1388 'confirm' => $relocate["confirm"], 'notify' => $relocate["notify"],
1389 'poll' => $relocate["poll"], 'site-pubkey' => $relocate["sitepubkey"]];
1390 $condition = ["(`id` = ?) OR (`nurl` = ?)", $importer["id"], Strings::normaliseLink($old["url"])];
1392 Contact::update($fields, $condition);
1394 Contact::updateAvatar($importer["id"], $relocate["avatar"], true);
1396 Logger::log('Contacts are updated.');
1399 /// merge with current record, current contents have priority
1400 /// update record, set url-updated
1401 /// update profile photos
1402 /// schedule a scan?
1409 * @param array $current the current item record
1410 * @param array $item the new item record
1411 * @param array $importer Record of the importer user mixed with contact of the content
1412 * @param int $entrytype Is it a toplevel entry, a comment or a relayed comment?
1414 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1415 * @todo set proper type-hints (array?)
1417 private static function updateContent($current, $item, $importer, $entrytype)
1421 if (self::isEditedTimestampNewer($current, $item)) {
1422 // do not accept (ignore) an earlier edit than one we currently have.
1423 if (DateTimeFormat::utc($item["edited"]) < $current["edited"]) {
1427 $fields = ['title' => $item['title'] ?? '', 'body' => $item['body'] ?? '',
1428 'changed' => DateTimeFormat::utcNow(),
1429 'edited' => DateTimeFormat::utc($item["edited"])];
1431 $condition = ["`uri` = ? AND `uid` IN (0, ?)", $item["uri"], $importer["importer_uid"]];
1432 Item::update($fields, $condition);
1440 * Detects the entry type of the item
1442 * @param array $importer Record of the importer user mixed with contact of the content
1443 * @param array $item the new item record
1445 * @return int Is it a toplevel entry, a comment or a relayed comment?
1446 * @throws \Exception
1447 * @todo set proper type-hints (array?)
1449 private static function getEntryType($importer, $item)
1451 if ($item["thr-parent"] != $item["uri"]) {
1454 if ($importer["page-flags"] == User::PAGE_FLAGS_COMMUNITY || $importer["page-flags"] == User::PAGE_FLAGS_PRVGROUP) {
1457 Logger::log("possible community action");
1459 $sql_extra = " AND `self` AND `wall`";
1462 // was the top-level post for this action written by somebody on this site?
1463 // Specifically, the recipient?
1464 $parent = Post::selectFirst(['forum_mode', 'wall'],
1465 ["`uri` = ? AND `uid` = ?" . $sql_extra, $item["thr-parent"], $importer["importer_uid"]]);
1467 $is_a_remote_action = DBA::isResult($parent);
1470 * Does this have the characteristics of a community or private group action?
1471 * If it's an action to a wall post on a community/prvgroup page it's a
1472 * valid community action. Also forum_mode makes it valid for sure.
1473 * If neither, it's not.
1475 if ($is_a_remote_action && $community && (!$parent["forum_mode"]) && (!$parent["wall"])) {
1476 $is_a_remote_action = false;
1477 Logger::log("not a community action");
1480 if ($is_a_remote_action) {
1481 return DFRN::REPLY_RC;
1486 return DFRN::TOP_LEVEL;
1493 * @param array $item The new item record
1494 * @param array $importer Record of the importer user mixed with contact of the content
1496 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1497 * @todo set proper type-hints (array?)
1499 private static function doPoke(array $item, array $importer)
1501 $verb = urldecode(substr($item["verb"], strpos($item["verb"], "#")+1));
1505 $xo = XML::parseString($item["object"]);
1507 if (($xo->type == Activity\ObjectType::PERSON) && ($xo->id)) {
1508 // somebody was poked/prodded. Was it me?
1510 foreach ($xo->link as $l) {
1511 $atts = $l->attributes();
1512 switch ($atts["rel"]) {
1514 $Blink = $atts["href"];
1521 if ($Blink && Strings::compareLink($Blink, DI::baseUrl() . "/profile/" . $importer["nickname"])) {
1522 $author = DBA::selectFirst('contact', ['id', 'name', 'thumb', 'url'], ['id' => $item['author-id']]);
1524 $parent = Post::selectFirst(['id'], ['uri' => $item['thr-parent'], 'uid' => $importer["importer_uid"]]);
1525 $item['parent'] = $parent['id'];
1527 // send a notification
1530 "type" => Notification\Type::POKE,
1531 "otype" => Notification\ObjectType::PERSON,
1532 "activity" => $verb,
1533 "verb" => $item["verb"],
1534 "uid" => $importer["importer_uid"],
1535 "cid" => $author["id"],
1537 "link" => DI::baseUrl() . "/display/" . urlencode($item['guid']),
1545 * Processes several actions, depending on the verb
1547 * @param int $entrytype Is it a toplevel entry, a comment or a relayed comment?
1548 * @param array $importer Record of the importer user mixed with contact of the content
1549 * @param array $item the new item record
1550 * @param bool $is_like Is the verb a "like"?
1552 * @return bool Should the processing of the entries be continued?
1553 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1554 * @todo set proper type-hints (array?)
1556 private static function processVerbs($entrytype, $importer, &$item, &$is_like)
1558 Logger::log("Process verb ".$item["verb"]." and object-type ".$item["object-type"]." for entrytype ".$entrytype, Logger::DEBUG);
1560 if (($entrytype == DFRN::TOP_LEVEL) && !empty($importer['id'])) {
1561 // The filling of the the "contact" variable is done for legcy reasons
1562 // The functions below are partly used by ostatus.php as well - where we have this variable
1563 $contact = Contact::selectFirst([], ['id' => $importer['id']]);
1565 $activity = DI::activity();
1567 // Big question: Do we need these functions? They were part of the "consume_feed" function.
1568 // This function once was responsible for DFRN and OStatus.
1569 if ($activity->match($item["verb"], Activity::FOLLOW)) {
1570 Logger::log("New follower");
1571 Contact::addRelationship($importer, $contact, $item);
1574 if ($activity->match($item["verb"], Activity::UNFOLLOW)) {
1575 Logger::log("Lost follower");
1576 Contact::removeFollower($contact);
1579 if ($activity->match($item["verb"], Activity::REQ_FRIEND)) {
1580 Logger::log("New friend request");
1581 Contact::addRelationship($importer, $contact, $item, true);
1584 if ($activity->match($item["verb"], Activity::UNFRIEND)) {
1585 Logger::log("Lost sharer");
1586 Contact::removeSharer($importer, $contact, $item);
1590 if (($item["verb"] == Activity::LIKE)
1591 || ($item["verb"] == Activity::DISLIKE)
1592 || ($item["verb"] == Activity::ATTEND)
1593 || ($item["verb"] == Activity::ATTENDNO)
1594 || ($item["verb"] == Activity::ATTENDMAYBE)
1595 || ($item["verb"] == Activity::ANNOUNCE)
1598 $item["gravity"] = GRAVITY_ACTIVITY;
1599 // only one like or dislike per person
1600 // split into two queries for performance issues
1601 $condition = ['uid' => $item["uid"], 'author-id' => $item["author-id"], 'gravity' => GRAVITY_ACTIVITY,
1602 'verb' => $item['verb'], 'parent-uri' => $item['thr-parent']];
1603 if (Post::exists($condition)) {
1607 $condition = ['uid' => $item["uid"], 'author-id' => $item["author-id"], 'gravity' => GRAVITY_ACTIVITY,
1608 'verb' => $item['verb'], 'thr-parent' => $item['thr-parent']];
1609 if (Post::exists($condition)) {
1613 // The owner of an activity must be the author
1614 $item["owner-name"] = $item["author-name"];
1615 $item["owner-link"] = $item["author-link"];
1616 $item["owner-avatar"] = $item["author-avatar"];
1617 $item["owner-id"] = $item["author-id"];
1622 if (($item["verb"] == Activity::TAG) && ($item["object-type"] == Activity\ObjectType::TAGTERM)) {
1623 $xo = XML::parseString($item["object"]);
1624 $xt = XML::parseString($item["target"]);
1626 if ($xt->type == Activity\ObjectType::NOTE) {
1627 $item_tag = Post::selectFirst(['id', 'uri-id'], ['uri' => $xt->id, 'uid' => $importer["importer_uid"]]);
1629 if (!DBA::isResult($item_tag)) {
1630 Logger::log("Query failed to execute, no result returned in " . __FUNCTION__);
1634 // extract tag, if not duplicate, add to parent item
1636 Tag::store($item_tag['uri-id'], Tag::HASHTAG, $xo->content);
1645 * Processes the link elements
1647 * @param object $links link elements
1648 * @param array $item the item record
1650 * @todo set proper type-hints
1652 private static function parseLinks($links, &$item)
1659 foreach ($links as $link) {
1660 foreach ($link->attributes as $attributes) {
1661 switch ($attributes->name) {
1662 case "href" : $href = $attributes->textContent; break;
1663 case "rel" : $rel = $attributes->textContent; break;
1664 case "type" : $type = $attributes->textContent; break;
1665 case "length": $length = $attributes->textContent; break;
1666 case "title" : $title = $attributes->textContent; break;
1669 if (($rel != "") && ($href != "")) {
1672 $item["plink"] = $href;
1675 Post\Media::insert(['uri-id' => $item['uri-id'], 'type' => Post\Media::DOCUMENT,
1676 'url' => $href, 'mimetype' => $type, 'size' => $length, 'description' => $title]);
1684 * Checks if an incoming message is wanted
1686 * @param array $item
1687 * @return boolean Is the message wanted?
1689 private static function isSolicitedMessage(array $item)
1691 if (DBA::exists('contact', ["`nurl` = ? AND `uid` != ? AND `rel` IN (?, ?)",
1692 Strings::normaliseLink($item["author-link"]), 0, Contact::FRIEND, Contact::SHARING])) {
1693 Logger::info('Author has got followers - accepted', ['uri' => $item['uri'], 'author' => $item["author-link"]]);
1697 $taglist = Tag::getByURIId($item['uri-id'], [Tag::HASHTAG]);
1698 $tags = array_column($taglist, 'name');
1699 return Relay::isSolicitedPost($tags, $item['body'], $item['author-id'], $item['uri'], Protocol::DFRN);
1703 * Processes the entry elements which contain the items and comments
1705 * @param array $header Array of the header elements that always stay the same
1706 * @param object $xpath XPath object
1707 * @param object $entry entry elements
1708 * @param array $importer Record of the importer user mixed with contact of the content
1709 * @param string $xml xml
1711 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1712 * @throws \ImagickException
1713 * @todo Add type-hints
1715 private static function processEntry($header, $xpath, $entry, $importer, $xml, $protocol)
1717 Logger::log("Processing entries");
1721 $item["protocol"] = $protocol;
1723 $item["source"] = $xml;
1726 $item["uri"] = XML::getFirstNodeValue($xpath, "atom:id/text()", $entry);
1728 $item["edited"] = XML::getFirstNodeValue($xpath, "atom:updated/text()", $entry);
1730 $current = Post::selectFirst(['id', 'uid', 'edited', 'body'],
1731 ['uri' => $item["uri"], 'uid' => $importer["importer_uid"]]
1733 // Is there an existing item?
1734 if (DBA::isResult($current) && !self::isEditedTimestampNewer($current, $item)) {
1735 Logger::log("Item ".$item["uri"]." (".$item['edited'].") already existed.", Logger::DEBUG);
1740 $owner = self::fetchauthor($xpath, $entry, $importer, "dfrn:owner", true, $xml);
1742 $owner_unknown = (isset($owner["contact-unknown"]) && $owner["contact-unknown"]);
1744 $item["owner-name"] = $owner["name"];
1745 $item["owner-link"] = $owner["link"];
1746 $item["owner-avatar"] = $owner["avatar"];
1747 $item["owner-id"] = Contact::getIdForURL($owner["link"], 0);
1750 $author = self::fetchauthor($xpath, $entry, $importer, "atom:author", true, $xml);
1752 $item["author-name"] = $author["name"];
1753 $item["author-link"] = $author["link"];
1754 $item["author-avatar"] = $author["avatar"];
1755 $item["author-id"] = Contact::getIdForURL($author["link"], 0);
1757 $item["title"] = XML::getFirstNodeValue($xpath, "atom:title/text()", $entry);
1759 if (!empty($item["title"])) {
1760 $item["post-type"] = Item::PT_ARTICLE;
1762 $item["post-type"] = Item::PT_NOTE;
1765 $item["created"] = XML::getFirstNodeValue($xpath, "atom:published/text()", $entry);
1767 $item["body"] = XML::getFirstNodeValue($xpath, "dfrn:env/text()", $entry);
1768 $item["body"] = str_replace([' ',"\t","\r","\n"], ['','','',''], $item["body"]);
1770 $item["body"] = Strings::base64UrlDecode($item["body"]);
1772 $item["body"] = BBCode::limitBodySize($item["body"]);
1774 /// @todo We should check for a repeated post and if we know the repeated author.
1776 // We don't need the content element since "dfrn:env" is always present
1777 //$item["body"] = $xpath->query("atom:content/text()", $entry)->item(0)->nodeValue;
1779 $item["location"] = XML::getFirstNodeValue($xpath, "dfrn:location/text()", $entry);
1781 $item["coord"] = XML::getFirstNodeValue($xpath, "georss:point", $entry);
1783 $item["private"] = XML::getFirstNodeValue($xpath, "dfrn:private/text()", $entry);
1785 $unlisted = XML::getFirstNodeValue($xpath, "dfrn:unlisted/text()", $entry);
1786 if (!empty($unlisted) && ($item['private'] != Item::PRIVATE)) {
1787 $item['private'] = Item::UNLISTED;
1790 $item["extid"] = XML::getFirstNodeValue($xpath, "dfrn:extid/text()", $entry);
1792 if (XML::getFirstNodeValue($xpath, "dfrn:bookmark/text()", $entry) == "true") {
1793 $item["post-type"] = Item::PT_PAGE;
1796 $notice_info = $xpath->query("statusnet:notice_info", $entry);
1797 if ($notice_info && ($notice_info->length > 0)) {
1798 foreach ($notice_info->item(0)->attributes as $attributes) {
1799 if ($attributes->name == "source") {
1800 $item["app"] = strip_tags($attributes->textContent);
1805 $item["guid"] = XML::getFirstNodeValue($xpath, "dfrn:diaspora_guid/text()", $entry);
1807 $item['uri-id'] = ItemURI::insert(['uri' => $item['uri'], 'guid' => $item['guid']]);
1809 $item["body"] = Item::improveSharedDataInBody($item);
1811 Tag::storeFromBody($item['uri-id'], $item["body"]);
1813 // We store the data from "dfrn:diaspora_signature" in a different table, this is done in "Item::insert"
1814 $dsprsig = XML::unescape(XML::getFirstNodeValue($xpath, "dfrn:diaspora_signature/text()", $entry));
1815 if ($dsprsig != "") {
1816 $signature = json_decode(base64_decode($dsprsig));
1817 // We don't store the old style signatures anymore that also contained the "signature" and "signer"
1818 if (!empty($signature->signed_text) && empty($signature->signature) && empty($signature->signer)) {
1819 $item["diaspora_signed_text"] = $signature->signed_text;
1823 $item["verb"] = XML::getFirstNodeValue($xpath, "activity:verb/text()", $entry);
1825 if (XML::getFirstNodeValue($xpath, "activity:object-type/text()", $entry) != "") {
1826 $item["object-type"] = XML::getFirstNodeValue($xpath, "activity:object-type/text()", $entry);
1829 $object = $xpath->query("activity:object", $entry)->item(0);
1830 $item["object"] = self::transformActivity($xpath, $object, "object");
1832 if (trim($item["object"]) != "") {
1833 $r = XML::parseString($item["object"]);
1834 if (isset($r->type)) {
1835 $item["object-type"] = $r->type;
1839 $target = $xpath->query("activity:target", $entry)->item(0);
1840 $item["target"] = self::transformActivity($xpath, $target, "target");
1842 $categories = $xpath->query("atom:category", $entry);
1844 foreach ($categories as $category) {
1847 foreach ($category->attributes as $attributes) {
1848 if ($attributes->name == "term") {
1849 $term = $attributes->textContent;
1852 if ($attributes->name == "scheme") {
1853 $scheme = $attributes->textContent;
1857 if (($term != "") && ($scheme != "")) {
1858 $parts = explode(":", $scheme);
1859 if ((count($parts) >= 4) && (array_shift($parts) == "X-DFRN")) {
1860 $termurl = array_pop($parts);
1861 $termurl = array_pop($parts) . ':' . $termurl;
1862 Tag::store($item['uri-id'], Tag::IMPLICIT_MENTION, $term, $termurl);
1868 $links = $xpath->query("atom:link", $entry);
1870 self::parseLinks($links, $item);
1873 $item['conversation-uri'] = XML::getFirstNodeValue($xpath, 'ostatus:conversation/text()', $entry);
1875 $conv = $xpath->query('ostatus:conversation', $entry);
1876 if (is_object($conv->item(0))) {
1877 foreach ($conv->item(0)->attributes as $attributes) {
1878 if ($attributes->name == "ref") {
1879 $item['conversation-uri'] = $attributes->textContent;
1881 if ($attributes->name == "href") {
1882 $item['conversation-href'] = $attributes->textContent;
1887 // Is it a reply or a top level posting?
1888 $item['thr-parent'] = $item['uri'];
1890 $inreplyto = $xpath->query("thr:in-reply-to", $entry);
1891 if (is_object($inreplyto->item(0))) {
1892 foreach ($inreplyto->item(0)->attributes as $attributes) {
1893 if ($attributes->name == "ref") {
1894 $item['thr-parent'] = $attributes->textContent;
1899 // Check if the message is wanted
1900 if (($importer['importer_uid'] == 0) && ($item['uri'] == $item['thr-parent'])) {
1901 if (!self::isSolicitedMessage($item)) {
1902 DBA::delete('item-uri', ['uri' => $item['uri']]);
1907 // Get the type of the item (Top level post, reply or remote reply)
1908 $entrytype = self::getEntryType($importer, $item);
1910 // Now assign the rest of the values that depend on the type of the message
1911 if (in_array($entrytype, [DFRN::REPLY, DFRN::REPLY_RC])) {
1912 if (!isset($item["object-type"])) {
1913 $item["object-type"] = Activity\ObjectType::COMMENT;
1916 if ($item["contact-id"] != $owner["contact-id"]) {
1917 $item["contact-id"] = $owner["contact-id"];
1920 if (($item["network"] != $owner["network"]) && ($owner["network"] != "")) {
1921 $item["network"] = $owner["network"];
1924 if ($item["contact-id"] != $author["contact-id"]) {
1925 $item["contact-id"] = $author["contact-id"];
1928 if (($item["network"] != $author["network"]) && ($author["network"] != "")) {
1929 $item["network"] = $author["network"];
1933 // Ensure to have the correct share data
1934 $item = Item::addShareDataFromOriginal($item);
1936 if ($entrytype == DFRN::REPLY_RC) {
1938 } elseif ($entrytype == DFRN::TOP_LEVEL) {
1939 if (!isset($item["object-type"])) {
1940 $item["object-type"] = Activity\ObjectType::NOTE;
1944 if (($item["object-type"] == Activity\ObjectType::EVENT) && !$owner_unknown) {
1945 Logger::log("Item ".$item["uri"]." seems to contain an event.", Logger::DEBUG);
1946 $ev = Event::fromBBCode($item["body"]);
1947 if ((!empty($ev['desc']) || !empty($ev['summary'])) && !empty($ev['start'])) {
1948 Logger::log("Event in item ".$item["uri"]." was found.", Logger::DEBUG);
1949 $ev["cid"] = $importer["id"];
1950 $ev["uid"] = $importer["importer_uid"];
1951 $ev["uri"] = $item["uri"];
1952 $ev["edited"] = $item["edited"];
1953 $ev["private"] = $item["private"];
1954 $ev["guid"] = $item["guid"];
1955 $ev["plink"] = $item["plink"];
1956 $ev["network"] = $item["network"];
1957 $ev["protocol"] = $item["protocol"];
1958 $ev["direction"] = $item["direction"];
1959 $ev["source"] = $item["source"];
1961 $condition = ['uri' => $item["uri"], 'uid' => $importer["importer_uid"]];
1962 $event = DBA::selectFirst('event', ['id'], $condition);
1963 if (DBA::isResult($event)) {
1964 $ev["id"] = $event["id"];
1967 $event_id = Event::store($ev);
1968 Logger::info('Event was stored', ['id' => $event_id]);
1970 $item = Event::getItemArrayForImportedId($event_id, $item);
1975 if (!self::processVerbs($entrytype, $importer, $item, $is_like)) {
1976 Logger::log("Exiting because 'processVerbs' told us so", Logger::DEBUG);
1980 // This check is done here to be able to receive connection requests in "processVerbs"
1981 if (($entrytype == DFRN::TOP_LEVEL) && $owner_unknown) {
1982 Logger::log("Item won't be stored because user " . $importer["importer_uid"] . " doesn't follow " . $item["owner-link"] . ".", Logger::DEBUG);
1987 // Update content if 'updated' changes
1988 if (DBA::isResult($current)) {
1989 if (self::updateContent($current, $item, $importer, $entrytype)) {
1990 Logger::log("Item ".$item["uri"]." was updated.", Logger::DEBUG);
1992 Logger::log("Item " . $item["uri"] . " already existed.", Logger::DEBUG);
1997 if (in_array($entrytype, [DFRN::REPLY, DFRN::REPLY_RC])) {
1998 // Will be overwritten for sharing accounts in Item::insert
1999 if (empty($item['post-reason']) && ($entrytype == DFRN::REPLY)) {
2000 $item['post-reason'] = Item::PR_COMMENT;
2003 $posted_id = Item::insert($item);
2005 Logger::log("Reply from contact ".$item["contact-id"]." was stored with id ".$posted_id, Logger::DEBUG);
2007 if ($item['uid'] == 0) {
2008 Item::distribute($posted_id);
2013 } else { // $entrytype == DFRN::TOP_LEVEL
2014 if (($importer["uid"] == 0) && ($importer["importer_uid"] != 0)) {
2015 Logger::log("Contact ".$importer["id"]." isn't known to user ".$importer["importer_uid"].". The post will be ignored.", Logger::DEBUG);
2018 if (!Strings::compareLink($item["owner-link"], $importer["url"])) {
2020 * The item owner info is not our contact. It's OK and is to be expected if this is a tgroup delivery,
2021 * but otherwise there's a possible data mixup on the sender's system.
2022 * the tgroup delivery code called from Item::insert will correct it if it's a forum,
2023 * but we're going to unconditionally correct it here so that the post will always be owned by our contact.
2025 Logger::log('Correcting item owner.', Logger::DEBUG);
2026 $item["owner-link"] = $importer["url"];
2027 $item["owner-id"] = Contact::getIdForURL($importer["url"], 0);
2030 if (($importer["rel"] == Contact::FOLLOWER) && (!self::tgroupCheck($importer["importer_uid"], $item))) {
2031 Logger::log("Contact ".$importer["id"]." is only follower and tgroup check was negative.", Logger::DEBUG);
2035 // This is my contact on another system, but it's really me.
2036 // Turn this into a wall post.
2037 $notify = Item::isRemoteSelf($importer, $item);
2039 $posted_id = Item::insert($item, $notify);
2042 $posted_id = $notify;
2045 Logger::log("Item was stored with id ".$posted_id, Logger::DEBUG);
2047 if ($item['uid'] == 0) {
2048 Item::distribute($posted_id);
2051 if (stristr($item["verb"], Activity::POKE)) {
2052 $item['id'] = $posted_id;
2053 self::doPoke($item, $importer);
2061 * @param object $xpath XPath object
2062 * @param object $deletion deletion elements
2063 * @param array $importer Record of the importer user mixed with contact of the content
2065 * @throws \Exception
2066 * @todo set proper type-hints
2068 private static function processDeletion($xpath, $deletion, $importer)
2070 Logger::log("Processing deletions");
2073 foreach ($deletion->attributes as $attributes) {
2074 if ($attributes->name == "ref") {
2075 $uri = $attributes->textContent;
2079 if (!$uri || !$importer["id"]) {
2083 $condition = ['uri' => $uri, 'uid' => $importer["importer_uid"]];
2084 $item = Post::selectFirst(['id', 'parent', 'contact-id', 'uri-id', 'deleted', 'gravity'], $condition);
2085 if (!DBA::isResult($item)) {
2086 Logger::log("Item with uri " . $uri . " for user " . $importer["importer_uid"] . " wasn't found.", Logger::DEBUG);
2090 if (DBA::exists('post-category', ['uri-id' => $item['uri-id'], 'uid' => $importer['importer_uid'], 'type' => Post\Category::FILE])) {
2091 Logger::notice("Item is filed. It won't be deleted.", ['uri' => $uri, 'uri-id' => $item['uri_id'], 'uid' => $importer["importer_uid"]]);
2095 // When it is a starting post it has to belong to the person that wants to delete it
2096 if (($item['gravity'] == GRAVITY_PARENT) && ($item['contact-id'] != $importer["id"])) {
2097 Logger::log("Item with uri " . $uri . " don't belong to contact " . $importer["id"] . " - ignoring deletion.", Logger::DEBUG);
2101 // Comments can be deleted by the thread owner or comment owner
2102 if (($item['gravity'] != GRAVITY_PARENT) && ($item['contact-id'] != $importer["id"])) {
2103 $condition = ['id' => $item['parent'], 'contact-id' => $importer["id"]];
2104 if (!Post::exists($condition)) {
2105 Logger::log("Item with uri " . $uri . " wasn't found or mustn't be deleted by contact " . $importer["id"] . " - ignoring deletion.", Logger::DEBUG);
2110 if ($item["deleted"]) {
2114 Logger::log('deleting item '.$item['id'].' uri='.$uri, Logger::DEBUG);
2116 Item::markForDeletion(['id' => $item['id']]);
2120 * Imports a DFRN message
2122 * @param string $xml The DFRN message
2123 * @param array $importer Record of the importer user mixed with contact of the content
2124 * @param int $protocol Transport protocol
2125 * @param int $direction Is the message pushed or pulled?
2126 * @return integer Import status
2127 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2128 * @throws \ImagickException
2129 * @todo set proper type-hints
2131 public static function import($xml, $importer, $protocol, $direction)
2137 $doc = new DOMDocument();
2138 @$doc->loadXML($xml);
2140 $xpath = new DOMXPath($doc);
2141 $xpath->registerNamespace("atom", ActivityNamespace::ATOM1);
2142 $xpath->registerNamespace("thr", ActivityNamespace::THREAD);
2143 $xpath->registerNamespace("at", ActivityNamespace::TOMB);
2144 $xpath->registerNamespace("media", ActivityNamespace::MEDIA);
2145 $xpath->registerNamespace("dfrn", ActivityNamespace::DFRN);
2146 $xpath->registerNamespace("activity", ActivityNamespace::ACTIVITY);
2147 $xpath->registerNamespace("georss", ActivityNamespace::GEORSS);
2148 $xpath->registerNamespace("poco", ActivityNamespace::POCO);
2149 $xpath->registerNamespace("ostatus", ActivityNamespace::OSTATUS);
2150 $xpath->registerNamespace("statusnet", ActivityNamespace::STATUSNET);
2153 $header["uid"] = $importer["importer_uid"];
2154 $header["network"] = Protocol::DFRN;
2155 $header["wall"] = 0;
2156 $header["origin"] = 0;
2157 $header["contact-id"] = $importer["id"];
2158 $header["direction"] = $direction;
2160 if ($direction === Conversation::RELAY) {
2161 $header['post-reason'] = Item::PR_RELAY;
2164 // Update the contact table if the data has changed
2166 // The "atom:author" is only present in feeds
2167 if ($xpath->query("/atom:feed/atom:author")->length > 0) {
2168 self::fetchauthor($xpath, $doc->firstChild, $importer, "atom:author", false, $xml);
2171 // Only the "dfrn:owner" in the head section contains all data
2172 if ($xpath->query("/atom:feed/dfrn:owner")->length > 0) {
2173 self::fetchauthor($xpath, $doc->firstChild, $importer, "dfrn:owner", false, $xml);
2176 Logger::log("Import DFRN message for user " . $importer["importer_uid"] . " from contact " . $importer["id"], Logger::DEBUG);
2178 if (!empty($importer['gsid']) && ($protocol == Conversation::PARCEL_DIASPORA_DFRN)) {
2179 GServer::setProtocol($importer['gsid'], Post\DeliveryData::DFRN);
2182 // is it a public forum? Private forums aren't exposed with this method
2183 $forum = intval(XML::getFirstNodeValue($xpath, "/atom:feed/dfrn:community/text()"));
2185 // The account type is new since 3.5.1
2186 if ($xpath->query("/atom:feed/dfrn:account_type")->length > 0) {
2187 // Hint: We are using separate update calls for uid=0 and uid!=0 since a combined call is bad for the database performance
2189 $accounttype = intval(XML::getFirstNodeValue($xpath, "/atom:feed/dfrn:account_type/text()"));
2191 if ($accounttype != $importer["contact-type"]) {
2192 Contact::update(['contact-type' => $accounttype], ['id' => $importer['id']]);
2194 // Updating the public contact as well
2195 Contact::update(['contact-type' => $accounttype], ['uid' => 0, 'nurl' => $importer['nurl']]);
2197 // A forum contact can either have set "forum" or "prv" - but not both
2198 if ($accounttype == User::ACCOUNT_TYPE_COMMUNITY) {
2199 // It's a forum, so either set the public or private forum flag
2200 $condition = ['(`forum` != ? OR `prv` != ?) AND `id` = ?', $forum, !$forum, $importer['id']];
2201 Contact::update(['forum' => $forum, 'prv' => !$forum], $condition);
2203 // Updating the public contact as well
2204 $condition = ['(`forum` != ? OR `prv` != ?) AND `uid` = 0 AND `nurl` = ?', $forum, !$forum, $importer['nurl']];
2205 Contact::update(['forum' => $forum, 'prv' => !$forum], $condition);
2207 // It's not a forum, so remove the flags
2208 $condition = ['(`forum` OR `prv`) AND `id` = ?', $importer['id']];
2209 Contact::update(['forum' => false, 'prv' => false], $condition);
2211 // Updating the public contact as well
2212 $condition = ['(`forum` OR `prv`) AND `uid` = 0 AND `nurl` = ?', $importer['nurl']];
2213 Contact::update(['forum' => false, 'prv' => false], $condition);
2215 } elseif ($forum != $importer["forum"]) { // Deprecated since 3.5.1
2216 $condition = ['`forum` != ? AND `id` = ?', $forum, $importer["id"]];
2217 Contact::update(['forum' => $forum], $condition);
2219 // Updating the public contact as well
2220 $condition = ['`forum` != ? AND `uid` = 0 AND `nurl` = ?', $forum, $importer['nurl']];
2221 Contact::update(['forum' => $forum], $condition);
2225 // We are processing relocations even if we are ignoring a contact
2226 $relocations = $xpath->query("/atom:feed/dfrn:relocate");
2227 foreach ($relocations as $relocation) {
2228 self::processRelocation($xpath, $relocation, $importer);
2231 if (($importer["uid"] != 0) && !$importer["readonly"]) {
2232 $mails = $xpath->query("/atom:feed/dfrn:mail");
2233 foreach ($mails as $mail) {
2234 self::processMail($xpath, $mail, $importer);
2237 $suggestions = $xpath->query("/atom:feed/dfrn:suggest");
2238 foreach ($suggestions as $suggestion) {
2239 self::processSuggestion($xpath, $suggestion, $importer);
2243 $deletions = $xpath->query("/atom:feed/at:deleted-entry");
2244 if (!empty($deletions)) {
2245 foreach ($deletions as $deletion) {
2246 self::processDeletion($xpath, $deletion, $importer);
2248 if (count($deletions) > 0) {
2249 Logger::notice('Deletions had been processed');
2254 $entries = $xpath->query("/atom:feed/atom:entry");
2255 foreach ($entries as $entry) {
2256 self::processEntry($header, $xpath, $entry, $importer, $xml, $protocol);
2259 Logger::log("Import done for user " . $importer["importer_uid"] . " from contact " . $importer["id"], Logger::DEBUG);
2264 * Returns the activity verb
2266 * @param array $item Item array
2268 * @return string activity verb
2270 private static function constructVerb(array $item)
2272 if ($item['verb']) {
2273 return $item['verb'];
2275 return Activity::POST;
2278 private static function tgroupCheck($uid, $item)
2282 // check that the message originated elsewhere and is a top-level post
2284 if ($item['wall'] || $item['origin'] || ($item['uri'] != $item['thr-parent'])) {
2288 $user = DBA::selectFirst('user', ['page-flags', 'nickname'], ['uid' => $uid]);
2289 if (!DBA::isResult($user)) {
2293 $community_page = ($user['page-flags'] == User::PAGE_FLAGS_COMMUNITY);
2294 $prvgroup = ($user['page-flags'] == User::PAGE_FLAGS_PRVGROUP);
2296 $link = Strings::normaliseLink(DI::baseUrl() . '/profile/' . $user['nickname']);
2299 * Diaspora uses their own hardwired link URL in @-tags
2300 * instead of the one we supply with webfinger
2302 $dlink = Strings::normaliseLink(DI::baseUrl() . '/u/' . $user['nickname']);
2304 $cnt = preg_match_all('/[\@\!]\[url\=(.*?)\](.*?)\[\/url\]/ism', $item['body'], $matches, PREG_SET_ORDER);
2306 foreach ($matches as $mtch) {
2307 if (Strings::compareLink($link, $mtch[1]) || Strings::compareLink($dlink, $mtch[1])) {
2309 Logger::log('mention found: ' . $mtch[2]);
2318 return $community_page || $prvgroup;
2322 * This function returns true if $update has an edited timestamp newer
2323 * than $existing, i.e. $update contains new data which should override
2324 * what's already there. If there is no timestamp yet, the update is
2325 * assumed to be newer. If the update has no timestamp, the existing
2326 * item is assumed to be up-to-date. If the timestamps are equal it
2327 * assumes the update has been seen before and should be ignored.
2332 * @throws \Exception
2334 private static function isEditedTimestampNewer($existing, $update)
2336 if (empty($existing['edited'])) {
2339 if (empty($update['edited'])) {
2343 $existing_edited = DateTimeFormat::utc($existing['edited']);
2344 $update_edited = DateTimeFormat::utc($update['edited']);
2346 return (strcmp($existing_edited, $update_edited) < 0);
2350 * Checks if the given contact url does support DFRN
2352 * @param string $url profile url
2354 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2355 * @throws \ImagickException
2357 public static function isSupportedByContactUrl($url)
2359 $probe = Probe::uri($url, Protocol::DFRN);
2360 return $probe['network'] == Protocol::DFRN;