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\Post;
41 use Friendica\Model\Profile;
42 use Friendica\Model\Tag;
43 use Friendica\Model\User;
44 use Friendica\Network\Probe;
45 use Friendica\Util\Crypto;
46 use Friendica\Util\DateTimeFormat;
47 use Friendica\Util\Images;
48 use Friendica\Util\Network;
49 use Friendica\Util\Proxy;
50 use Friendica\Util\Strings;
51 use Friendica\Util\XML;
54 * This class contain functions to create and send DFRN XML files
59 const TOP_LEVEL = 0; // Top level posting
60 const REPLY = 1; // Regular reply that is stored locally
61 const REPLY_RC = 2; // Reply that will be relayed
64 * Generates an array of contact and user for DFRN imports
66 * This array contains not only the receiver but also the sender of the message.
68 * @param integer $cid Contact id
69 * @param integer $uid User id
71 * @return array importer
74 public static function getImporter($cid, $uid = 0)
76 $condition = ['id' => $cid, 'blocked' => false, 'pending' => false];
77 $contact = DBA::selectFirst('contact', [], $condition);
78 if (!DBA::isResult($contact)) {
82 $contact['cpubkey'] = $contact['pubkey'];
83 $contact['cprvkey'] = $contact['prvkey'];
84 $contact['senderName'] = $contact['name'];
87 $condition = ['uid' => $uid, 'account_expired' => false, 'account_removed' => false];
88 $user = DBA::selectFirst('user', [], $condition);
89 if (!DBA::isResult($user)) {
93 $user['importer_uid'] = $user['uid'];
94 $user['uprvkey'] = $user['prvkey'];
96 $user = ['importer_uid' => 0, 'uprvkey' => '', 'timezone' => 'UTC',
97 'nickname' => '', 'sprvkey' => '', 'spubkey' => '',
98 'page-flags' => 0, 'account-type' => 0, 'prvnets' => 0];
101 return array_merge($contact, $user);
105 * Generates the atom entries for delivery.php
107 * This function is used whenever content is transmitted via DFRN.
109 * @param array $items Item elements
110 * @param array $owner Owner record
112 * @return string DFRN entries
113 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
114 * @throws \ImagickException
115 * @todo Find proper type-hints
117 public static function entries($items, $owner)
119 $doc = new DOMDocument('1.0', 'utf-8');
120 $doc->formatOutput = true;
122 $root = self::addHeader($doc, $owner, "dfrn:owner", "", false);
124 if (! count($items)) {
125 return trim($doc->saveXML());
128 foreach ($items as $item) {
129 // These values aren't sent when sending from the queue.
130 /// @todo Check if we can set these values from the queue or if they are needed at all.
131 $item["entry:comment-allow"] = ($item["entry:comment-allow"] ?? '') ?: true;
132 $item["entry:cid"] = $item["entry:cid"] ?? 0;
134 $entry = self::entry($doc, "text", $item, $owner, $item["entry:comment-allow"], $item["entry:cid"]);
136 $root->appendChild($entry);
140 return trim($doc->saveXML());
144 * Generate an atom entry for a given uri id and user
146 * @param int $uri_id The uri id
147 * @param int $uid The user id
148 * @param boolean $conversation Show the conversation. If false show the single post.
150 * @return string DFRN feed entry
151 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
152 * @throws \ImagickException
154 public static function itemFeed(int $uri_id, int $uid, bool $conversation = false)
157 $condition = ['parent-uri-id' => $uri_id];
159 $condition = ['uri-id' => $uri_id];
162 $condition['uid'] = $uid;
164 $items = Post::selectToArray(Item::DELIVER_FIELDLIST, $condition);
165 if (!DBA::isResult($items)) {
171 if ($item['uid'] != 0) {
172 $owner = User::getOwnerDataById($item['uid']);
177 $owner = ['uid' => 0, 'nick' => 'feed-item'];
180 $doc = new DOMDocument('1.0', 'utf-8');
181 $doc->formatOutput = true;
185 $root = $doc->createElementNS(ActivityNamespace::ATOM1, 'feed');
186 $doc->appendChild($root);
188 $root->setAttribute("xmlns:thr", ActivityNamespace::THREAD);
189 $root->setAttribute("xmlns:at", ActivityNamespace::TOMB);
190 $root->setAttribute("xmlns:media", ActivityNamespace::MEDIA);
191 $root->setAttribute("xmlns:dfrn", ActivityNamespace::DFRN);
192 $root->setAttribute("xmlns:activity", ActivityNamespace::ACTIVITY);
193 $root->setAttribute("xmlns:georss", ActivityNamespace::GEORSS);
194 $root->setAttribute("xmlns:poco", ActivityNamespace::POCO);
195 $root->setAttribute("xmlns:ostatus", ActivityNamespace::OSTATUS);
196 $root->setAttribute("xmlns:statusnet", ActivityNamespace::STATUSNET);
198 //$root = self::addHeader($doc, $owner, "dfrn:owner", "", false);
200 foreach ($items as $item) {
201 $entry = self::entry($doc, $type, $item, $owner, true, 0);
203 $root->appendChild($entry);
207 self::entry($doc, $type, $item, $owner, true, 0, true);
210 $atom = trim($doc->saveXML());
215 * Create XML text for DFRN mails
217 * @param array $mail Mail record
218 * @param array $owner Owner record
220 * @return string DFRN mail
221 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
222 * @todo Find proper type-hints
224 public static function mail(array $mail, array $owner)
226 $doc = new DOMDocument('1.0', 'utf-8');
227 $doc->formatOutput = true;
229 $root = self::addHeader($doc, $owner, "dfrn:owner", "", false);
231 $mailElement = $doc->createElement("dfrn:mail");
232 $senderElement = $doc->createElement("dfrn:sender");
234 XML::addElement($doc, $senderElement, "dfrn:name", $owner['name']);
235 XML::addElement($doc, $senderElement, "dfrn:uri", $owner['url']);
236 XML::addElement($doc, $senderElement, "dfrn:avatar", $owner['thumb']);
238 $mailElement->appendChild($senderElement);
240 XML::addElement($doc, $mailElement, "dfrn:id", $mail['uri']);
241 XML::addElement($doc, $mailElement, "dfrn:in-reply-to", $mail['parent-uri']);
242 XML::addElement($doc, $mailElement, "dfrn:sentdate", DateTimeFormat::utc($mail['created'] . '+00:00', DateTimeFormat::ATOM));
243 XML::addElement($doc, $mailElement, "dfrn:subject", $mail['title']);
244 XML::addElement($doc, $mailElement, "dfrn:content", $mail['body']);
246 $root->appendChild($mailElement);
248 return trim($doc->saveXML());
252 * Create XML text for DFRN friend suggestions
254 * @param array $item suggestion elements
255 * @param array $owner Owner record
257 * @return string DFRN suggestions
258 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
259 * @todo Find proper type-hints
261 public static function fsuggest($item, $owner)
263 $doc = new DOMDocument('1.0', 'utf-8');
264 $doc->formatOutput = true;
266 $root = self::addHeader($doc, $owner, "dfrn:owner", "", false);
268 $suggest = $doc->createElement("dfrn:suggest");
270 XML::addElement($doc, $suggest, "dfrn:url", $item['url']);
271 XML::addElement($doc, $suggest, "dfrn:name", $item['name']);
272 XML::addElement($doc, $suggest, "dfrn:photo", $item['photo']);
273 XML::addElement($doc, $suggest, "dfrn:request", $item['request']);
274 XML::addElement($doc, $suggest, "dfrn:note", $item['note']);
276 $root->appendChild($suggest);
278 return trim($doc->saveXML());
282 * Create XML text for DFRN relocations
284 * @param array $owner Owner record
285 * @param int $uid User ID
287 * @return string DFRN relocations
288 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
289 * @todo Find proper type-hints
291 public static function relocate($owner, $uid)
294 /* get site pubkey. this could be a new installation with no site keys*/
295 $pubkey = DI::config()->get('system', 'site_pubkey');
297 $res = Crypto::newKeypair(1024);
298 DI::config()->set('system', 'site_prvkey', $res['prvkey']);
299 DI::config()->set('system', 'site_pubkey', $res['pubkey']);
303 "SELECT `resource-id` , `scale`, type FROM `photo`
304 WHERE `profile` = 1 AND `uid` = %d ORDER BY scale;",
308 $ext = Images::supportedTypes();
310 foreach ($rp as $p) {
311 $photos[$p['scale']] = DI::baseUrl().'/photo/'.$p['resource-id'].'-'.$p['scale'].'.'.$ext[$p['type']];
315 $doc = new DOMDocument('1.0', 'utf-8');
316 $doc->formatOutput = true;
318 $root = self::addHeader($doc, $owner, "dfrn:owner", "", false);
320 $relocate = $doc->createElement("dfrn:relocate");
322 XML::addElement($doc, $relocate, "dfrn:url", $owner['url']);
323 XML::addElement($doc, $relocate, "dfrn:name", $owner['name']);
324 XML::addElement($doc, $relocate, "dfrn:addr", $owner['addr']);
325 XML::addElement($doc, $relocate, "dfrn:avatar", $owner['avatar']);
326 XML::addElement($doc, $relocate, "dfrn:photo", $photos[4]);
327 XML::addElement($doc, $relocate, "dfrn:thumb", $photos[5]);
328 XML::addElement($doc, $relocate, "dfrn:micro", $photos[6]);
329 XML::addElement($doc, $relocate, "dfrn:request", $owner['request']);
330 XML::addElement($doc, $relocate, "dfrn:confirm", $owner['confirm']);
331 XML::addElement($doc, $relocate, "dfrn:notify", $owner['notify']);
332 XML::addElement($doc, $relocate, "dfrn:poll", $owner['poll']);
333 XML::addElement($doc, $relocate, "dfrn:sitepubkey", DI::config()->get('system', 'site_pubkey'));
335 $root->appendChild($relocate);
337 return trim($doc->saveXML());
341 * Adds the header elements for the DFRN protocol
343 * @param DOMDocument $doc XML document
344 * @param array $owner Owner record
345 * @param string $authorelement Element name for the author
346 * @param string $alternatelink link to profile or category
347 * @param bool $public Is it a header for public posts?
349 * @return object XML root object
350 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
351 * @todo Find proper type-hints
353 private static function addHeader(DOMDocument $doc, $owner, $authorelement, $alternatelink = "", $public = false)
356 if ($alternatelink == "") {
357 $alternatelink = $owner['url'];
360 $root = $doc->createElementNS(ActivityNamespace::ATOM1, 'feed');
361 $doc->appendChild($root);
363 $root->setAttribute("xmlns:thr", ActivityNamespace::THREAD);
364 $root->setAttribute("xmlns:at", ActivityNamespace::TOMB);
365 $root->setAttribute("xmlns:media", ActivityNamespace::MEDIA);
366 $root->setAttribute("xmlns:dfrn", ActivityNamespace::DFRN);
367 $root->setAttribute("xmlns:activity", ActivityNamespace::ACTIVITY);
368 $root->setAttribute("xmlns:georss", ActivityNamespace::GEORSS);
369 $root->setAttribute("xmlns:poco", ActivityNamespace::POCO);
370 $root->setAttribute("xmlns:ostatus", ActivityNamespace::OSTATUS);
371 $root->setAttribute("xmlns:statusnet", ActivityNamespace::STATUSNET);
373 XML::addElement($doc, $root, "id", DI::baseUrl()."/profile/".$owner["nick"]);
374 XML::addElement($doc, $root, "title", $owner["name"]);
376 $attributes = ["uri" => "https://friendi.ca", "version" => FRIENDICA_VERSION."-".DB_UPDATE_VERSION];
377 XML::addElement($doc, $root, "generator", FRIENDICA_PLATFORM, $attributes);
379 $attributes = ["rel" => "license", "href" => "http://creativecommons.org/licenses/by/3.0/"];
380 XML::addElement($doc, $root, "link", "", $attributes);
382 $attributes = ["rel" => "alternate", "type" => "text/html", "href" => $alternatelink];
383 XML::addElement($doc, $root, "link", "", $attributes);
387 // DFRN itself doesn't uses this. But maybe someone else wants to subscribe to the public feed.
388 OStatus::hublinks($doc, $root, $owner["nick"]);
390 $attributes = ["rel" => "salmon", "href" => DI::baseUrl()."/salmon/".$owner["nick"]];
391 XML::addElement($doc, $root, "link", "", $attributes);
393 $attributes = ["rel" => "http://salmon-protocol.org/ns/salmon-replies", "href" => DI::baseUrl()."/salmon/".$owner["nick"]];
394 XML::addElement($doc, $root, "link", "", $attributes);
396 $attributes = ["rel" => "http://salmon-protocol.org/ns/salmon-mention", "href" => DI::baseUrl()."/salmon/".$owner["nick"]];
397 XML::addElement($doc, $root, "link", "", $attributes);
400 // For backward compatibility we keep this element
401 if ($owner['page-flags'] == User::PAGE_FLAGS_COMMUNITY) {
402 XML::addElement($doc, $root, "dfrn:community", 1);
405 // The former element is replaced by this one
406 XML::addElement($doc, $root, "dfrn:account_type", $owner["account-type"]);
408 /// @todo We need a way to transmit the different page flags like "User::PAGE_FLAGS_PRVGROUP"
410 XML::addElement($doc, $root, "updated", DateTimeFormat::utcNow(DateTimeFormat::ATOM));
412 $author = self::addAuthor($doc, $owner, $authorelement, $public);
413 $root->appendChild($author);
419 * Adds the author element in the header for the DFRN protocol
421 * @param DOMDocument $doc XML document
422 * @param array $owner Owner record
423 * @param string $authorelement Element name for the author
424 * @param boolean $public boolean
426 * @return \DOMElement XML author object
427 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
428 * @todo Find proper type-hints
430 private static function addAuthor(DOMDocument $doc, array $owner, $authorelement, $public)
432 // Should the profile be "unsearchable" in the net? Then add the "hide" element
433 $hide = DBA::exists('profile', ['uid' => $owner['uid'], 'net-publish' => false]);
435 $author = $doc->createElement($authorelement);
437 $namdate = DateTimeFormat::utc($owner['name-date'].'+00:00', DateTimeFormat::ATOM);
438 $picdate = DateTimeFormat::utc($owner['avatar-date'].'+00:00', DateTimeFormat::ATOM);
442 if (!$public || !$hide) {
443 $attributes = ["dfrn:updated" => $namdate];
446 XML::addElement($doc, $author, "name", $owner["name"], $attributes);
447 XML::addElement($doc, $author, "uri", DI::baseUrl().'/profile/'.$owner["nickname"], $attributes);
448 XML::addElement($doc, $author, "dfrn:handle", $owner["addr"], $attributes);
450 $attributes = ["rel" => "photo", "type" => "image/jpeg",
451 "media:width" => Proxy::PIXEL_SMALL, "media:height" => Proxy::PIXEL_SMALL,
452 "href" => Contact::getAvatarUrlForId($owner['id'], Proxy::SIZE_SMALL, $owner['updated'])];
454 if (!$public || !$hide) {
455 $attributes["dfrn:updated"] = $picdate;
458 XML::addElement($doc, $author, "link", "", $attributes);
460 $attributes["rel"] = "avatar";
461 XML::addElement($doc, $author, "link", "", $attributes);
464 XML::addElement($doc, $author, "dfrn:hide", "true");
467 // The following fields will only be generated if the data isn't meant for a public feed
472 $birthday = feed_birthday($owner['uid'], $owner['timezone']);
475 XML::addElement($doc, $author, "dfrn:birthday", $birthday);
478 // Only show contact details when we are allowed to
479 $profile = DBA::selectFirst('owner-view',
480 ['about', 'name', 'homepage', 'nickname', 'timezone', 'locality', 'region', 'country-name', 'pub_keywords', 'xmpp', 'dob'],
481 ['uid' => $owner['uid'], 'hidewall' => false]);
482 if (DBA::isResult($profile)) {
483 XML::addElement($doc, $author, "poco:displayName", $profile["name"]);
484 XML::addElement($doc, $author, "poco:updated", $namdate);
486 if (trim($profile["dob"]) > DBA::NULL_DATE) {
487 XML::addElement($doc, $author, "poco:birthday", "0000-".date("m-d", strtotime($profile["dob"])));
490 XML::addElement($doc, $author, "poco:note", $profile["about"]);
491 XML::addElement($doc, $author, "poco:preferredUsername", $profile["nickname"]);
493 $savetz = date_default_timezone_get();
494 date_default_timezone_set($profile["timezone"]);
495 XML::addElement($doc, $author, "poco:utcOffset", date("P"));
496 date_default_timezone_set($savetz);
498 if (trim($profile["homepage"]) != "") {
499 $urls = $doc->createElement("poco:urls");
500 XML::addElement($doc, $urls, "poco:type", "homepage");
501 XML::addElement($doc, $urls, "poco:value", $profile["homepage"]);
502 XML::addElement($doc, $urls, "poco:primary", "true");
503 $author->appendChild($urls);
506 if (trim($profile["pub_keywords"]) != "") {
507 $keywords = explode(",", $profile["pub_keywords"]);
509 foreach ($keywords as $keyword) {
510 XML::addElement($doc, $author, "poco:tags", trim($keyword));
514 if (trim($profile["xmpp"]) != "") {
515 $ims = $doc->createElement("poco:ims");
516 XML::addElement($doc, $ims, "poco:type", "xmpp");
517 XML::addElement($doc, $ims, "poco:value", $profile["xmpp"]);
518 XML::addElement($doc, $ims, "poco:primary", "true");
519 $author->appendChild($ims);
522 if (trim($profile["locality"].$profile["region"].$profile["country-name"]) != "") {
523 $element = $doc->createElement("poco:address");
525 XML::addElement($doc, $element, "poco:formatted", Profile::formatLocation($profile));
527 if (trim($profile["locality"]) != "") {
528 XML::addElement($doc, $element, "poco:locality", $profile["locality"]);
531 if (trim($profile["region"]) != "") {
532 XML::addElement($doc, $element, "poco:region", $profile["region"]);
535 if (trim($profile["country-name"]) != "") {
536 XML::addElement($doc, $element, "poco:country", $profile["country-name"]);
539 $author->appendChild($element);
547 * Adds the author elements in the "entry" elements of the DFRN protocol
549 * @param DOMDocument $doc XML document
550 * @param string $element Element name for the author
551 * @param string $contact_url Link of the contact
552 * @param array $item Item elements
554 * @return \DOMElement XML author object
555 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
556 * @todo Find proper type-hints
558 private static function addEntryAuthor(DOMDocument $doc, $element, $contact_url, $item)
560 $author = $doc->createElement($element);
562 $contact = Contact::getByURLForUser($contact_url, $item["uid"], false, ['url', 'name', 'addr', 'photo']);
563 if (!empty($contact)) {
564 XML::addElement($doc, $author, "name", $contact["name"]);
565 XML::addElement($doc, $author, "uri", $contact["url"]);
566 XML::addElement($doc, $author, "dfrn:handle", $contact["addr"]);
569 /// - Check real image type and image size
570 /// - Check which of these boths elements we should use
573 "type" => "image/jpeg",
575 "media:height" => 80,
576 "href" => $contact["photo"]];
577 XML::addElement($doc, $author, "link", "", $attributes);
581 "type" => "image/jpeg",
583 "media:height" => 80,
584 "href" => $contact["photo"]];
585 XML::addElement($doc, $author, "link", "", $attributes);
592 * Adds the activity elements
594 * @param DOMDocument $doc XML document
595 * @param string $element Element name for the activity
596 * @param string $activity activity value
597 * @param int $uriid Uri-Id of the post
599 * @return \DOMElement XML activity object
600 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
601 * @todo Find proper type-hints
603 private static function createActivity(DOMDocument $doc, $element, $activity, $uriid)
606 $entry = $doc->createElement($element);
608 $r = XML::parseString($activity);
614 XML::addElement($doc, $entry, "activity:object-type", $r->type);
618 XML::addElement($doc, $entry, "id", $r->id);
622 XML::addElement($doc, $entry, "title", $r->title);
626 if (substr($r->link, 0, 1) == '<') {
627 if (strstr($r->link, '&') && (! strstr($r->link, '&'))) {
628 $r->link = str_replace('&', '&', $r->link);
631 $r->link = preg_replace('/\<link(.*?)\"\>/', '<link$1"/>', $r->link);
633 // XML does need a single element as root element so we add a dummy element here
634 $data = XML::parseString("<dummy>" . $r->link . "</dummy>");
635 if (is_object($data)) {
636 foreach ($data->link as $link) {
638 foreach ($link->attributes() as $parameter => $value) {
639 $attributes[$parameter] = $value;
641 XML::addElement($doc, $entry, "link", "", $attributes);
645 $attributes = ["rel" => "alternate", "type" => "text/html", "href" => $r->link];
646 XML::addElement($doc, $entry, "link", "", $attributes);
650 XML::addElement($doc, $entry, "content", BBCode::convertForUriId($uriid, $r->content, BBCode::EXTERNAL), ["type" => "html"]);
660 * Adds the elements for attachments
662 * @param object $doc XML document
663 * @param object $root XML root
664 * @param array $item Item element
666 * @return void XML attachment object
667 * @todo Find proper type-hints
669 private static function getAttachment($doc, $root, $item)
671 foreach (Post\Media::getByURIId($item['uri-id'], [Post\Media::DOCUMENT, Post\Media::TORRENT, Post\Media::UNKNOWN]) as $attachment) {
672 $attributes = ['rel' => 'enclosure',
673 'href' => $attachment['url'],
674 'type' => $attachment['mimetype']];
676 if (!empty($attachment['size'])) {
677 $attributes['length'] = intval($attachment['size']);
679 if (!empty($attachment['description'])) {
680 $attributes['title'] = $attachment['description'];
683 XML::addElement($doc, $root, 'link', '', $attributes);
688 * Adds the "entry" elements for the DFRN protocol
690 * @param DOMDocument $doc XML document
691 * @param string $type "text" or "html"
692 * @param array $item Item element
693 * @param array $owner Owner record
694 * @param bool $comment Trigger the sending of the "comment" element
695 * @param int $cid Contact ID of the recipient
696 * @param bool $single If set, the entry is created as an XML document with a single "entry" element
698 * @return null|\DOMElement XML entry object
699 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
700 * @throws \ImagickException
701 * @todo Find proper type-hints
703 private static function entry(DOMDocument $doc, $type, array $item, array $owner, $comment = false, $cid = 0, $single = false)
707 if (!$item['parent']) {
708 Logger::notice('Item without parent found.', ['type' => $type, 'item' => $item]);
712 if ($item['deleted']) {
713 $attributes = ["ref" => $item['uri'], "when" => DateTimeFormat::utc($item['edited'] . '+00:00', DateTimeFormat::ATOM)];
714 return XML::createElement($doc, "at:deleted-entry", "", $attributes);
718 $entry = $doc->createElement("entry");
720 $entry = $doc->createElementNS(ActivityNamespace::ATOM1, 'entry');
721 $doc->appendChild($entry);
723 $entry->setAttribute("xmlns:thr", ActivityNamespace::THREAD);
724 $entry->setAttribute("xmlns:at", ActivityNamespace::TOMB);
725 $entry->setAttribute("xmlns:media", ActivityNamespace::MEDIA);
726 $entry->setAttribute("xmlns:dfrn", ActivityNamespace::DFRN);
727 $entry->setAttribute("xmlns:activity", ActivityNamespace::ACTIVITY);
728 $entry->setAttribute("xmlns:georss", ActivityNamespace::GEORSS);
729 $entry->setAttribute("xmlns:poco", ActivityNamespace::POCO);
730 $entry->setAttribute("xmlns:ostatus", ActivityNamespace::OSTATUS);
731 $entry->setAttribute("xmlns:statusnet", ActivityNamespace::STATUSNET);
734 $body = Post\Media::addAttachmentsToBody($item['uri-id'], $item['body'] ?? '');
736 if ($item['private'] == Item::PRIVATE) {
737 $body = Item::fixPrivatePhotos($body, $owner['uid'], $item, $cid);
740 // Remove the abstract element. It is only locally important.
741 $body = BBCode::stripAbstract($body);
744 if ($type == 'html') {
747 if ($item['title'] != "") {
748 $htmlbody = "[b]" . $item['title'] . "[/b]\n\n" . $htmlbody;
751 $htmlbody = BBCode::convertForUriId($item['uri-id'], $htmlbody, BBCode::ACTIVITYPUB);
754 $author = self::addEntryAuthor($doc, "author", $item["author-link"], $item);
755 $entry->appendChild($author);
757 $dfrnowner = self::addEntryAuthor($doc, "dfrn:owner", $item["owner-link"], $item);
758 $entry->appendChild($dfrnowner);
760 if ($item['gravity'] != GRAVITY_PARENT) {
761 $parent = Post::selectFirst(['guid', 'plink'], ['uri' => $item['thr-parent'], 'uid' => $item['uid']]);
762 if (DBA::isResult($parent)) {
763 $attributes = ["ref" => $item['thr-parent'], "type" => "text/html",
764 "href" => $parent['plink'],
765 "dfrn:diaspora_guid" => $parent['guid']];
766 XML::addElement($doc, $entry, "thr:in-reply-to", "", $attributes);
770 // Add conversation data. This is used for OStatus
771 $conversation_href = DI::baseUrl()."/display/".$item["parent-guid"];
772 $conversation_uri = $conversation_href;
774 if (isset($parent_item)) {
775 $conversation = DBA::selectFirst('conversation', ['conversation-uri', 'conversation-href'], ['item-uri' => $item['thr-parent']]);
776 if (DBA::isResult($conversation)) {
777 if ($conversation['conversation-uri'] != '') {
778 $conversation_uri = $conversation['conversation-uri'];
780 if ($conversation['conversation-href'] != '') {
781 $conversation_href = $conversation['conversation-href'];
787 "href" => $conversation_href,
788 "ref" => $conversation_uri];
790 XML::addElement($doc, $entry, "ostatus:conversation", $conversation_uri, $attributes);
792 XML::addElement($doc, $entry, "id", $item["uri"]);
793 XML::addElement($doc, $entry, "title", $item["title"]);
795 XML::addElement($doc, $entry, "published", DateTimeFormat::utc($item["created"] . "+00:00", DateTimeFormat::ATOM));
796 XML::addElement($doc, $entry, "updated", DateTimeFormat::utc($item["edited"] . "+00:00", DateTimeFormat::ATOM));
798 // "dfrn:env" is used to read the content
799 XML::addElement($doc, $entry, "dfrn:env", Strings::base64UrlEncode($body, true));
801 // The "content" field is not read by the receiver. We could remove it when the type is "text"
802 // We keep it at the moment, maybe there is some old version that doesn't read "dfrn:env"
803 XML::addElement($doc, $entry, "content", (($type == 'html') ? $htmlbody : $body), ["type" => $type]);
805 // We save this value in "plink". Maybe we should read it from there as well?
811 ["rel" => "alternate", "type" => "text/html",
812 "href" => DI::baseUrl() . "/display/" . $item["guid"]]
815 // "comment-allow" is some old fashioned stuff for old Friendica versions.
816 // It is included in the rewritten code for completeness
818 XML::addElement($doc, $entry, "dfrn:comment-allow", 1);
821 if ($item['location']) {
822 XML::addElement($doc, $entry, "dfrn:location", $item['location']);
825 if ($item['coord']) {
826 XML::addElement($doc, $entry, "georss:point", $item['coord']);
829 if ($item['private']) {
830 // Friendica versions prior to 2020.3 can't handle "unlisted" properly. So we can only transmit public and private
831 XML::addElement($doc, $entry, "dfrn:private", ($item['private'] == Item::PRIVATE ? Item::PRIVATE : Item::PUBLIC));
832 XML::addElement($doc, $entry, "dfrn:unlisted", $item['private'] == Item::UNLISTED);
835 if ($item['extid']) {
836 XML::addElement($doc, $entry, "dfrn:extid", $item['extid']);
839 if ($item['post-type'] == Item::PT_PAGE) {
840 XML::addElement($doc, $entry, "dfrn:bookmark", "true");
844 XML::addElement($doc, $entry, "statusnet:notice_info", "", ["local_id" => $item['id'], "source" => $item['app']]);
847 XML::addElement($doc, $entry, "dfrn:diaspora_guid", $item["guid"]);
849 // The signed text contains the content in Markdown, the sender handle and the signatur for the content
850 // It is needed for relayed comments to Diaspora.
851 if ($item['signed_text']) {
852 $sign = base64_encode(json_encode(['signed_text' => $item['signed_text'],'signature' => '','signer' => '']));
853 XML::addElement($doc, $entry, "dfrn:diaspora_signature", $sign);
856 XML::addElement($doc, $entry, "activity:verb", self::constructVerb($item));
858 if ($item['object-type'] != "") {
859 XML::addElement($doc, $entry, "activity:object-type", $item['object-type']);
860 } elseif ($item['gravity'] == GRAVITY_PARENT) {
861 XML::addElement($doc, $entry, "activity:object-type", Activity\ObjectType::NOTE);
863 XML::addElement($doc, $entry, "activity:object-type", Activity\ObjectType::COMMENT);
866 $actobj = self::createActivity($doc, "activity:object", $item['object'], $item['uri-id']);
868 $entry->appendChild($actobj);
871 $actarg = self::createActivity($doc, "activity:target", $item['target'], $item['uri-id']);
873 $entry->appendChild($actarg);
876 $tags = Tag::getByURIId($item['uri-id']);
879 foreach ($tags as $tag) {
880 if (($type != 'html') || ($tag['type'] == Tag::HASHTAG)) {
881 XML::addElement($doc, $entry, "category", "", ["scheme" => "X-DFRN:" . Tag::TAG_CHARACTER[$tag['type']] . ":" . $tag['url'], "term" => $tag['name']]);
883 if ($tag['type'] != Tag::HASHTAG) {
884 $mentioned[$tag['url']] = $tag['url'];
889 foreach ($mentioned as $mention) {
890 $condition = ['uid' => $owner["uid"], 'nurl' => Strings::normaliseLink($mention)];
891 $contact = DBA::selectFirst('contact', ['forum', 'prv'], $condition);
893 if (DBA::isResult($contact) && ($contact["forum"] || $contact["prv"])) {
899 ["rel" => "mentioned",
900 "ostatus:object-type" => Activity\ObjectType::GROUP,
909 ["rel" => "mentioned",
910 "ostatus:object-type" => Activity\ObjectType::PERSON,
916 self::getAttachment($doc, $entry, $item);
922 * Transmits atom content to the contacts via the Diaspora transport layer
924 * @param array $owner Owner record
925 * @param array $contact Contact record of the receiver
926 * @param string $atom Content that will be transmitted
928 * @param bool $public_batch
929 * @return int Deliver status. Negative values mean an error.
930 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
931 * @throws \ImagickException
933 public static function transmit($owner, $contact, $atom, $public_batch = false)
935 if (!$public_batch) {
936 if (empty($contact['addr'])) {
937 Logger::log('Empty contact handle for ' . $contact['id'] . ' - ' . $contact['url'] . ' - trying to update it.');
938 if (Contact::updateFromProbe($contact['id'])) {
939 $new_contact = DBA::selectFirst('contact', ['addr'], ['id' => $contact['id']]);
940 $contact['addr'] = $new_contact['addr'];
943 if (empty($contact['addr'])) {
944 Logger::log('Unable to find contact handle for ' . $contact['id'] . ' - ' . $contact['url']);
949 $fcontact = FContact::getByURL($contact['addr']);
950 if (empty($fcontact)) {
951 Logger::log('Unable to find contact details for ' . $contact['id'] . ' - ' . $contact['addr']);
954 $pubkey = $fcontact['pubkey'];
959 $envelope = Diaspora::buildMessage($atom, $owner, $contact, $owner['uprvkey'], $pubkey, $public_batch);
961 // Create the endpoint for public posts. This is some WIP and should later be added to the probing
962 if ($public_batch && empty($contact["batch"])) {
963 $parts = parse_url($contact["notify"]);
964 $path_parts = explode('/', $parts['path']);
965 array_pop($path_parts);
966 $parts['path'] = implode('/', $path_parts);
967 $contact["batch"] = Network::unparseURL($parts);
970 $dest_url = ($public_batch ? $contact["batch"] : $contact["notify"]);
972 if (empty($dest_url)) {
973 Logger::info('Empty destination', ['public' => $public_batch, 'contact' => $contact]);
977 $content_type = ($public_batch ? "application/magic-envelope+xml" : "application/json");
979 $postResult = DI::httpClient()->post($dest_url, $envelope, ['Content-Type' => $content_type]);
980 $xml = $postResult->getBody();
982 $curl_stat = $postResult->getReturnCode();
983 if (empty($curl_stat) || empty($xml)) {
984 Logger::log('Empty answer from ' . $contact['id'] . ' - ' . $dest_url);
985 return -9; // timed out
988 if (($curl_stat == 503) && $postResult->inHeader('retry-after')) {
992 if (strpos($xml, '<?xml') === false) {
993 Logger::log('No valid XML returned from ' . $contact['id'] . ' - ' . $dest_url);
994 Logger::log('Returned XML: ' . $xml, Logger::DATA);
998 $res = XML::parseString($xml);
1000 if (empty($res->status)) {
1004 if (!empty($res->message)) {
1005 Logger::log('Transmit to ' . $dest_url . ' returned status '.$res->status.' - '.$res->message, Logger::DEBUG);
1008 return intval($res->status);
1012 * Fetch the author data from head or entry items
1014 * @param \DOMXPath $xpath XPath object
1015 * @param \DOMNode $context In which context should the data be searched
1016 * @param array $importer Record of the importer user mixed with contact of the content
1017 * @param string $element Element name from which the data is fetched
1018 * @param bool $onlyfetch Should the data only be fetched or should it update the contact record as well
1019 * @param string $xml optional, default empty
1021 * @return array Relevant data of the author
1022 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1023 * @throws \ImagickException
1024 * @todo Find good type-hints for all parameter
1026 private static function fetchauthor(\DOMXPath $xpath, \DOMNode $context, $importer, $element, $onlyfetch, $xml = "")
1029 $author["name"] = XML::getFirstNodeValue($xpath, $element."/atom:name/text()", $context);
1030 $author["link"] = XML::getFirstNodeValue($xpath, $element."/atom:uri/text()", $context);
1032 $fields = ['id', 'uid', 'url', 'network', 'avatar-date', 'avatar', 'name-date', 'uri-date', 'addr',
1033 'name', 'nick', 'about', 'location', 'keywords', 'xmpp', 'bdyear', 'bd', 'hidden', 'contact-type'];
1034 $condition = ["`uid` = ? AND `nurl` = ? AND `network` != ? AND NOT `pending` AND NOT `blocked`",
1035 $importer["importer_uid"], Strings::normaliseLink($author["link"]), Protocol::STATUSNET];
1037 if ($importer['account-type'] != User::ACCOUNT_TYPE_COMMUNITY) {
1038 $condition = DBA::mergeConditions($condition, ['rel' => [Contact::SHARING, Contact::FRIEND]]);
1041 $contact_old = DBA::selectFirst('contact', $fields, $condition);
1043 if (DBA::isResult($contact_old)) {
1044 $author["contact-id"] = $contact_old["id"];
1045 $author["network"] = $contact_old["network"];
1047 Logger::info('Contact not found', ['condition' => $condition]);
1049 $author["contact-unknown"] = true;
1050 $contact = Contact::getByURL($author["link"], null, ["id", "network"]);
1051 $author["contact-id"] = $contact["id"] ?? $importer["id"];
1052 $author["network"] = $contact["network"] ?? $importer["network"];
1056 // Until now we aren't serving different sizes - but maybe later
1058 /// @todo check if "avatar" or "photo" would be the best field in the specification
1059 $avatars = $xpath->query($element . "/atom:link[@rel='avatar']", $context);
1060 foreach ($avatars as $avatar) {
1063 foreach ($avatar->attributes as $attributes) {
1064 /// @TODO Rewrite these similar if() to one switch
1065 if ($attributes->name == "href") {
1066 $href = $attributes->textContent;
1068 if ($attributes->name == "width") {
1069 $width = $attributes->textContent;
1071 if ($attributes->name == "updated") {
1072 $author["avatar-date"] = $attributes->textContent;
1075 if (($width > 0) && ($href != "")) {
1076 $avatarlist[$width] = $href;
1080 if (count($avatarlist) > 0) {
1081 krsort($avatarlist);
1082 $author["avatar"] = current($avatarlist);
1085 if (empty($author['avatar']) && !empty($author['link'])) {
1086 $cid = Contact::getIdForURL($author['link'], 0);
1088 $contact = DBA::selectFirst('contact', ['avatar'], ['id' => $cid]);
1089 if (DBA::isResult($contact)) {
1090 $author['avatar'] = $contact['avatar'];
1095 if (empty($author['avatar'])) {
1096 Logger::log('Empty author: ' . $xml);
1097 $author['avatar'] = '';
1100 if (DBA::isResult($contact_old) && !$onlyfetch) {
1101 Logger::log("Check if contact details for contact " . $contact_old["id"] . " (" . $contact_old["nick"] . ") have to be updated.", Logger::DEBUG);
1103 $poco = ["url" => $contact_old["url"], "network" => $contact_old["network"]];
1105 // When was the last change to name or uri?
1106 $name_element = $xpath->query($element . "/atom:name", $context)->item(0);
1107 foreach ($name_element->attributes as $attributes) {
1108 if ($attributes->name == "updated") {
1109 $poco["name-date"] = $attributes->textContent;
1113 $link_element = $xpath->query($element . "/atom:link", $context)->item(0);
1114 foreach ($link_element->attributes as $attributes) {
1115 if ($attributes->name == "updated") {
1116 $poco["uri-date"] = $attributes->textContent;
1120 // Update contact data
1121 $value = XML::getFirstNodeValue($xpath, $element . "/dfrn:handle/text()", $context);
1123 $poco["addr"] = $value;
1126 $value = XML::getFirstNodeValue($xpath, $element . "/poco:displayName/text()", $context);
1128 $poco["name"] = $value;
1131 $value = XML::getFirstNodeValue($xpath, $element . "/poco:preferredUsername/text()", $context);
1133 $poco["nick"] = $value;
1136 $value = XML::getFirstNodeValue($xpath, $element . "/poco:note/text()", $context);
1138 $poco["about"] = $value;
1141 $value = XML::getFirstNodeValue($xpath, $element . "/poco:address/poco:formatted/text()", $context);
1143 $poco["location"] = $value;
1146 /// @todo Only search for elements with "poco:type" = "xmpp"
1147 $value = XML::getFirstNodeValue($xpath, $element . "/poco:ims/poco:value/text()", $context);
1149 $poco["xmpp"] = $value;
1152 /// @todo Add support for the following fields that we don't support by now in the contact table:
1153 /// - poco:utcOffset
1159 // If the "hide" element is present then the profile isn't searchable.
1160 $hide = intval(XML::getFirstNodeValue($xpath, $element . "/dfrn:hide/text()", $context) == "true");
1162 Logger::log("Hidden status for contact " . $contact_old["url"] . ": " . $hide, Logger::DEBUG);
1164 // If the contact isn't searchable then set the contact to "hidden".
1165 // Problem: This can be manually overridden by the user.
1167 $contact_old["hidden"] = true;
1170 // Save the keywords into the contact table
1172 $tagelements = $xpath->evaluate($element . "/poco:tags/text()", $context);
1173 foreach ($tagelements as $tag) {
1174 $tags[$tag->nodeValue] = $tag->nodeValue;
1178 $poco["keywords"] = implode(", ", $tags);
1181 // "dfrn:birthday" contains the birthday converted to UTC
1182 $birthday = XML::getFirstNodeValue($xpath, $element . "/dfrn:birthday/text()", $context);
1184 $birthday_date = new \DateTime($birthday);
1185 if ($birthday_date > new \DateTime()) {
1186 $poco["bdyear"] = $birthday_date->format("Y");
1188 } catch (\Exception $e) {
1192 // "poco:birthday" is the birthday in the format "yyyy-mm-dd"
1193 $value = XML::getFirstNodeValue($xpath, $element . "/poco:birthday/text()", $context);
1195 if (!in_array($value, ["", "0000-00-00", DBA::NULL_DATE])) {
1196 $bdyear = date("Y");
1197 $value = str_replace(["0000", "0001"], $bdyear, $value);
1199 if (strtotime($value) < time()) {
1200 $value = str_replace($bdyear, $bdyear + 1, $value);
1203 $poco["bd"] = $value;
1206 $contact = array_merge($contact_old, $poco);
1208 if ($contact_old["bdyear"] != $contact["bdyear"]) {
1209 Event::createBirthday($contact, $birthday);
1212 $fields = ['name' => $contact['name'], 'nick' => $contact['nick'], 'about' => $contact['about'],
1213 'location' => $contact['location'], 'addr' => $contact['addr'], 'keywords' => $contact['keywords'],
1214 'bdyear' => $contact['bdyear'], 'bd' => $contact['bd'], 'hidden' => $contact['hidden'],
1215 'xmpp' => $contact['xmpp'], 'name-date' => DateTimeFormat::utc($contact['name-date']),
1216 'unsearchable' => $contact['hidden'], 'uri-date' => DateTimeFormat::utc($contact['uri-date'])];
1218 DBA::update('contact', $fields, ['id' => $contact['id'], 'network' => $contact['network']], $contact_old);
1220 // Update the public contact. Don't set the "hidden" value, this is used differently for public contacts
1221 unset($fields['hidden']);
1222 $condition = ['uid' => 0, 'nurl' => Strings::normaliseLink($contact_old['url'])];
1223 DBA::update('contact', $fields, $condition, true);
1225 Contact::updateAvatar($contact['id'], $author['avatar']);
1227 $pcid = Contact::getIdForURL($contact_old['url']);
1228 if (!empty($pcid)) {
1229 Contact::updateAvatar($pcid, $author['avatar']);
1237 * Transforms activity objects into an XML string
1239 * @param object $xpath XPath object
1240 * @param object $activity Activity object
1241 * @param string $element element name
1243 * @return string XML string
1244 * @todo Find good type-hints for all parameter
1246 private static function transformActivity($xpath, $activity, $element)
1248 if (!is_object($activity)) {
1252 $obj_doc = new DOMDocument("1.0", "utf-8");
1253 $obj_doc->formatOutput = true;
1255 $obj_element = $obj_doc->createElementNS( ActivityNamespace::ATOM1, $element);
1257 $activity_type = $xpath->query("activity:object-type/text()", $activity)->item(0)->nodeValue;
1258 XML::addElement($obj_doc, $obj_element, "type", $activity_type);
1260 $id = $xpath->query("atom:id", $activity)->item(0);
1261 if (is_object($id)) {
1262 $obj_element->appendChild($obj_doc->importNode($id, true));
1265 $title = $xpath->query("atom:title", $activity)->item(0);
1266 if (is_object($title)) {
1267 $obj_element->appendChild($obj_doc->importNode($title, true));
1270 $links = $xpath->query("atom:link", $activity);
1271 if (is_object($links)) {
1272 foreach ($links as $link) {
1273 $obj_element->appendChild($obj_doc->importNode($link, true));
1277 $content = $xpath->query("atom:content", $activity)->item(0);
1278 if (is_object($content)) {
1279 $obj_element->appendChild($obj_doc->importNode($content, true));
1282 $obj_doc->appendChild($obj_element);
1284 $objxml = $obj_doc->saveXML($obj_element);
1286 /// @todo This isn't totally clean. We should find a way to transform the namespaces
1287 $objxml = str_replace("<".$element.' xmlns="http://www.w3.org/2005/Atom">', "<".$element.">", $objxml);
1292 * Processes the mail elements
1294 * @param object $xpath XPath object
1295 * @param object $mail mail elements
1296 * @param array $importer Record of the importer user mixed with contact of the content
1298 * @throws \Exception
1299 * @todo Find good type-hints for all parameter
1301 private static function processMail($xpath, $mail, $importer)
1303 Logger::log("Processing mails");
1306 $msg["uid"] = $importer["importer_uid"];
1307 $msg["from-name"] = XML::getFirstValue($xpath, "dfrn:sender/dfrn:name/text()", $mail);
1308 $msg["from-url"] = XML::getFirstValue($xpath, "dfrn:sender/dfrn:uri/text()", $mail);
1309 $msg["from-photo"] = XML::getFirstValue($xpath, "dfrn:sender/dfrn:avatar/text()", $mail);
1310 $msg["contact-id"] = $importer["id"];
1311 $msg["uri"] = XML::getFirstValue($xpath, "dfrn:id/text()", $mail);
1312 $msg["parent-uri"] = XML::getFirstValue($xpath, "dfrn:in-reply-to/text()", $mail);
1313 $msg["created"] = DateTimeFormat::utc(XML::getFirstValue($xpath, "dfrn:sentdate/text()", $mail));
1314 $msg["title"] = XML::getFirstValue($xpath, "dfrn:subject/text()", $mail);
1315 $msg["body"] = XML::getFirstValue($xpath, "dfrn:content/text()", $mail);
1321 * Processes the suggestion elements
1323 * @param object $xpath XPath object
1324 * @param object $suggestion suggestion elements
1325 * @param array $importer Record of the importer user mixed with contact of the content
1327 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1328 * @todo Find good type-hints for all parameter
1330 private static function processSuggestion($xpath, $suggestion, $importer)
1332 Logger::notice('Processing suggestions');
1334 $url = $xpath->evaluate('string(dfrn:url[1]/text())', $suggestion);
1335 $cid = Contact::getIdForURL($url);
1336 $note = $xpath->evaluate('string(dfrn:note[1]/text())', $suggestion);
1338 return FContact::addSuggestion($importer['importer_uid'], $cid, $importer['id'], $note);
1342 * Processes the relocation elements
1344 * @param object $xpath XPath object
1345 * @param object $relocation relocation elements
1346 * @param array $importer Record of the importer user mixed with contact of the content
1348 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1349 * @throws \ImagickException
1350 * @todo Find good type-hints for all parameter
1352 private static function processRelocation($xpath, $relocation, $importer)
1354 Logger::log("Processing relocations");
1356 /// @TODO Rewrite this to one statement
1358 $relocate["uid"] = $importer["importer_uid"];
1359 $relocate["cid"] = $importer["id"];
1360 $relocate["url"] = $xpath->query("dfrn:url/text()", $relocation)->item(0)->nodeValue;
1361 $relocate["addr"] = $xpath->query("dfrn:addr/text()", $relocation)->item(0)->nodeValue;
1362 $relocate["name"] = $xpath->query("dfrn:name/text()", $relocation)->item(0)->nodeValue;
1363 $relocate["avatar"] = $xpath->query("dfrn:avatar/text()", $relocation)->item(0)->nodeValue;
1364 $relocate["photo"] = $xpath->query("dfrn:photo/text()", $relocation)->item(0)->nodeValue;
1365 $relocate["thumb"] = $xpath->query("dfrn:thumb/text()", $relocation)->item(0)->nodeValue;
1366 $relocate["micro"] = $xpath->query("dfrn:micro/text()", $relocation)->item(0)->nodeValue;
1367 $relocate["request"] = $xpath->query("dfrn:request/text()", $relocation)->item(0)->nodeValue;
1368 $relocate["confirm"] = $xpath->query("dfrn:confirm/text()", $relocation)->item(0)->nodeValue;
1369 $relocate["notify"] = $xpath->query("dfrn:notify/text()", $relocation)->item(0)->nodeValue;
1370 $relocate["poll"] = $xpath->query("dfrn:poll/text()", $relocation)->item(0)->nodeValue;
1371 $relocate["sitepubkey"] = $xpath->query("dfrn:sitepubkey/text()", $relocation)->item(0)->nodeValue;
1373 if (($relocate["avatar"] == "") && ($relocate["photo"] != "")) {
1374 $relocate["avatar"] = $relocate["photo"];
1377 if ($relocate["addr"] == "") {
1378 $relocate["addr"] = preg_replace("=(https?://)(.*)/profile/(.*)=ism", "$3@$2", $relocate["url"]);
1383 "SELECT `photo`, `url` FROM `contact` WHERE `id` = %d AND `uid` = %d",
1384 intval($importer["id"]),
1385 intval($importer["importer_uid"])
1388 if (!DBA::isResult($r)) {
1389 Logger::log("Query failed to execute, no result returned in " . __FUNCTION__);
1395 // Update the contact table. We try to find every entry.
1396 $fields = ['name' => $relocate["name"], 'avatar' => $relocate["avatar"],
1397 'url' => $relocate["url"], 'nurl' => Strings::normaliseLink($relocate["url"]),
1398 'addr' => $relocate["addr"], 'request' => $relocate["request"],
1399 'confirm' => $relocate["confirm"], 'notify' => $relocate["notify"],
1400 'poll' => $relocate["poll"], 'site-pubkey' => $relocate["sitepubkey"]];
1401 $condition = ["(`id` = ?) OR (`nurl` = ?)", $importer["id"], Strings::normaliseLink($old["url"])];
1403 DBA::update('contact', $fields, $condition);
1405 Contact::updateAvatar($importer["id"], $relocate["avatar"], true);
1407 Logger::log('Contacts are updated.');
1410 /// merge with current record, current contents have priority
1411 /// update record, set url-updated
1412 /// update profile photos
1413 /// schedule a scan?
1420 * @param array $current the current item record
1421 * @param array $item the new item record
1422 * @param array $importer Record of the importer user mixed with contact of the content
1423 * @param int $entrytype Is it a toplevel entry, a comment or a relayed comment?
1425 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1426 * @todo set proper type-hints (array?)
1428 private static function updateContent($current, $item, $importer, $entrytype)
1432 if (self::isEditedTimestampNewer($current, $item)) {
1433 // do not accept (ignore) an earlier edit than one we currently have.
1434 if (DateTimeFormat::utc($item["edited"]) < $current["edited"]) {
1438 $fields = ['title' => $item['title'] ?? '', 'body' => $item['body'] ?? '',
1439 'changed' => DateTimeFormat::utcNow(),
1440 'edited' => DateTimeFormat::utc($item["edited"])];
1442 $condition = ["`uri` = ? AND `uid` IN (0, ?)", $item["uri"], $importer["importer_uid"]];
1443 Item::update($fields, $condition);
1451 * Detects the entry type of the item
1453 * @param array $importer Record of the importer user mixed with contact of the content
1454 * @param array $item the new item record
1456 * @return int Is it a toplevel entry, a comment or a relayed comment?
1457 * @throws \Exception
1458 * @todo set proper type-hints (array?)
1460 private static function getEntryType($importer, $item)
1462 if ($item["thr-parent"] != $item["uri"]) {
1465 if ($importer["page-flags"] == User::PAGE_FLAGS_COMMUNITY || $importer["page-flags"] == User::PAGE_FLAGS_PRVGROUP) {
1468 Logger::log("possible community action");
1470 $sql_extra = " AND `self` AND `wall`";
1473 // was the top-level post for this action written by somebody on this site?
1474 // Specifically, the recipient?
1475 $parent = Post::selectFirst(['forum_mode', 'wall'],
1476 ["`uri` = ? AND `uid` = ?" . $sql_extra, $item["thr-parent"], $importer["importer_uid"]]);
1478 $is_a_remote_action = DBA::isResult($parent);
1481 * Does this have the characteristics of a community or private group action?
1482 * If it's an action to a wall post on a community/prvgroup page it's a
1483 * valid community action. Also forum_mode makes it valid for sure.
1484 * If neither, it's not.
1486 if ($is_a_remote_action && $community && (!$parent["forum_mode"]) && (!$parent["wall"])) {
1487 $is_a_remote_action = false;
1488 Logger::log("not a community action");
1491 if ($is_a_remote_action) {
1492 return DFRN::REPLY_RC;
1497 return DFRN::TOP_LEVEL;
1504 * @param array $item The new item record
1505 * @param array $importer Record of the importer user mixed with contact of the content
1507 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1508 * @todo set proper type-hints (array?)
1510 private static function doPoke(array $item, array $importer)
1512 $verb = urldecode(substr($item["verb"], strpos($item["verb"], "#")+1));
1516 $xo = XML::parseString($item["object"]);
1518 if (($xo->type == Activity\ObjectType::PERSON) && ($xo->id)) {
1519 // somebody was poked/prodded. Was it me?
1521 foreach ($xo->link as $l) {
1522 $atts = $l->attributes();
1523 switch ($atts["rel"]) {
1525 $Blink = $atts["href"];
1532 if ($Blink && Strings::compareLink($Blink, DI::baseUrl() . "/profile/" . $importer["nickname"])) {
1533 $author = DBA::selectFirst('contact', ['id', 'name', 'thumb', 'url'], ['id' => $item['author-id']]);
1535 $parent = Post::selectFirst(['id'], ['uri' => $item['thr-parent'], 'uid' => $importer["importer_uid"]]);
1536 $item['parent'] = $parent['id'];
1538 // send a notification
1541 "type" => Notification\Type::POKE,
1542 "otype" => Notification\ObjectType::PERSON,
1543 "activity" => $verb,
1544 "verb" => $item["verb"],
1545 "uid" => $importer["importer_uid"],
1546 "cid" => $author["id"],
1548 "link" => DI::baseUrl() . "/display/" . urlencode($item['guid']),
1556 * Processes several actions, depending on the verb
1558 * @param int $entrytype Is it a toplevel entry, a comment or a relayed comment?
1559 * @param array $importer Record of the importer user mixed with contact of the content
1560 * @param array $item the new item record
1561 * @param bool $is_like Is the verb a "like"?
1563 * @return bool Should the processing of the entries be continued?
1564 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1565 * @todo set proper type-hints (array?)
1567 private static function processVerbs($entrytype, $importer, &$item, &$is_like)
1569 Logger::log("Process verb ".$item["verb"]." and object-type ".$item["object-type"]." for entrytype ".$entrytype, Logger::DEBUG);
1571 if (($entrytype == DFRN::TOP_LEVEL) && !empty($importer['id'])) {
1572 // The filling of the the "contact" variable is done for legcy reasons
1573 // The functions below are partly used by ostatus.php as well - where we have this variable
1574 $contact = Contact::selectFirst([], ['id' => $importer['id']]);
1576 $activity = DI::activity();
1578 // Big question: Do we need these functions? They were part of the "consume_feed" function.
1579 // This function once was responsible for DFRN and OStatus.
1580 if ($activity->match($item["verb"], Activity::FOLLOW)) {
1581 Logger::log("New follower");
1582 Contact::addRelationship($importer, $contact, $item);
1585 if ($activity->match($item["verb"], Activity::UNFOLLOW)) {
1586 Logger::log("Lost follower");
1587 Contact::removeFollower($importer, $contact, $item);
1590 if ($activity->match($item["verb"], Activity::REQ_FRIEND)) {
1591 Logger::log("New friend request");
1592 Contact::addRelationship($importer, $contact, $item, true);
1595 if ($activity->match($item["verb"], Activity::UNFRIEND)) {
1596 Logger::log("Lost sharer");
1597 Contact::removeSharer($importer, $contact, $item);
1601 if (($item["verb"] == Activity::LIKE)
1602 || ($item["verb"] == Activity::DISLIKE)
1603 || ($item["verb"] == Activity::ATTEND)
1604 || ($item["verb"] == Activity::ATTENDNO)
1605 || ($item["verb"] == Activity::ATTENDMAYBE)
1606 || ($item["verb"] == Activity::ANNOUNCE)
1609 $item["gravity"] = GRAVITY_ACTIVITY;
1610 // only one like or dislike per person
1611 // split into two queries for performance issues
1612 $condition = ['uid' => $item["uid"], 'author-id' => $item["author-id"], 'gravity' => GRAVITY_ACTIVITY,
1613 'verb' => $item['verb'], 'parent-uri' => $item['thr-parent']];
1614 if (Post::exists($condition)) {
1618 $condition = ['uid' => $item["uid"], 'author-id' => $item["author-id"], 'gravity' => GRAVITY_ACTIVITY,
1619 'verb' => $item['verb'], 'thr-parent' => $item['thr-parent']];
1620 if (Post::exists($condition)) {
1624 // The owner of an activity must be the author
1625 $item["owner-name"] = $item["author-name"];
1626 $item["owner-link"] = $item["author-link"];
1627 $item["owner-avatar"] = $item["author-avatar"];
1628 $item["owner-id"] = $item["author-id"];
1633 if (($item["verb"] == Activity::TAG) && ($item["object-type"] == Activity\ObjectType::TAGTERM)) {
1634 $xo = XML::parseString($item["object"]);
1635 $xt = XML::parseString($item["target"]);
1637 if ($xt->type == Activity\ObjectType::NOTE) {
1638 $item_tag = Post::selectFirst(['id', 'uri-id'], ['uri' => $xt->id, 'uid' => $importer["importer_uid"]]);
1640 if (!DBA::isResult($item_tag)) {
1641 Logger::log("Query failed to execute, no result returned in " . __FUNCTION__);
1645 // extract tag, if not duplicate, add to parent item
1647 Tag::store($item_tag['uri-id'], Tag::HASHTAG, $xo->content);
1656 * Processes the link elements
1658 * @param object $links link elements
1659 * @param array $item the item record
1661 * @todo set proper type-hints
1663 private static function parseLinks($links, &$item)
1670 foreach ($links as $link) {
1671 foreach ($link->attributes as $attributes) {
1672 switch ($attributes->name) {
1673 case "href" : $href = $attributes->textContent; break;
1674 case "rel" : $rel = $attributes->textContent; break;
1675 case "type" : $type = $attributes->textContent; break;
1676 case "length": $length = $attributes->textContent; break;
1677 case "title" : $title = $attributes->textContent; break;
1680 if (($rel != "") && ($href != "")) {
1683 $item["plink"] = $href;
1686 Post\Media::insert(['uri-id' => $item['uri-id'], 'type' => Post\Media::DOCUMENT,
1687 'url' => $href, 'mimetype' => $type, 'size' => $length, 'description' => $title]);
1695 * Checks if an incoming message is wanted
1697 * @param array $item
1698 * @return boolean Is the message wanted?
1700 private static function isSolicitedMessage(array $item)
1702 if (DBA::exists('contact', ["`nurl` = ? AND `uid` != ? AND `rel` IN (?, ?)",
1703 Strings::normaliseLink($item["author-link"]), 0, Contact::FRIEND, Contact::SHARING])) {
1704 Logger::info('Author has got followers - accepted', ['uri' => $item['uri'], 'author' => $item["author-link"]]);
1708 $taglist = Tag::getByURIId($item['uri-id'], [Tag::HASHTAG]);
1709 $tags = array_column($taglist, 'name');
1710 return Relay::isSolicitedPost($tags, $item['body'], $item['author-id'], $item['uri'], Protocol::DFRN);
1714 * Processes the entry elements which contain the items and comments
1716 * @param array $header Array of the header elements that always stay the same
1717 * @param object $xpath XPath object
1718 * @param object $entry entry elements
1719 * @param array $importer Record of the importer user mixed with contact of the content
1720 * @param string $xml xml
1722 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1723 * @throws \ImagickException
1724 * @todo Add type-hints
1726 private static function processEntry($header, $xpath, $entry, $importer, $xml, $protocol)
1728 Logger::log("Processing entries");
1732 $item["protocol"] = $protocol;
1734 $item["source"] = $xml;
1737 $item["uri"] = XML::getFirstNodeValue($xpath, "atom:id/text()", $entry);
1739 $item["edited"] = XML::getFirstNodeValue($xpath, "atom:updated/text()", $entry);
1741 $current = Post::selectFirst(['id', 'uid', 'edited', 'body'],
1742 ['uri' => $item["uri"], 'uid' => $importer["importer_uid"]]
1744 // Is there an existing item?
1745 if (DBA::isResult($current) && !self::isEditedTimestampNewer($current, $item)) {
1746 Logger::log("Item ".$item["uri"]." (".$item['edited'].") already existed.", Logger::DEBUG);
1751 $owner = self::fetchauthor($xpath, $entry, $importer, "dfrn:owner", true, $xml);
1753 $owner_unknown = (isset($owner["contact-unknown"]) && $owner["contact-unknown"]);
1755 $item["owner-name"] = $owner["name"];
1756 $item["owner-link"] = $owner["link"];
1757 $item["owner-avatar"] = $owner["avatar"];
1758 $item["owner-id"] = Contact::getIdForURL($owner["link"], 0);
1761 $author = self::fetchauthor($xpath, $entry, $importer, "atom:author", true, $xml);
1763 $item["author-name"] = $author["name"];
1764 $item["author-link"] = $author["link"];
1765 $item["author-avatar"] = $author["avatar"];
1766 $item["author-id"] = Contact::getIdForURL($author["link"], 0);
1768 $item["title"] = XML::getFirstNodeValue($xpath, "atom:title/text()", $entry);
1770 if (!empty($item["title"])) {
1771 $item["post-type"] = Item::PT_ARTICLE;
1773 $item["post-type"] = Item::PT_NOTE;
1776 $item["created"] = XML::getFirstNodeValue($xpath, "atom:published/text()", $entry);
1778 $item["body"] = XML::getFirstNodeValue($xpath, "dfrn:env/text()", $entry);
1779 $item["body"] = str_replace([' ',"\t","\r","\n"], ['','','',''], $item["body"]);
1781 $item["body"] = Strings::base64UrlDecode($item["body"]);
1783 $item["body"] = BBCode::limitBodySize($item["body"]);
1785 /// @todo We should check for a repeated post and if we know the repeated author.
1787 // We don't need the content element since "dfrn:env" is always present
1788 //$item["body"] = $xpath->query("atom:content/text()", $entry)->item(0)->nodeValue;
1790 $item["location"] = XML::getFirstNodeValue($xpath, "dfrn:location/text()", $entry);
1792 $item["coord"] = XML::getFirstNodeValue($xpath, "georss:point", $entry);
1794 $item["private"] = XML::getFirstNodeValue($xpath, "dfrn:private/text()", $entry);
1796 $unlisted = XML::getFirstNodeValue($xpath, "dfrn:unlisted/text()", $entry);
1797 if (!empty($unlisted) && ($item['private'] != Item::PRIVATE)) {
1798 $item['private'] = Item::UNLISTED;
1801 $item["extid"] = XML::getFirstNodeValue($xpath, "dfrn:extid/text()", $entry);
1803 if (XML::getFirstNodeValue($xpath, "dfrn:bookmark/text()", $entry) == "true") {
1804 $item["post-type"] = Item::PT_PAGE;
1807 $notice_info = $xpath->query("statusnet:notice_info", $entry);
1808 if ($notice_info && ($notice_info->length > 0)) {
1809 foreach ($notice_info->item(0)->attributes as $attributes) {
1810 if ($attributes->name == "source") {
1811 $item["app"] = strip_tags($attributes->textContent);
1816 $item["guid"] = XML::getFirstNodeValue($xpath, "dfrn:diaspora_guid/text()", $entry);
1818 $item['uri-id'] = ItemURI::insert(['uri' => $item['uri'], 'guid' => $item['guid']]);
1820 $item["body"] = Item::improveSharedDataInBody($item);
1822 Tag::storeFromBody($item['uri-id'], $item["body"]);
1824 // We store the data from "dfrn:diaspora_signature" in a different table, this is done in "Item::insert"
1825 $dsprsig = XML::unescape(XML::getFirstNodeValue($xpath, "dfrn:diaspora_signature/text()", $entry));
1826 if ($dsprsig != "") {
1827 $signature = json_decode(base64_decode($dsprsig));
1828 // We don't store the old style signatures anymore that also contained the "signature" and "signer"
1829 if (!empty($signature->signed_text) && empty($signature->signature) && empty($signature->signer)) {
1830 $item["diaspora_signed_text"] = $signature->signed_text;
1834 $item["verb"] = XML::getFirstNodeValue($xpath, "activity:verb/text()", $entry);
1836 if (XML::getFirstNodeValue($xpath, "activity:object-type/text()", $entry) != "") {
1837 $item["object-type"] = XML::getFirstNodeValue($xpath, "activity:object-type/text()", $entry);
1840 $object = $xpath->query("activity:object", $entry)->item(0);
1841 $item["object"] = self::transformActivity($xpath, $object, "object");
1843 if (trim($item["object"]) != "") {
1844 $r = XML::parseString($item["object"]);
1845 if (isset($r->type)) {
1846 $item["object-type"] = $r->type;
1850 $target = $xpath->query("activity:target", $entry)->item(0);
1851 $item["target"] = self::transformActivity($xpath, $target, "target");
1853 $categories = $xpath->query("atom:category", $entry);
1855 foreach ($categories as $category) {
1858 foreach ($category->attributes as $attributes) {
1859 if ($attributes->name == "term") {
1860 $term = $attributes->textContent;
1863 if ($attributes->name == "scheme") {
1864 $scheme = $attributes->textContent;
1868 if (($term != "") && ($scheme != "")) {
1869 $parts = explode(":", $scheme);
1870 if ((count($parts) >= 4) && (array_shift($parts) == "X-DFRN")) {
1871 $termurl = array_pop($parts);
1872 $termurl = array_pop($parts) . ':' . $termurl;
1873 Tag::store($item['uri-id'], Tag::IMPLICIT_MENTION, $term, $termurl);
1879 $links = $xpath->query("atom:link", $entry);
1881 self::parseLinks($links, $item);
1884 $item['conversation-uri'] = XML::getFirstNodeValue($xpath, 'ostatus:conversation/text()', $entry);
1886 $conv = $xpath->query('ostatus:conversation', $entry);
1887 if (is_object($conv->item(0))) {
1888 foreach ($conv->item(0)->attributes as $attributes) {
1889 if ($attributes->name == "ref") {
1890 $item['conversation-uri'] = $attributes->textContent;
1892 if ($attributes->name == "href") {
1893 $item['conversation-href'] = $attributes->textContent;
1898 // Is it a reply or a top level posting?
1899 $item['thr-parent'] = $item['uri'];
1901 $inreplyto = $xpath->query("thr:in-reply-to", $entry);
1902 if (is_object($inreplyto->item(0))) {
1903 foreach ($inreplyto->item(0)->attributes as $attributes) {
1904 if ($attributes->name == "ref") {
1905 $item['thr-parent'] = $attributes->textContent;
1910 // Check if the message is wanted
1911 if (($importer['importer_uid'] == 0) && ($item['uri'] == $item['thr-parent'])) {
1912 if (!self::isSolicitedMessage($item)) {
1913 DBA::delete('item-uri', ['uri' => $item['uri']]);
1918 // Get the type of the item (Top level post, reply or remote reply)
1919 $entrytype = self::getEntryType($importer, $item);
1921 // Now assign the rest of the values that depend on the type of the message
1922 if (in_array($entrytype, [DFRN::REPLY, DFRN::REPLY_RC])) {
1923 if (!isset($item["object-type"])) {
1924 $item["object-type"] = Activity\ObjectType::COMMENT;
1927 if ($item["contact-id"] != $owner["contact-id"]) {
1928 $item["contact-id"] = $owner["contact-id"];
1931 if (($item["network"] != $owner["network"]) && ($owner["network"] != "")) {
1932 $item["network"] = $owner["network"];
1935 if ($item["contact-id"] != $author["contact-id"]) {
1936 $item["contact-id"] = $author["contact-id"];
1939 if (($item["network"] != $author["network"]) && ($author["network"] != "")) {
1940 $item["network"] = $author["network"];
1944 // Ensure to have the correct share data
1945 $item = Item::addShareDataFromOriginal($item);
1947 if ($entrytype == DFRN::REPLY_RC) {
1949 } elseif ($entrytype == DFRN::TOP_LEVEL) {
1950 if (!isset($item["object-type"])) {
1951 $item["object-type"] = Activity\ObjectType::NOTE;
1955 if (($item["object-type"] == Activity\ObjectType::EVENT) && !$owner_unknown) {
1956 Logger::log("Item ".$item["uri"]." seems to contain an event.", Logger::DEBUG);
1957 $ev = Event::fromBBCode($item["body"]);
1958 if ((!empty($ev['desc']) || !empty($ev['summary'])) && !empty($ev['start'])) {
1959 Logger::log("Event in item ".$item["uri"]." was found.", Logger::DEBUG);
1960 $ev["cid"] = $importer["id"];
1961 $ev["uid"] = $importer["importer_uid"];
1962 $ev["uri"] = $item["uri"];
1963 $ev["edited"] = $item["edited"];
1964 $ev["private"] = $item["private"];
1965 $ev["guid"] = $item["guid"];
1966 $ev["plink"] = $item["plink"];
1967 $ev["network"] = $item["network"];
1968 $ev["protocol"] = $item["protocol"];
1969 $ev["direction"] = $item["direction"];
1970 $ev["source"] = $item["source"];
1972 $condition = ['uri' => $item["uri"], 'uid' => $importer["importer_uid"]];
1973 $event = DBA::selectFirst('event', ['id'], $condition);
1974 if (DBA::isResult($event)) {
1975 $ev["id"] = $event["id"];
1978 $event_id = Event::store($ev);
1979 Logger::info('Event was stored', ['id' => $event_id]);
1981 $item = Event::getItemArrayForImportedId($event_id, $item);
1986 if (!self::processVerbs($entrytype, $importer, $item, $is_like)) {
1987 Logger::log("Exiting because 'processVerbs' told us so", Logger::DEBUG);
1991 // This check is done here to be able to receive connection requests in "processVerbs"
1992 if (($entrytype == DFRN::TOP_LEVEL) && $owner_unknown) {
1993 Logger::log("Item won't be stored because user " . $importer["importer_uid"] . " doesn't follow " . $item["owner-link"] . ".", Logger::DEBUG);
1998 // Update content if 'updated' changes
1999 if (DBA::isResult($current)) {
2000 if (self::updateContent($current, $item, $importer, $entrytype)) {
2001 Logger::log("Item ".$item["uri"]." was updated.", Logger::DEBUG);
2003 Logger::log("Item " . $item["uri"] . " already existed.", Logger::DEBUG);
2008 if (in_array($entrytype, [DFRN::REPLY, DFRN::REPLY_RC])) {
2009 // Will be overwritten for sharing accounts in Item::insert
2010 if (empty($item['post-reason']) && ($entrytype == DFRN::REPLY)) {
2011 $item['post-reason'] = Item::PR_COMMENT;
2014 $posted_id = Item::insert($item);
2016 Logger::log("Reply from contact ".$item["contact-id"]." was stored with id ".$posted_id, Logger::DEBUG);
2018 if ($item['uid'] == 0) {
2019 Item::distribute($posted_id);
2024 } else { // $entrytype == DFRN::TOP_LEVEL
2025 if (($importer["uid"] == 0) && ($importer["importer_uid"] != 0)) {
2026 Logger::log("Contact ".$importer["id"]." isn't known to user ".$importer["importer_uid"].". The post will be ignored.", Logger::DEBUG);
2029 if (!Strings::compareLink($item["owner-link"], $importer["url"])) {
2031 * The item owner info is not our contact. It's OK and is to be expected if this is a tgroup delivery,
2032 * but otherwise there's a possible data mixup on the sender's system.
2033 * the tgroup delivery code called from Item::insert will correct it if it's a forum,
2034 * but we're going to unconditionally correct it here so that the post will always be owned by our contact.
2036 Logger::log('Correcting item owner.', Logger::DEBUG);
2037 $item["owner-link"] = $importer["url"];
2038 $item["owner-id"] = Contact::getIdForURL($importer["url"], 0);
2041 if (($importer["rel"] == Contact::FOLLOWER) && (!self::tgroupCheck($importer["importer_uid"], $item))) {
2042 Logger::log("Contact ".$importer["id"]." is only follower and tgroup check was negative.", Logger::DEBUG);
2046 // This is my contact on another system, but it's really me.
2047 // Turn this into a wall post.
2048 $notify = Item::isRemoteSelf($importer, $item);
2050 $posted_id = Item::insert($item, $notify);
2053 $posted_id = $notify;
2056 Logger::log("Item was stored with id ".$posted_id, Logger::DEBUG);
2058 if ($item['uid'] == 0) {
2059 Item::distribute($posted_id);
2062 if (stristr($item["verb"], Activity::POKE)) {
2063 $item['id'] = $posted_id;
2064 self::doPoke($item, $importer);
2072 * @param object $xpath XPath object
2073 * @param object $deletion deletion elements
2074 * @param array $importer Record of the importer user mixed with contact of the content
2076 * @throws \Exception
2077 * @todo set proper type-hints
2079 private static function processDeletion($xpath, $deletion, $importer)
2081 Logger::log("Processing deletions");
2084 foreach ($deletion->attributes as $attributes) {
2085 if ($attributes->name == "ref") {
2086 $uri = $attributes->textContent;
2090 if (!$uri || !$importer["id"]) {
2094 $condition = ['uri' => $uri, 'uid' => $importer["importer_uid"]];
2095 $item = Post::selectFirst(['id', 'parent', 'contact-id', 'uri-id', 'deleted', 'gravity'], $condition);
2096 if (!DBA::isResult($item)) {
2097 Logger::log("Item with uri " . $uri . " for user " . $importer["importer_uid"] . " wasn't found.", Logger::DEBUG);
2101 if (DBA::exists('post-category', ['uri-id' => $item['uri-id'], 'uid' => $importer['importer_uid'], 'type' => Post\Category::FILE])) {
2102 Logger::notice("Item is filed. It won't be deleted.", ['uri' => $uri, 'uri-id' => $item['uri_id'], 'uid' => $importer["importer_uid"]]);
2106 // When it is a starting post it has to belong to the person that wants to delete it
2107 if (($item['gravity'] == GRAVITY_PARENT) && ($item['contact-id'] != $importer["id"])) {
2108 Logger::log("Item with uri " . $uri . " don't belong to contact " . $importer["id"] . " - ignoring deletion.", Logger::DEBUG);
2112 // Comments can be deleted by the thread owner or comment owner
2113 if (($item['gravity'] != GRAVITY_PARENT) && ($item['contact-id'] != $importer["id"])) {
2114 $condition = ['id' => $item['parent'], 'contact-id' => $importer["id"]];
2115 if (!Post::exists($condition)) {
2116 Logger::log("Item with uri " . $uri . " wasn't found or mustn't be deleted by contact " . $importer["id"] . " - ignoring deletion.", Logger::DEBUG);
2121 if ($item["deleted"]) {
2125 Logger::log('deleting item '.$item['id'].' uri='.$uri, Logger::DEBUG);
2127 Item::markForDeletion(['id' => $item['id']]);
2131 * Imports a DFRN message
2133 * @param string $xml The DFRN message
2134 * @param array $importer Record of the importer user mixed with contact of the content
2135 * @param int $protocol Transport protocol
2136 * @param int $direction Is the message pushed or pulled?
2137 * @return integer Import status
2138 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2139 * @throws \ImagickException
2140 * @todo set proper type-hints
2142 public static function import($xml, $importer, $protocol, $direction)
2148 $doc = new DOMDocument();
2149 @$doc->loadXML($xml);
2151 $xpath = new DOMXPath($doc);
2152 $xpath->registerNamespace("atom", ActivityNamespace::ATOM1);
2153 $xpath->registerNamespace("thr", ActivityNamespace::THREAD);
2154 $xpath->registerNamespace("at", ActivityNamespace::TOMB);
2155 $xpath->registerNamespace("media", ActivityNamespace::MEDIA);
2156 $xpath->registerNamespace("dfrn", ActivityNamespace::DFRN);
2157 $xpath->registerNamespace("activity", ActivityNamespace::ACTIVITY);
2158 $xpath->registerNamespace("georss", ActivityNamespace::GEORSS);
2159 $xpath->registerNamespace("poco", ActivityNamespace::POCO);
2160 $xpath->registerNamespace("ostatus", ActivityNamespace::OSTATUS);
2161 $xpath->registerNamespace("statusnet", ActivityNamespace::STATUSNET);
2164 $header["uid"] = $importer["importer_uid"];
2165 $header["network"] = Protocol::DFRN;
2166 $header["wall"] = 0;
2167 $header["origin"] = 0;
2168 $header["contact-id"] = $importer["id"];
2169 $header["direction"] = $direction;
2171 if ($direction === Conversation::RELAY) {
2172 $header['post-reason'] = Item::PR_RELAY;
2175 // Update the contact table if the data has changed
2177 // The "atom:author" is only present in feeds
2178 if ($xpath->query("/atom:feed/atom:author")->length > 0) {
2179 self::fetchauthor($xpath, $doc->firstChild, $importer, "atom:author", false, $xml);
2182 // Only the "dfrn:owner" in the head section contains all data
2183 if ($xpath->query("/atom:feed/dfrn:owner")->length > 0) {
2184 self::fetchauthor($xpath, $doc->firstChild, $importer, "dfrn:owner", false, $xml);
2187 Logger::log("Import DFRN message for user " . $importer["importer_uid"] . " from contact " . $importer["id"], Logger::DEBUG);
2189 if (!empty($importer['gsid']) && ($protocol == Conversation::PARCEL_DIASPORA_DFRN)) {
2190 GServer::setProtocol($importer['gsid'], Post\DeliveryData::DFRN);
2193 // is it a public forum? Private forums aren't exposed with this method
2194 $forum = intval(XML::getFirstNodeValue($xpath, "/atom:feed/dfrn:community/text()"));
2196 // The account type is new since 3.5.1
2197 if ($xpath->query("/atom:feed/dfrn:account_type")->length > 0) {
2198 // Hint: We are using separate update calls for uid=0 and uid!=0 since a combined call is bad for the database performance
2200 $accounttype = intval(XML::getFirstNodeValue($xpath, "/atom:feed/dfrn:account_type/text()"));
2202 if ($accounttype != $importer["contact-type"]) {
2203 DBA::update('contact', ['contact-type' => $accounttype], ['id' => $importer['id']]);
2205 // Updating the public contact as well
2206 DBA::update('contact', ['contact-type' => $accounttype], ['uid' => 0, 'nurl' => $importer['nurl']]);
2208 // A forum contact can either have set "forum" or "prv" - but not both
2209 if ($accounttype == User::ACCOUNT_TYPE_COMMUNITY) {
2210 // It's a forum, so either set the public or private forum flag
2211 $condition = ['(`forum` != ? OR `prv` != ?) AND `id` = ?', $forum, !$forum, $importer['id']];
2212 DBA::update('contact', ['forum' => $forum, 'prv' => !$forum], $condition);
2214 // Updating the public contact as well
2215 $condition = ['(`forum` != ? OR `prv` != ?) AND `uid` = 0 AND `nurl` = ?', $forum, !$forum, $importer['nurl']];
2216 DBA::update('contact', ['forum' => $forum, 'prv' => !$forum], $condition);
2218 // It's not a forum, so remove the flags
2219 $condition = ['(`forum` OR `prv`) AND `id` = ?', $importer['id']];
2220 DBA::update('contact', ['forum' => false, 'prv' => false], $condition);
2222 // Updating the public contact as well
2223 $condition = ['(`forum` OR `prv`) AND `uid` = 0 AND `nurl` = ?', $importer['nurl']];
2224 DBA::update('contact', ['forum' => false, 'prv' => false], $condition);
2226 } elseif ($forum != $importer["forum"]) { // Deprecated since 3.5.1
2227 $condition = ['`forum` != ? AND `id` = ?', $forum, $importer["id"]];
2228 DBA::update('contact', ['forum' => $forum], $condition);
2230 // Updating the public contact as well
2231 $condition = ['`forum` != ? AND `uid` = 0 AND `nurl` = ?', $forum, $importer['nurl']];
2232 DBA::update('contact', ['forum' => $forum], $condition);
2236 // We are processing relocations even if we are ignoring a contact
2237 $relocations = $xpath->query("/atom:feed/dfrn:relocate");
2238 foreach ($relocations as $relocation) {
2239 self::processRelocation($xpath, $relocation, $importer);
2242 if (($importer["uid"] != 0) && !$importer["readonly"]) {
2243 $mails = $xpath->query("/atom:feed/dfrn:mail");
2244 foreach ($mails as $mail) {
2245 self::processMail($xpath, $mail, $importer);
2248 $suggestions = $xpath->query("/atom:feed/dfrn:suggest");
2249 foreach ($suggestions as $suggestion) {
2250 self::processSuggestion($xpath, $suggestion, $importer);
2254 $deletions = $xpath->query("/atom:feed/at:deleted-entry");
2255 if (!empty($deletions)) {
2256 foreach ($deletions as $deletion) {
2257 self::processDeletion($xpath, $deletion, $importer);
2259 if (count($deletions) > 0) {
2260 Logger::notice('Deletions had been processed');
2265 $entries = $xpath->query("/atom:feed/atom:entry");
2266 foreach ($entries as $entry) {
2267 self::processEntry($header, $xpath, $entry, $importer, $xml, $protocol);
2270 Logger::log("Import done for user " . $importer["importer_uid"] . " from contact " . $importer["id"], Logger::DEBUG);
2275 * Returns the activity verb
2277 * @param array $item Item array
2279 * @return string activity verb
2281 private static function constructVerb(array $item)
2283 if ($item['verb']) {
2284 return $item['verb'];
2286 return Activity::POST;
2289 private static function tgroupCheck($uid, $item)
2293 // check that the message originated elsewhere and is a top-level post
2295 if ($item['wall'] || $item['origin'] || ($item['uri'] != $item['thr-parent'])) {
2299 $user = DBA::selectFirst('user', ['page-flags', 'nickname'], ['uid' => $uid]);
2300 if (!DBA::isResult($user)) {
2304 $community_page = ($user['page-flags'] == User::PAGE_FLAGS_COMMUNITY);
2305 $prvgroup = ($user['page-flags'] == User::PAGE_FLAGS_PRVGROUP);
2307 $link = Strings::normaliseLink(DI::baseUrl() . '/profile/' . $user['nickname']);
2310 * Diaspora uses their own hardwired link URL in @-tags
2311 * instead of the one we supply with webfinger
2313 $dlink = Strings::normaliseLink(DI::baseUrl() . '/u/' . $user['nickname']);
2315 $cnt = preg_match_all('/[\@\!]\[url\=(.*?)\](.*?)\[\/url\]/ism', $item['body'], $matches, PREG_SET_ORDER);
2317 foreach ($matches as $mtch) {
2318 if (Strings::compareLink($link, $mtch[1]) || Strings::compareLink($dlink, $mtch[1])) {
2320 Logger::log('mention found: ' . $mtch[2]);
2329 return $community_page || $prvgroup;
2333 * This function returns true if $update has an edited timestamp newer
2334 * than $existing, i.e. $update contains new data which should override
2335 * what's already there. If there is no timestamp yet, the update is
2336 * assumed to be newer. If the update has no timestamp, the existing
2337 * item is assumed to be up-to-date. If the timestamps are equal it
2338 * assumes the update has been seen before and should be ignored.
2343 * @throws \Exception
2345 private static function isEditedTimestampNewer($existing, $update)
2347 if (empty($existing['edited'])) {
2350 if (empty($update['edited'])) {
2354 $existing_edited = DateTimeFormat::utc($existing['edited']);
2355 $update_edited = DateTimeFormat::utc($update['edited']);
2357 return (strcmp($existing_edited, $update_edited) < 0);
2361 * Checks if the given contact url does support DFRN
2363 * @param string $url profile url
2365 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2366 * @throws \ImagickException
2368 public static function isSupportedByContactUrl($url)
2370 $probe = Probe::uri($url, Protocol::DFRN);
2371 return $probe['network'] == Protocol::DFRN;