3 * @copyright Copyright (C) 2010-2022, the Friendica project
5 * @license GNU AGPL version 3 or any later version
7 * This program is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU Affero General Public License as
9 * published by the Free Software Foundation, either version 3 of the
10 * License, or (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU Affero General Public License for more details.
17 * You should have received a copy of the GNU Affero General Public License
18 * along with this program. If not, see <https://www.gnu.org/licenses/>.
22 namespace Friendica\Protocol;
26 use Friendica\Content\Text\BBCode;
27 use Friendica\Core\Logger;
28 use Friendica\Core\Protocol;
29 use Friendica\Database\DBA;
31 use Friendica\Model\Contact;
32 use Friendica\Model\Conversation;
33 use Friendica\Model\Event;
34 use Friendica\Model\FContact;
35 use Friendica\Model\GServer;
36 use Friendica\Model\Item;
37 use Friendica\Model\ItemURI;
38 use Friendica\Model\Mail;
39 use Friendica\Model\Notification;
40 use Friendica\Model\Photo;
41 use Friendica\Model\Post;
42 use Friendica\Model\Profile;
43 use Friendica\Model\Tag;
44 use Friendica\Model\User;
45 use Friendica\Network\HTTPClient\Client\HttpClientAccept;
46 use Friendica\Network\Probe;
47 use Friendica\Util\Crypto;
48 use Friendica\Util\DateTimeFormat;
49 use Friendica\Util\Images;
50 use Friendica\Util\Network;
51 use Friendica\Util\Proxy;
52 use Friendica\Util\Strings;
53 use Friendica\Util\XML;
56 * This class contain functions to create and send DFRN XML files
61 const TOP_LEVEL = 0; // Top level posting
62 const REPLY = 1; // Regular reply that is stored locally
63 const REPLY_RC = 2; // Reply that will be relayed
66 * Generates an array of contact and user for DFRN imports
68 * This array contains not only the receiver but also the sender of the message.
70 * @param integer $cid Contact id
71 * @param integer $uid User id
73 * @return array importer
76 public static function getImporter($cid, $uid = 0)
78 $condition = ['id' => $cid, 'blocked' => false, 'pending' => false];
79 $contact = DBA::selectFirst('contact', [], $condition);
80 if (!DBA::isResult($contact)) {
84 $contact['cpubkey'] = $contact['pubkey'];
85 $contact['cprvkey'] = $contact['prvkey'];
86 $contact['senderName'] = $contact['name'];
89 $condition = ['uid' => $uid, 'account_expired' => false, 'account_removed' => false];
90 $user = DBA::selectFirst('user', [], $condition);
91 if (!DBA::isResult($user)) {
95 $user['importer_uid'] = $user['uid'];
96 $user['uprvkey'] = $user['prvkey'];
98 $user = ['importer_uid' => 0, 'uprvkey' => '', 'timezone' => 'UTC',
99 'nickname' => '', 'sprvkey' => '', 'spubkey' => '',
100 'page-flags' => 0, 'account-type' => 0, 'prvnets' => 0];
103 return array_merge($contact, $user);
107 * Generates the atom entries for delivery.php
109 * This function is used whenever content is transmitted via DFRN.
111 * @param array $items Item elements
112 * @param array $owner Owner record
114 * @return string DFRN entries
115 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
116 * @throws \ImagickException
117 * @todo Find proper type-hints
119 public static function entries($items, $owner)
121 $doc = new DOMDocument('1.0', 'utf-8');
122 $doc->formatOutput = true;
124 $root = self::addHeader($doc, $owner, "dfrn:owner", "", false);
126 if (! count($items)) {
127 return trim($doc->saveXML());
130 foreach ($items as $item) {
131 // These values aren't sent when sending from the queue.
132 /// @todo Check if we can set these values from the queue or if they are needed at all.
133 $item["entry:comment-allow"] = ($item["entry:comment-allow"] ?? '') ?: true;
134 $item["entry:cid"] = $item["entry:cid"] ?? 0;
136 $entry = self::entry($doc, "text", $item, $owner, $item["entry:comment-allow"], $item["entry:cid"]);
138 $root->appendChild($entry);
142 return trim($doc->saveXML());
146 * Generate an atom entry for a given uri id and user
148 * @param int $uri_id The uri id
149 * @param int $uid The user id
150 * @param boolean $conversation Show the conversation. If false show the single post.
152 * @return string DFRN feed entry
153 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
154 * @throws \ImagickException
156 public static function itemFeed(int $uri_id, int $uid, bool $conversation = false)
159 $condition = ['parent-uri-id' => $uri_id];
161 $condition = ['uri-id' => $uri_id];
164 $condition['uid'] = $uid;
166 $items = Post::selectToArray(Item::DELIVER_FIELDLIST, $condition);
167 if (!DBA::isResult($items)) {
173 if ($item['uid'] != 0) {
174 $owner = User::getOwnerDataById($item['uid']);
179 $owner = ['uid' => 0, 'nick' => 'feed-item'];
182 $doc = new DOMDocument('1.0', 'utf-8');
183 $doc->formatOutput = true;
187 $root = $doc->createElementNS(ActivityNamespace::ATOM1, 'feed');
188 $doc->appendChild($root);
190 $root->setAttribute("xmlns:thr", ActivityNamespace::THREAD);
191 $root->setAttribute("xmlns:at", ActivityNamespace::TOMB);
192 $root->setAttribute("xmlns:media", ActivityNamespace::MEDIA);
193 $root->setAttribute("xmlns:dfrn", ActivityNamespace::DFRN);
194 $root->setAttribute("xmlns:activity", ActivityNamespace::ACTIVITY);
195 $root->setAttribute("xmlns:georss", ActivityNamespace::GEORSS);
196 $root->setAttribute("xmlns:poco", ActivityNamespace::POCO);
197 $root->setAttribute("xmlns:ostatus", ActivityNamespace::OSTATUS);
198 $root->setAttribute("xmlns:statusnet", ActivityNamespace::STATUSNET);
200 //$root = self::addHeader($doc, $owner, "dfrn:owner", "", false);
202 foreach ($items as $item) {
203 $entry = self::entry($doc, $type, $item, $owner, true, 0);
205 $root->appendChild($entry);
209 self::entry($doc, $type, $item, $owner, true, 0, true);
212 $atom = trim($doc->saveXML());
217 * Create XML text for DFRN mails
219 * @param array $mail Mail record
220 * @param array $owner Owner record
222 * @return string DFRN mail
223 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
224 * @todo Find proper type-hints
226 public static function mail(array $mail, array $owner)
228 $doc = new DOMDocument('1.0', 'utf-8');
229 $doc->formatOutput = true;
231 $root = self::addHeader($doc, $owner, "dfrn:owner", "", false);
233 $mailElement = $doc->createElement("dfrn:mail");
234 $senderElement = $doc->createElement("dfrn:sender");
236 XML::addElement($doc, $senderElement, "dfrn:name", $owner['name']);
237 XML::addElement($doc, $senderElement, "dfrn:uri", $owner['url']);
238 XML::addElement($doc, $senderElement, "dfrn:avatar", $owner['thumb']);
240 $mailElement->appendChild($senderElement);
242 XML::addElement($doc, $mailElement, "dfrn:id", $mail['uri']);
243 XML::addElement($doc, $mailElement, "dfrn:in-reply-to", $mail['parent-uri']);
244 XML::addElement($doc, $mailElement, "dfrn:sentdate", DateTimeFormat::utc($mail['created'] . '+00:00', DateTimeFormat::ATOM));
245 XML::addElement($doc, $mailElement, "dfrn:subject", $mail['title']);
246 XML::addElement($doc, $mailElement, "dfrn:content", $mail['body']);
248 $root->appendChild($mailElement);
250 return trim($doc->saveXML());
254 * Create XML text for DFRN friend suggestions
256 * @param array $item suggestion elements
257 * @param array $owner Owner record
259 * @return string DFRN suggestions
260 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
261 * @todo Find proper type-hints
263 public static function fsuggest($item, $owner)
265 $doc = new DOMDocument('1.0', 'utf-8');
266 $doc->formatOutput = true;
268 $root = self::addHeader($doc, $owner, "dfrn:owner", "", false);
270 $suggest = $doc->createElement("dfrn:suggest");
272 XML::addElement($doc, $suggest, "dfrn:url", $item['url']);
273 XML::addElement($doc, $suggest, "dfrn:name", $item['name']);
274 XML::addElement($doc, $suggest, "dfrn:photo", $item['photo']);
275 XML::addElement($doc, $suggest, "dfrn:request", $item['request']);
276 XML::addElement($doc, $suggest, "dfrn:note", $item['note']);
278 $root->appendChild($suggest);
280 return trim($doc->saveXML());
284 * Create XML text for DFRN relocations
286 * @param array $owner Owner record
287 * @param int $uid User ID
289 * @return string DFRN relocations
290 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
291 * @todo Find proper type-hints
293 public static function relocate($owner, $uid)
296 /* get site pubkey. this could be a new installation with no site keys*/
297 $pubkey = DI::config()->get('system', 'site_pubkey');
299 $res = Crypto::newKeypair(1024);
300 DI::config()->set('system', 'site_prvkey', $res['prvkey']);
301 DI::config()->set('system', 'site_pubkey', $res['pubkey']);
304 $profilephotos = Photo::selectToArray(['resource-id' , 'scale'], ['profile' => true, 'uid' => $uid], ['order' => ['scale']]);
307 $ext = Images::supportedTypes();
309 foreach ($profilephotos as $p) {
310 $photos[$p['scale']] = DI::baseUrl().'/photo/'.$p['resource-id'].'-'.$p['scale'].'.'.$ext[$p['type']];
314 $doc = new DOMDocument('1.0', 'utf-8');
315 $doc->formatOutput = true;
317 $root = self::addHeader($doc, $owner, "dfrn:owner", "", false);
319 $relocate = $doc->createElement("dfrn:relocate");
321 XML::addElement($doc, $relocate, "dfrn:url", $owner['url']);
322 XML::addElement($doc, $relocate, "dfrn:name", $owner['name']);
323 XML::addElement($doc, $relocate, "dfrn:addr", $owner['addr']);
324 XML::addElement($doc, $relocate, "dfrn:avatar", $owner['avatar']);
325 XML::addElement($doc, $relocate, "dfrn:photo", $photos[4]);
326 XML::addElement($doc, $relocate, "dfrn:thumb", $photos[5]);
327 XML::addElement($doc, $relocate, "dfrn:micro", $photos[6]);
328 XML::addElement($doc, $relocate, "dfrn:request", $owner['request']);
329 XML::addElement($doc, $relocate, "dfrn:confirm", $owner['confirm']);
330 XML::addElement($doc, $relocate, "dfrn:notify", $owner['notify']);
331 XML::addElement($doc, $relocate, "dfrn:poll", $owner['poll']);
332 XML::addElement($doc, $relocate, "dfrn:sitepubkey", DI::config()->get('system', 'site_pubkey'));
334 $root->appendChild($relocate);
336 return trim($doc->saveXML());
340 * Adds the header elements for the DFRN protocol
342 * @param DOMDocument $doc XML document
343 * @param array $owner Owner record
344 * @param string $authorelement Element name for the author
345 * @param string $alternatelink link to profile or category
346 * @param bool $public Is it a header for public posts?
348 * @return object XML root object
349 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
350 * @todo Find proper type-hints
352 private static function addHeader(DOMDocument $doc, $owner, $authorelement, $alternatelink = "", $public = false)
355 if ($alternatelink == "") {
356 $alternatelink = $owner['url'];
359 $root = $doc->createElementNS(ActivityNamespace::ATOM1, 'feed');
360 $doc->appendChild($root);
362 $root->setAttribute("xmlns:thr", ActivityNamespace::THREAD);
363 $root->setAttribute("xmlns:at", ActivityNamespace::TOMB);
364 $root->setAttribute("xmlns:media", ActivityNamespace::MEDIA);
365 $root->setAttribute("xmlns:dfrn", ActivityNamespace::DFRN);
366 $root->setAttribute("xmlns:activity", ActivityNamespace::ACTIVITY);
367 $root->setAttribute("xmlns:georss", ActivityNamespace::GEORSS);
368 $root->setAttribute("xmlns:poco", ActivityNamespace::POCO);
369 $root->setAttribute("xmlns:ostatus", ActivityNamespace::OSTATUS);
370 $root->setAttribute("xmlns:statusnet", ActivityNamespace::STATUSNET);
372 XML::addElement($doc, $root, "id", DI::baseUrl()."/profile/".$owner["nick"]);
373 XML::addElement($doc, $root, "title", $owner["name"]);
375 $attributes = ["uri" => "https://friendi.ca", "version" => FRIENDICA_VERSION."-".DB_UPDATE_VERSION];
376 XML::addElement($doc, $root, "generator", FRIENDICA_PLATFORM, $attributes);
378 $attributes = ["rel" => "license", "href" => "http://creativecommons.org/licenses/by/3.0/"];
379 XML::addElement($doc, $root, "link", "", $attributes);
381 $attributes = ["rel" => "alternate", "type" => "text/html", "href" => $alternatelink];
382 XML::addElement($doc, $root, "link", "", $attributes);
386 // DFRN itself doesn't uses this. But maybe someone else wants to subscribe to the public feed.
387 OStatus::hublinks($doc, $root, $owner["nick"]);
389 $attributes = ["rel" => "salmon", "href" => DI::baseUrl()."/salmon/".$owner["nick"]];
390 XML::addElement($doc, $root, "link", "", $attributes);
392 $attributes = ["rel" => "http://salmon-protocol.org/ns/salmon-replies", "href" => DI::baseUrl()."/salmon/".$owner["nick"]];
393 XML::addElement($doc, $root, "link", "", $attributes);
395 $attributes = ["rel" => "http://salmon-protocol.org/ns/salmon-mention", "href" => DI::baseUrl()."/salmon/".$owner["nick"]];
396 XML::addElement($doc, $root, "link", "", $attributes);
399 // For backward compatibility we keep this element
400 if ($owner['page-flags'] == User::PAGE_FLAGS_COMMUNITY) {
401 XML::addElement($doc, $root, "dfrn:community", 1);
404 // The former element is replaced by this one
405 XML::addElement($doc, $root, "dfrn:account_type", $owner["account-type"]);
407 /// @todo We need a way to transmit the different page flags like "User::PAGE_FLAGS_PRVGROUP"
409 XML::addElement($doc, $root, "updated", DateTimeFormat::utcNow(DateTimeFormat::ATOM));
411 $author = self::addAuthor($doc, $owner, $authorelement, $public);
412 $root->appendChild($author);
418 * Determine the next birthday, but only if the birthday is published
419 * in the default profile. We _could_ also look for a private profile that the
420 * recipient can see, but somebody could get mad at us if they start getting
421 * public birthday greetings when they haven't made this info public.
423 * Assuming we are able to publish this info, we are then going to convert
424 * the start time from the owner's timezone to UTC.
426 * This will potentially solve the problem found with some social networks
427 * where birthdays are converted to the viewer's timezone and salutations from
428 * elsewhere in the world show up on the wrong day. We will convert it to the
429 * viewer's timezone also, but first we are going to convert it from the birthday
430 * person's timezone to GMT - so the viewer may find the birthday starting at
431 * 6:00PM the day before, but that will correspond to midnight to the birthday person.
433 private static function determineNextBirthday($uid, $tz)
441 $profile = DBA::selectFirst('profile', ['dob'], ['uid' => $uid]);
442 if (DBA::isResult($profile)) {
443 $tmp_dob = substr($profile['dob'], 5);
444 if (intval($tmp_dob)) {
445 $y = DateTimeFormat::timezoneNow($tz, 'Y');
446 $bd = $y . '-' . $tmp_dob . ' 00:00';
447 $t_dob = strtotime($bd);
448 $now = strtotime(DateTimeFormat::timezoneNow($tz));
450 $bd = $y + 1 . '-' . $tmp_dob . ' 00:00';
452 $birthday = DateTimeFormat::convert($bd, 'UTC', $tz, DateTimeFormat::ATOM);
460 * Adds the author element in the header for the DFRN protocol
462 * @param DOMDocument $doc XML document
463 * @param array $owner Owner record
464 * @param string $authorelement Element name for the author
465 * @param boolean $public boolean
467 * @return \DOMElement XML author object
468 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
469 * @todo Find proper type-hints
471 private static function addAuthor(DOMDocument $doc, array $owner, $authorelement, $public)
473 // Should the profile be "unsearchable" in the net? Then add the "hide" element
474 $hide = DBA::exists('profile', ['uid' => $owner['uid'], 'net-publish' => false]);
476 $author = $doc->createElement($authorelement);
478 $namdate = DateTimeFormat::utc($owner['name-date'].'+00:00', DateTimeFormat::ATOM);
479 $picdate = DateTimeFormat::utc($owner['avatar-date'].'+00:00', DateTimeFormat::ATOM);
483 if (!$public || !$hide) {
484 $attributes = ["dfrn:updated" => $namdate];
487 XML::addElement($doc, $author, "name", $owner["name"], $attributes);
488 XML::addElement($doc, $author, "uri", DI::baseUrl().'/profile/'.$owner["nickname"], $attributes);
489 XML::addElement($doc, $author, "dfrn:handle", $owner["addr"], $attributes);
491 $attributes = ["rel" => "photo", "type" => "image/jpeg",
492 "media:width" => Proxy::PIXEL_SMALL, "media:height" => Proxy::PIXEL_SMALL,
493 "href" => User::getAvatarUrl($owner, Proxy::SIZE_SMALL)];
495 if (!$public || !$hide) {
496 $attributes["dfrn:updated"] = $picdate;
499 XML::addElement($doc, $author, "link", "", $attributes);
501 $attributes["rel"] = "avatar";
502 XML::addElement($doc, $author, "link", "", $attributes);
505 XML::addElement($doc, $author, "dfrn:hide", "true");
508 // The following fields will only be generated if the data isn't meant for a public feed
513 $birthday = self::determineNextBirthday($owner['uid'], $owner['timezone']);
516 XML::addElement($doc, $author, "dfrn:birthday", $birthday);
519 // Only show contact details when we are allowed to
520 $profile = DBA::selectFirst('owner-view',
521 ['about', 'name', 'homepage', 'nickname', 'timezone', 'locality', 'region', 'country-name', 'pub_keywords', 'xmpp', 'dob'],
522 ['uid' => $owner['uid'], 'hidewall' => false]);
523 if (DBA::isResult($profile)) {
524 XML::addElement($doc, $author, "poco:displayName", $profile["name"]);
525 XML::addElement($doc, $author, "poco:updated", $namdate);
527 if (trim($profile["dob"]) > DBA::NULL_DATE) {
528 XML::addElement($doc, $author, "poco:birthday", "0000-".date("m-d", strtotime($profile["dob"])));
531 XML::addElement($doc, $author, "poco:note", $profile["about"]);
532 XML::addElement($doc, $author, "poco:preferredUsername", $profile["nickname"]);
534 XML::addElement($doc, $author, "poco:utcOffset", DateTimeFormat::timezoneNow($profile["timezone"], "P"));
536 if (trim($profile["homepage"]) != "") {
537 $urls = $doc->createElement("poco:urls");
538 XML::addElement($doc, $urls, "poco:type", "homepage");
539 XML::addElement($doc, $urls, "poco:value", $profile["homepage"]);
540 XML::addElement($doc, $urls, "poco:primary", "true");
541 $author->appendChild($urls);
544 if (trim($profile["pub_keywords"]) != "") {
545 $keywords = explode(",", $profile["pub_keywords"]);
547 foreach ($keywords as $keyword) {
548 XML::addElement($doc, $author, "poco:tags", trim($keyword));
552 if (trim($profile["xmpp"]) != "") {
553 $ims = $doc->createElement("poco:ims");
554 XML::addElement($doc, $ims, "poco:type", "xmpp");
555 XML::addElement($doc, $ims, "poco:value", $profile["xmpp"]);
556 XML::addElement($doc, $ims, "poco:primary", "true");
557 $author->appendChild($ims);
560 if (trim($profile["locality"].$profile["region"].$profile["country-name"]) != "") {
561 $element = $doc->createElement("poco:address");
563 XML::addElement($doc, $element, "poco:formatted", Profile::formatLocation($profile));
565 if (trim($profile["locality"]) != "") {
566 XML::addElement($doc, $element, "poco:locality", $profile["locality"]);
569 if (trim($profile["region"]) != "") {
570 XML::addElement($doc, $element, "poco:region", $profile["region"]);
573 if (trim($profile["country-name"]) != "") {
574 XML::addElement($doc, $element, "poco:country", $profile["country-name"]);
577 $author->appendChild($element);
585 * Adds the author elements in the "entry" elements of the DFRN protocol
587 * @param DOMDocument $doc XML document
588 * @param string $element Element name for the author
589 * @param string $contact_url Link of the contact
590 * @param array $item Item elements
592 * @return \DOMElement XML author object
593 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
594 * @todo Find proper type-hints
596 private static function addEntryAuthor(DOMDocument $doc, $element, $contact_url, $item)
598 $author = $doc->createElement($element);
600 $contact = Contact::getByURLForUser($contact_url, $item["uid"], false, ['url', 'name', 'addr', 'photo']);
601 if (!empty($contact)) {
602 XML::addElement($doc, $author, "name", $contact["name"]);
603 XML::addElement($doc, $author, "uri", $contact["url"]);
604 XML::addElement($doc, $author, "dfrn:handle", $contact["addr"]);
607 /// - Check real image type and image size
608 /// - Check which of these boths elements we should use
611 "type" => "image/jpeg",
613 "media:height" => 80,
614 "href" => $contact["photo"]];
615 XML::addElement($doc, $author, "link", "", $attributes);
619 "type" => "image/jpeg",
621 "media:height" => 80,
622 "href" => $contact["photo"]];
623 XML::addElement($doc, $author, "link", "", $attributes);
630 * Adds the activity elements
632 * @param DOMDocument $doc XML document
633 * @param string $element Element name for the activity
634 * @param string $activity activity value
635 * @param int $uriid Uri-Id of the post
637 * @return \DOMElement XML activity object
638 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
639 * @todo Find proper type-hints
641 private static function createActivity(DOMDocument $doc, $element, $activity, $uriid)
644 $entry = $doc->createElement($element);
646 $r = XML::parseString($activity);
652 XML::addElement($doc, $entry, "activity:object-type", $r->type);
656 XML::addElement($doc, $entry, "id", $r->id);
660 XML::addElement($doc, $entry, "title", $r->title);
664 if (substr($r->link, 0, 1) == '<') {
665 if (strstr($r->link, '&') && (! strstr($r->link, '&'))) {
666 $r->link = str_replace('&', '&', $r->link);
669 $r->link = preg_replace('/\<link(.*?)\"\>/', '<link$1"/>', $r->link);
671 // XML does need a single element as root element so we add a dummy element here
672 $data = XML::parseString("<dummy>" . $r->link . "</dummy>");
673 if (is_object($data)) {
674 foreach ($data->link as $link) {
676 foreach ($link->attributes() as $parameter => $value) {
677 $attributes[$parameter] = $value;
679 XML::addElement($doc, $entry, "link", "", $attributes);
683 $attributes = ["rel" => "alternate", "type" => "text/html", "href" => $r->link];
684 XML::addElement($doc, $entry, "link", "", $attributes);
688 XML::addElement($doc, $entry, "content", BBCode::convertForUriId($uriid, $r->content, BBCode::EXTERNAL), ["type" => "html"]);
698 * Adds the elements for attachments
700 * @param object $doc XML document
701 * @param object $root XML root
702 * @param array $item Item element
704 * @return void XML attachment object
705 * @todo Find proper type-hints
707 private static function getAttachment($doc, $root, $item)
709 foreach (Post\Media::getByURIId($item['uri-id'], [Post\Media::DOCUMENT, Post\Media::TORRENT, Post\Media::UNKNOWN]) as $attachment) {
710 $attributes = ['rel' => 'enclosure',
711 'href' => $attachment['url'],
712 'type' => $attachment['mimetype']];
714 if (!empty($attachment['size'])) {
715 $attributes['length'] = intval($attachment['size']);
717 if (!empty($attachment['description'])) {
718 $attributes['title'] = $attachment['description'];
721 XML::addElement($doc, $root, 'link', '', $attributes);
726 * Adds the "entry" elements for the DFRN protocol
728 * @param DOMDocument $doc XML document
729 * @param string $type "text" or "html"
730 * @param array $item Item element
731 * @param array $owner Owner record
732 * @param bool $comment Trigger the sending of the "comment" element
733 * @param int $cid Contact ID of the recipient
734 * @param bool $single If set, the entry is created as an XML document with a single "entry" element
736 * @return null|\DOMElement XML entry object
737 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
738 * @throws \ImagickException
739 * @todo Find proper type-hints
741 private static function entry(DOMDocument $doc, $type, array $item, array $owner, $comment = false, $cid = 0, $single = false)
745 if (!$item['parent']) {
746 Logger::notice('Item without parent found.', ['type' => $type, 'item' => $item]);
750 if ($item['deleted']) {
751 $attributes = ["ref" => $item['uri'], "when" => DateTimeFormat::utc($item['edited'] . '+00:00', DateTimeFormat::ATOM)];
752 return XML::createElement($doc, "at:deleted-entry", "", $attributes);
756 $entry = $doc->createElement("entry");
758 $entry = $doc->createElementNS(ActivityNamespace::ATOM1, 'entry');
759 $doc->appendChild($entry);
761 $entry->setAttribute("xmlns:thr", ActivityNamespace::THREAD);
762 $entry->setAttribute("xmlns:at", ActivityNamespace::TOMB);
763 $entry->setAttribute("xmlns:media", ActivityNamespace::MEDIA);
764 $entry->setAttribute("xmlns:dfrn", ActivityNamespace::DFRN);
765 $entry->setAttribute("xmlns:activity", ActivityNamespace::ACTIVITY);
766 $entry->setAttribute("xmlns:georss", ActivityNamespace::GEORSS);
767 $entry->setAttribute("xmlns:poco", ActivityNamespace::POCO);
768 $entry->setAttribute("xmlns:ostatus", ActivityNamespace::OSTATUS);
769 $entry->setAttribute("xmlns:statusnet", ActivityNamespace::STATUSNET);
772 $body = Post\Media::addAttachmentsToBody($item['uri-id'], $item['body'] ?? '');
774 if ($item['private'] == Item::PRIVATE) {
775 $body = Item::fixPrivatePhotos($body, $owner['uid'], $item, $cid);
778 // Remove the abstract element. It is only locally important.
779 $body = BBCode::stripAbstract($body);
782 if ($type == 'html') {
785 if ($item['title'] != "") {
786 $htmlbody = "[b]" . $item['title'] . "[/b]\n\n" . $htmlbody;
789 $htmlbody = BBCode::convertForUriId($item['uri-id'], $htmlbody, BBCode::ACTIVITYPUB);
792 $author = self::addEntryAuthor($doc, "author", $item["author-link"], $item);
793 $entry->appendChild($author);
795 $dfrnowner = self::addEntryAuthor($doc, "dfrn:owner", $item["owner-link"], $item);
796 $entry->appendChild($dfrnowner);
798 if ($item['gravity'] != GRAVITY_PARENT) {
799 $parent = Post::selectFirst(['guid', 'plink'], ['uri' => $item['thr-parent'], 'uid' => $item['uid']]);
800 if (DBA::isResult($parent)) {
801 $attributes = ["ref" => $item['thr-parent'], "type" => "text/html",
802 "href" => $parent['plink'],
803 "dfrn:diaspora_guid" => $parent['guid']];
804 XML::addElement($doc, $entry, "thr:in-reply-to", "", $attributes);
808 // Add conversation data. This is used for OStatus
809 $conversation_href = DI::baseUrl()."/display/".$item["parent-guid"];
810 $conversation_uri = $conversation_href;
812 if (isset($parent_item)) {
813 $conversation = DBA::selectFirst('conversation', ['conversation-uri', 'conversation-href'], ['item-uri' => $item['thr-parent']]);
814 if (DBA::isResult($conversation)) {
815 if ($conversation['conversation-uri'] != '') {
816 $conversation_uri = $conversation['conversation-uri'];
818 if ($conversation['conversation-href'] != '') {
819 $conversation_href = $conversation['conversation-href'];
825 "href" => $conversation_href,
826 "ref" => $conversation_uri];
828 XML::addElement($doc, $entry, "ostatus:conversation", $conversation_uri, $attributes);
830 XML::addElement($doc, $entry, "id", $item["uri"]);
831 XML::addElement($doc, $entry, "title", $item["title"]);
833 XML::addElement($doc, $entry, "published", DateTimeFormat::utc($item["created"] . "+00:00", DateTimeFormat::ATOM));
834 XML::addElement($doc, $entry, "updated", DateTimeFormat::utc($item["edited"] . "+00:00", DateTimeFormat::ATOM));
836 // "dfrn:env" is used to read the content
837 XML::addElement($doc, $entry, "dfrn:env", Strings::base64UrlEncode($body, true));
839 // The "content" field is not read by the receiver. We could remove it when the type is "text"
840 // We keep it at the moment, maybe there is some old version that doesn't read "dfrn:env"
841 XML::addElement($doc, $entry, "content", (($type == 'html') ? $htmlbody : $body), ["type" => $type]);
843 // We save this value in "plink". Maybe we should read it from there as well?
849 ["rel" => "alternate", "type" => "text/html",
850 "href" => DI::baseUrl() . "/display/" . $item["guid"]]
853 // "comment-allow" is some old fashioned stuff for old Friendica versions.
854 // It is included in the rewritten code for completeness
856 XML::addElement($doc, $entry, "dfrn:comment-allow", 1);
859 if ($item['location']) {
860 XML::addElement($doc, $entry, "dfrn:location", $item['location']);
863 if ($item['coord']) {
864 XML::addElement($doc, $entry, "georss:point", $item['coord']);
867 if ($item['private']) {
868 // Friendica versions prior to 2020.3 can't handle "unlisted" properly. So we can only transmit public and private
869 XML::addElement($doc, $entry, "dfrn:private", ($item['private'] == Item::PRIVATE ? Item::PRIVATE : Item::PUBLIC));
870 XML::addElement($doc, $entry, "dfrn:unlisted", $item['private'] == Item::UNLISTED);
873 if ($item['extid']) {
874 XML::addElement($doc, $entry, "dfrn:extid", $item['extid']);
877 if ($item['post-type'] == Item::PT_PAGE) {
878 XML::addElement($doc, $entry, "dfrn:bookmark", "true");
882 XML::addElement($doc, $entry, "statusnet:notice_info", "", ["local_id" => $item['id'], "source" => $item['app']]);
885 XML::addElement($doc, $entry, "dfrn:diaspora_guid", $item["guid"]);
887 // The signed text contains the content in Markdown, the sender handle and the signatur for the content
888 // It is needed for relayed comments to Diaspora.
889 if ($item['signed_text']) {
890 $sign = base64_encode(json_encode(['signed_text' => $item['signed_text'],'signature' => '','signer' => '']));
891 XML::addElement($doc, $entry, "dfrn:diaspora_signature", $sign);
894 XML::addElement($doc, $entry, "activity:verb", self::constructVerb($item));
896 if ($item['object-type'] != "") {
897 XML::addElement($doc, $entry, "activity:object-type", $item['object-type']);
898 } elseif ($item['gravity'] == GRAVITY_PARENT) {
899 XML::addElement($doc, $entry, "activity:object-type", Activity\ObjectType::NOTE);
901 XML::addElement($doc, $entry, "activity:object-type", Activity\ObjectType::COMMENT);
904 $actobj = self::createActivity($doc, "activity:object", $item['object'], $item['uri-id']);
906 $entry->appendChild($actobj);
909 $actarg = self::createActivity($doc, "activity:target", $item['target'], $item['uri-id']);
911 $entry->appendChild($actarg);
914 $tags = Tag::getByURIId($item['uri-id']);
917 foreach ($tags as $tag) {
918 if (($type != 'html') || ($tag['type'] == Tag::HASHTAG)) {
919 XML::addElement($doc, $entry, "category", "", ["scheme" => "X-DFRN:" . Tag::TAG_CHARACTER[$tag['type']] . ":" . $tag['url'], "term" => $tag['name']]);
921 if ($tag['type'] != Tag::HASHTAG) {
922 $mentioned[$tag['url']] = $tag['url'];
927 foreach ($mentioned as $mention) {
928 $condition = ['uid' => $owner["uid"], 'nurl' => Strings::normaliseLink($mention)];
929 $contact = DBA::selectFirst('contact', ['contact-type'], $condition);
931 if (DBA::isResult($contact) && ($contact['contact-type'] == Contact::TYPE_COMMUNITY)) {
937 ["rel" => "mentioned",
938 "ostatus:object-type" => Activity\ObjectType::GROUP,
947 ["rel" => "mentioned",
948 "ostatus:object-type" => Activity\ObjectType::PERSON,
954 self::getAttachment($doc, $entry, $item);
960 * Transmits atom content to the contacts via the Diaspora transport layer
962 * @param array $owner Owner record
963 * @param array $contact Contact record of the receiver
964 * @param string $atom Content that will be transmitted
966 * @param bool $public_batch
967 * @return int Deliver status. Negative values mean an error.
968 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
969 * @throws \ImagickException
971 public static function transmit($owner, $contact, $atom, $public_batch = false)
973 if (!$public_batch) {
974 if (empty($contact['addr'])) {
975 Logger::notice('Empty contact handle for ' . $contact['id'] . ' - ' . $contact['url'] . ' - trying to update it.');
976 if (Contact::updateFromProbe($contact['id'])) {
977 $new_contact = DBA::selectFirst('contact', ['addr'], ['id' => $contact['id']]);
978 $contact['addr'] = $new_contact['addr'];
981 if (empty($contact['addr'])) {
982 Logger::notice('Unable to find contact handle for ' . $contact['id'] . ' - ' . $contact['url']);
987 $fcontact = FContact::getByURL($contact['addr']);
988 if (empty($fcontact)) {
989 Logger::notice('Unable to find contact details for ' . $contact['id'] . ' - ' . $contact['addr']);
992 $pubkey = $fcontact['pubkey'];
997 $envelope = Diaspora::buildMessage($atom, $owner, $contact, $owner['uprvkey'], $pubkey, $public_batch);
999 // Create the endpoint for public posts. This is some WIP and should later be added to the probing
1000 if ($public_batch && empty($contact["batch"])) {
1001 $parts = parse_url($contact["notify"]);
1002 $path_parts = explode('/', $parts['path']);
1003 array_pop($path_parts);
1004 $parts['path'] = implode('/', $path_parts);
1005 $contact["batch"] = Network::unparseURL($parts);
1008 $dest_url = ($public_batch ? $contact["batch"] : $contact["notify"]);
1010 if (empty($dest_url)) {
1011 Logger::info('Empty destination', ['public' => $public_batch, 'contact' => $contact]);
1015 $content_type = ($public_batch ? "application/magic-envelope+xml" : "application/json");
1017 $postResult = DI::httpClient()->post($dest_url, $envelope, HttpClientAccept::DEFAULT, ['Content-Type' => $content_type]);
1018 $xml = $postResult->getBody();
1020 $curl_stat = $postResult->getReturnCode();
1021 if (empty($curl_stat) || empty($xml)) {
1022 Logger::notice('Empty answer from ' . $contact['id'] . ' - ' . $dest_url);
1023 return -9; // timed out
1026 if (($curl_stat == 503) && $postResult->inHeader('retry-after')) {
1030 if (strpos($xml, '<?xml') === false) {
1031 Logger::notice('No valid XML returned from ' . $contact['id'] . ' - ' . $dest_url);
1032 Logger::debug('Returned XML: ' . $xml);
1036 $res = XML::parseString($xml);
1038 if (empty($res->status)) {
1042 if (!empty($res->message)) {
1043 Logger::info('Transmit to ' . $dest_url . ' returned status '.$res->status.' - '.$res->message);
1046 return intval($res->status);
1050 * Fetch the author data from head or entry items
1052 * @param \DOMXPath $xpath XPath object
1053 * @param \DOMNode $context In which context should the data be searched
1054 * @param array $importer Record of the importer user mixed with contact of the content
1055 * @param string $element Element name from which the data is fetched
1056 * @param bool $onlyfetch Should the data only be fetched or should it update the contact record as well
1057 * @param string $xml optional, default empty
1059 * @return array Relevant data of the author
1060 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1061 * @throws \ImagickException
1062 * @todo Find good type-hints for all parameter
1064 private static function fetchauthor(\DOMXPath $xpath, \DOMNode $context, $importer, $element, $onlyfetch, $xml = "")
1067 $author["name"] = XML::getFirstNodeValue($xpath, $element."/atom:name/text()", $context);
1068 $author["link"] = XML::getFirstNodeValue($xpath, $element."/atom:uri/text()", $context);
1070 $fields = ['id', 'uid', 'url', 'network', 'avatar-date', 'avatar', 'name-date', 'uri-date', 'addr',
1071 'name', 'nick', 'about', 'location', 'keywords', 'xmpp', 'bdyear', 'bd', 'hidden', 'contact-type'];
1072 $condition = ["`uid` = ? AND `nurl` = ? AND `network` != ? AND NOT `pending` AND NOT `blocked`",
1073 $importer["importer_uid"], Strings::normaliseLink($author["link"]), Protocol::STATUSNET];
1075 if ($importer['account-type'] != User::ACCOUNT_TYPE_COMMUNITY) {
1076 $condition = DBA::mergeConditions($condition, ['rel' => [Contact::SHARING, Contact::FRIEND]]);
1079 $contact_old = DBA::selectFirst('contact', $fields, $condition);
1081 if (DBA::isResult($contact_old)) {
1082 $author["contact-id"] = $contact_old["id"];
1083 $author["network"] = $contact_old["network"];
1085 Logger::info('Contact not found', ['condition' => $condition]);
1087 $author["contact-unknown"] = true;
1088 $contact = Contact::getByURL($author["link"], null, ["id", "network"]);
1089 $author["contact-id"] = $contact["id"] ?? $importer["id"];
1090 $author["network"] = $contact["network"] ?? $importer["network"];
1094 // Until now we aren't serving different sizes - but maybe later
1096 /// @todo check if "avatar" or "photo" would be the best field in the specification
1097 $avatars = $xpath->query($element . "/atom:link[@rel='avatar']", $context);
1098 foreach ($avatars as $avatar) {
1101 foreach ($avatar->attributes as $attributes) {
1102 /// @TODO Rewrite these similar if() to one switch
1103 if ($attributes->name == "href") {
1104 $href = $attributes->textContent;
1106 if ($attributes->name == "width") {
1107 $width = $attributes->textContent;
1109 if ($attributes->name == "updated") {
1110 $author["avatar-date"] = $attributes->textContent;
1113 if (($width > 0) && ($href != "")) {
1114 $avatarlist[$width] = $href;
1118 if (count($avatarlist) > 0) {
1119 krsort($avatarlist);
1120 $author["avatar"] = current($avatarlist);
1123 if (empty($author['avatar']) && !empty($author['link'])) {
1124 $cid = Contact::getIdForURL($author['link'], 0);
1126 $contact = DBA::selectFirst('contact', ['avatar'], ['id' => $cid]);
1127 if (DBA::isResult($contact)) {
1128 $author['avatar'] = $contact['avatar'];
1133 if (empty($author['avatar'])) {
1134 Logger::notice('Empty author: ' . $xml);
1135 $author['avatar'] = '';
1138 if (DBA::isResult($contact_old) && !$onlyfetch) {
1139 Logger::info("Check if contact details for contact " . $contact_old["id"] . " (" . $contact_old["nick"] . ") have to be updated.");
1141 $poco = ["url" => $contact_old["url"], "network" => $contact_old["network"]];
1143 // When was the last change to name or uri?
1144 $name_element = $xpath->query($element . "/atom:name", $context)->item(0);
1145 foreach ($name_element->attributes as $attributes) {
1146 if ($attributes->name == "updated") {
1147 $poco["name-date"] = $attributes->textContent;
1151 $link_element = $xpath->query($element . "/atom:link", $context)->item(0);
1152 foreach ($link_element->attributes as $attributes) {
1153 if ($attributes->name == "updated") {
1154 $poco["uri-date"] = $attributes->textContent;
1158 // Update contact data
1159 $value = XML::getFirstNodeValue($xpath, $element . "/dfrn:handle/text()", $context);
1161 $poco["addr"] = $value;
1164 $value = XML::getFirstNodeValue($xpath, $element . "/poco:displayName/text()", $context);
1166 $poco["name"] = $value;
1169 $value = XML::getFirstNodeValue($xpath, $element . "/poco:preferredUsername/text()", $context);
1171 $poco["nick"] = $value;
1174 $value = XML::getFirstNodeValue($xpath, $element . "/poco:note/text()", $context);
1176 $poco["about"] = $value;
1179 $value = XML::getFirstNodeValue($xpath, $element . "/poco:address/poco:formatted/text()", $context);
1181 $poco["location"] = $value;
1184 /// @todo Only search for elements with "poco:type" = "xmpp"
1185 $value = XML::getFirstNodeValue($xpath, $element . "/poco:ims/poco:value/text()", $context);
1187 $poco["xmpp"] = $value;
1190 /// @todo Add support for the following fields that we don't support by now in the contact table:
1191 /// - poco:utcOffset
1197 // If the "hide" element is present then the profile isn't searchable.
1198 $hide = intval(XML::getFirstNodeValue($xpath, $element . "/dfrn:hide/text()", $context) == "true");
1200 Logger::info("Hidden status for contact " . $contact_old["url"] . ": " . $hide);
1202 // If the contact isn't searchable then set the contact to "hidden".
1203 // Problem: This can be manually overridden by the user.
1205 $contact_old["hidden"] = true;
1208 // Save the keywords into the contact table
1210 $tagelements = $xpath->evaluate($element . "/poco:tags/text()", $context);
1211 foreach ($tagelements as $tag) {
1212 $tags[$tag->nodeValue] = $tag->nodeValue;
1216 $poco["keywords"] = implode(", ", $tags);
1219 // "dfrn:birthday" contains the birthday converted to UTC
1220 $birthday = XML::getFirstNodeValue($xpath, $element . "/dfrn:birthday/text()", $context);
1222 $birthday_date = new \DateTime($birthday);
1223 if ($birthday_date > new \DateTime()) {
1224 $poco["bdyear"] = $birthday_date->format("Y");
1226 } catch (\Exception $e) {
1230 // "poco:birthday" is the birthday in the format "yyyy-mm-dd"
1231 $value = XML::getFirstNodeValue($xpath, $element . "/poco:birthday/text()", $context);
1233 if (!in_array($value, ["", "0000-00-00", DBA::NULL_DATE])) {
1234 $bdyear = date("Y");
1235 $value = str_replace(["0000", "0001"], $bdyear, $value);
1237 if (strtotime($value) < time()) {
1238 $value = str_replace($bdyear, $bdyear + 1, $value);
1241 $poco["bd"] = $value;
1244 $contact = array_merge($contact_old, $poco);
1246 if ($contact_old["bdyear"] != $contact["bdyear"]) {
1247 Event::createBirthday($contact, $birthday);
1250 $fields = ['name' => $contact['name'], 'nick' => $contact['nick'], 'about' => $contact['about'],
1251 'location' => $contact['location'], 'addr' => $contact['addr'], 'keywords' => $contact['keywords'],
1252 'bdyear' => $contact['bdyear'], 'bd' => $contact['bd'], 'hidden' => $contact['hidden'],
1253 'xmpp' => $contact['xmpp'], 'name-date' => DateTimeFormat::utc($contact['name-date']),
1254 'unsearchable' => $contact['hidden'], 'uri-date' => DateTimeFormat::utc($contact['uri-date'])];
1256 Contact::update($fields, ['id' => $contact['id'], 'network' => $contact['network']], $contact_old);
1258 // Update the public contact. Don't set the "hidden" value, this is used differently for public contacts
1259 unset($fields['hidden']);
1260 $condition = ['uid' => 0, 'nurl' => Strings::normaliseLink($contact_old['url'])];
1261 Contact::update($fields, $condition, true);
1263 Contact::updateAvatar($contact['id'], $author['avatar']);
1265 $pcid = Contact::getIdForURL($contact_old['url']);
1266 if (!empty($pcid)) {
1267 Contact::updateAvatar($pcid, $author['avatar']);
1275 * Transforms activity objects into an XML string
1277 * @param object $xpath XPath object
1278 * @param object $activity Activity object
1279 * @param string $element element name
1281 * @return string XML string
1282 * @todo Find good type-hints for all parameter
1284 private static function transformActivity($xpath, $activity, $element)
1286 if (!is_object($activity)) {
1290 $obj_doc = new DOMDocument("1.0", "utf-8");
1291 $obj_doc->formatOutput = true;
1293 $obj_element = $obj_doc->createElementNS( ActivityNamespace::ATOM1, $element);
1295 $activity_type = $xpath->query("activity:object-type/text()", $activity)->item(0)->nodeValue;
1296 XML::addElement($obj_doc, $obj_element, "type", $activity_type);
1298 $id = $xpath->query("atom:id", $activity)->item(0);
1299 if (is_object($id)) {
1300 $obj_element->appendChild($obj_doc->importNode($id, true));
1303 $title = $xpath->query("atom:title", $activity)->item(0);
1304 if (is_object($title)) {
1305 $obj_element->appendChild($obj_doc->importNode($title, true));
1308 $links = $xpath->query("atom:link", $activity);
1309 if (is_object($links)) {
1310 foreach ($links as $link) {
1311 $obj_element->appendChild($obj_doc->importNode($link, true));
1315 $content = $xpath->query("atom:content", $activity)->item(0);
1316 if (is_object($content)) {
1317 $obj_element->appendChild($obj_doc->importNode($content, true));
1320 $obj_doc->appendChild($obj_element);
1322 $objxml = $obj_doc->saveXML($obj_element);
1324 /// @todo This isn't totally clean. We should find a way to transform the namespaces
1325 $objxml = str_replace("<".$element.' xmlns="http://www.w3.org/2005/Atom">', "<".$element.">", $objxml);
1330 * Processes the mail elements
1332 * @param object $xpath XPath object
1333 * @param object $mail mail elements
1334 * @param array $importer Record of the importer user mixed with contact of the content
1336 * @throws \Exception
1337 * @todo Find good type-hints for all parameter
1339 private static function processMail($xpath, $mail, $importer)
1341 Logger::notice("Processing mails");
1344 $msg["uid"] = $importer["importer_uid"];
1345 $msg["from-name"] = XML::getFirstValue($xpath, "dfrn:sender/dfrn:name/text()", $mail);
1346 $msg["from-url"] = XML::getFirstValue($xpath, "dfrn:sender/dfrn:uri/text()", $mail);
1347 $msg["from-photo"] = XML::getFirstValue($xpath, "dfrn:sender/dfrn:avatar/text()", $mail);
1348 $msg["contact-id"] = $importer["id"];
1349 $msg["uri"] = XML::getFirstValue($xpath, "dfrn:id/text()", $mail);
1350 $msg["parent-uri"] = XML::getFirstValue($xpath, "dfrn:in-reply-to/text()", $mail);
1351 $msg["created"] = DateTimeFormat::utc(XML::getFirstValue($xpath, "dfrn:sentdate/text()", $mail));
1352 $msg["title"] = XML::getFirstValue($xpath, "dfrn:subject/text()", $mail);
1353 $msg["body"] = XML::getFirstValue($xpath, "dfrn:content/text()", $mail);
1359 * Processes the suggestion elements
1361 * @param object $xpath XPath object
1362 * @param object $suggestion suggestion elements
1363 * @param array $importer Record of the importer user mixed with contact of the content
1365 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1366 * @todo Find good type-hints for all parameter
1368 private static function processSuggestion($xpath, $suggestion, $importer)
1370 Logger::notice('Processing suggestions');
1372 $url = $xpath->evaluate('string(dfrn:url[1]/text())', $suggestion);
1373 $cid = Contact::getIdForURL($url);
1374 $note = $xpath->evaluate('string(dfrn:note[1]/text())', $suggestion);
1376 return self::addSuggestion($importer['importer_uid'], $cid, $importer['id'], $note);
1380 * Suggest a given contact to a given user from a given contact
1382 * @param integer $uid
1383 * @param integer $cid
1384 * @param integer $from_cid
1385 * @return bool Was the adding successful?
1387 private static function addSuggestion(int $uid, int $cid, int $from_cid, string $note = '')
1389 $owner = User::getOwnerDataById($uid);
1390 $contact = Contact::getById($cid);
1391 $from_contact = Contact::getById($from_cid);
1393 if (DBA::exists('contact', ['nurl' => Strings::normaliseLink($contact['url']), 'uid' => $uid])) {
1397 // Quit if we already have an introduction for this person
1398 if (DI::intro()->suggestionExistsForUser($cid, $uid)) {
1403 $suggest['uid'] = $uid;
1404 $suggest['cid'] = $from_cid;
1405 $suggest['url'] = $contact['url'];
1406 $suggest['name'] = $contact['name'];
1407 $suggest['photo'] = $contact['photo'];
1408 $suggest['request'] = $contact['request'];
1409 $suggest['title'] = '';
1410 $suggest['body'] = $note;
1412 DI::intro()->save(DI::introFactory()->createNew(
1420 DI::notify()->createFromArray([
1421 'type' => Notification\Type::SUGGEST,
1422 'otype' => Notification\ObjectType::INTRO,
1423 'verb' => Activity::REQ_FRIEND,
1424 'uid' => $owner['uid'],
1425 'cid' => $from_contact['uid'],
1427 'link' => DI::baseUrl().'/notifications/intros',
1434 * Processes the relocation elements
1436 * @param object $xpath XPath object
1437 * @param object $relocation relocation elements
1438 * @param array $importer Record of the importer user mixed with contact of the content
1440 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1441 * @throws \ImagickException
1442 * @todo Find good type-hints for all parameter
1444 private static function processRelocation($xpath, $relocation, $importer)
1446 Logger::notice("Processing relocations");
1448 /// @TODO Rewrite this to one statement
1450 $relocate["uid"] = $importer["importer_uid"];
1451 $relocate["cid"] = $importer["id"];
1452 $relocate["url"] = $xpath->query("dfrn:url/text()", $relocation)->item(0)->nodeValue;
1453 $relocate["addr"] = $xpath->query("dfrn:addr/text()", $relocation)->item(0)->nodeValue;
1454 $relocate["name"] = $xpath->query("dfrn:name/text()", $relocation)->item(0)->nodeValue;
1455 $relocate["avatar"] = $xpath->query("dfrn:avatar/text()", $relocation)->item(0)->nodeValue;
1456 $relocate["photo"] = $xpath->query("dfrn:photo/text()", $relocation)->item(0)->nodeValue;
1457 $relocate["thumb"] = $xpath->query("dfrn:thumb/text()", $relocation)->item(0)->nodeValue;
1458 $relocate["micro"] = $xpath->query("dfrn:micro/text()", $relocation)->item(0)->nodeValue;
1459 $relocate["request"] = $xpath->query("dfrn:request/text()", $relocation)->item(0)->nodeValue;
1460 $relocate["confirm"] = $xpath->query("dfrn:confirm/text()", $relocation)->item(0)->nodeValue;
1461 $relocate["notify"] = $xpath->query("dfrn:notify/text()", $relocation)->item(0)->nodeValue;
1462 $relocate["poll"] = $xpath->query("dfrn:poll/text()", $relocation)->item(0)->nodeValue;
1463 $relocate["sitepubkey"] = $xpath->query("dfrn:sitepubkey/text()", $relocation)->item(0)->nodeValue;
1465 if (($relocate["avatar"] == "") && ($relocate["photo"] != "")) {
1466 $relocate["avatar"] = $relocate["photo"];
1469 if ($relocate["addr"] == "") {
1470 $relocate["addr"] = preg_replace("=(https?://)(.*)/profile/(.*)=ism", "$3@$2", $relocate["url"]);
1474 $old = Contact::selectFirst(['photo', 'url'], ['id' => $importer["id"], 'uid' => $importer["importer_uid"]]);
1476 if (!DBA::isResult($old)) {
1477 Logger::notice("Query failed to execute, no result returned in " . __FUNCTION__);
1481 // Update the contact table. We try to find every entry.
1482 $fields = ['name' => $relocate["name"], 'avatar' => $relocate["avatar"],
1483 'url' => $relocate["url"], 'nurl' => Strings::normaliseLink($relocate["url"]),
1484 'addr' => $relocate["addr"], 'request' => $relocate["request"],
1485 'confirm' => $relocate["confirm"], 'notify' => $relocate["notify"],
1486 'poll' => $relocate["poll"], 'site-pubkey' => $relocate["sitepubkey"]];
1487 $condition = ["(`id` = ?) OR (`nurl` = ?)", $importer["id"], Strings::normaliseLink($old["url"])];
1489 Contact::update($fields, $condition);
1491 Contact::updateAvatar($importer["id"], $relocate["avatar"], true);
1493 Logger::notice('Contacts are updated.');
1496 /// merge with current record, current contents have priority
1497 /// update record, set url-updated
1498 /// update profile photos
1499 /// schedule a scan?
1506 * @param array $current the current item record
1507 * @param array $item the new item record
1508 * @param array $importer Record of the importer user mixed with contact of the content
1509 * @param int $entrytype Is it a toplevel entry, a comment or a relayed comment?
1511 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1512 * @todo set proper type-hints (array?)
1514 private static function updateContent($current, $item, $importer, $entrytype)
1518 if (self::isEditedTimestampNewer($current, $item)) {
1519 // do not accept (ignore) an earlier edit than one we currently have.
1520 if (DateTimeFormat::utc($item["edited"]) < $current["edited"]) {
1524 $fields = ['title' => $item['title'] ?? '', 'body' => $item['body'] ?? '',
1525 'changed' => DateTimeFormat::utcNow(),
1526 'edited' => DateTimeFormat::utc($item["edited"])];
1528 $condition = ["`uri` = ? AND `uid` IN (0, ?)", $item["uri"], $importer["importer_uid"]];
1529 Item::update($fields, $condition);
1537 * Detects the entry type of the item
1539 * @param array $importer Record of the importer user mixed with contact of the content
1540 * @param array $item the new item record
1542 * @return int Is it a toplevel entry, a comment or a relayed comment?
1543 * @throws \Exception
1544 * @todo set proper type-hints (array?)
1546 private static function getEntryType($importer, $item)
1548 if ($item["thr-parent"] != $item["uri"]) {
1551 if ($importer['account-type'] == User::ACCOUNT_TYPE_COMMUNITY) {
1554 Logger::notice("possible community action");
1556 $sql_extra = " AND `self` AND `wall`";
1559 // was the top-level post for this action written by somebody on this site?
1560 // Specifically, the recipient?
1561 $parent = Post::selectFirst(['wall'],
1562 ["`uri` = ? AND `uid` = ?" . $sql_extra, $item["thr-parent"], $importer["importer_uid"]]);
1564 $is_a_remote_action = DBA::isResult($parent);
1566 if ($is_a_remote_action) {
1567 return DFRN::REPLY_RC;
1572 return DFRN::TOP_LEVEL;
1579 * @param array $item The new item record
1580 * @param array $importer Record of the importer user mixed with contact of the content
1582 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1583 * @todo set proper type-hints (array?)
1585 private static function doPoke(array $item, array $importer)
1587 $verb = urldecode(substr($item["verb"], strpos($item["verb"], "#")+1));
1591 $xo = XML::parseString($item["object"]);
1593 if (($xo->type == Activity\ObjectType::PERSON) && ($xo->id)) {
1594 // somebody was poked/prodded. Was it me?
1596 foreach ($xo->link as $l) {
1597 $atts = $l->attributes();
1598 switch ($atts["rel"]) {
1600 $Blink = $atts["href"];
1607 if ($Blink && Strings::compareLink($Blink, DI::baseUrl() . "/profile/" . $importer["nickname"])) {
1608 $author = DBA::selectFirst('contact', ['id', 'name', 'thumb', 'url'], ['id' => $item['author-id']]);
1610 $parent = Post::selectFirst(['id'], ['uri' => $item['thr-parent'], 'uid' => $importer["importer_uid"]]);
1611 $item['parent'] = $parent['id'];
1613 // send a notification
1614 DI::notify()->createFromArray(
1616 "type" => Notification\Type::POKE,
1617 "otype" => Notification\ObjectType::PERSON,
1618 "activity" => $verb,
1619 "verb" => $item["verb"],
1620 "uid" => $importer["importer_uid"],
1621 "cid" => $author["id"],
1623 "link" => DI::baseUrl() . "/display/" . urlencode($item['guid']),
1631 * Processes several actions, depending on the verb
1633 * @param int $entrytype Is it a toplevel entry, a comment or a relayed comment?
1634 * @param array $importer Record of the importer user mixed with contact of the content
1635 * @param array $item the new item record
1636 * @param bool $is_like Is the verb a "like"?
1638 * @return bool Should the processing of the entries be continued?
1639 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1640 * @todo set proper type-hints (array?)
1642 private static function processVerbs($entrytype, $importer, &$item, &$is_like)
1644 Logger::info("Process verb ".$item["verb"]." and object-type ".$item["object-type"]." for entrytype ".$entrytype);
1646 if (($entrytype == DFRN::TOP_LEVEL) && !empty($importer['id'])) {
1647 // The filling of the the "contact" variable is done for legcy reasons
1648 // The functions below are partly used by ostatus.php as well - where we have this variable
1649 $contact = Contact::selectFirst([], ['id' => $importer['id']]);
1651 $activity = DI::activity();
1653 // Big question: Do we need these functions? They were part of the "consume_feed" function.
1654 // This function once was responsible for DFRN and OStatus.
1655 if ($activity->match($item["verb"], Activity::FOLLOW)) {
1656 Logger::notice("New follower");
1657 Contact::addRelationship($importer, $contact, $item);
1660 if ($activity->match($item["verb"], Activity::UNFOLLOW)) {
1661 Logger::notice("Lost follower");
1662 Contact::removeFollower($contact);
1665 if ($activity->match($item["verb"], Activity::REQ_FRIEND)) {
1666 Logger::notice("New friend request");
1667 Contact::addRelationship($importer, $contact, $item, true);
1670 if ($activity->match($item["verb"], Activity::UNFRIEND)) {
1671 Logger::notice("Lost sharer");
1672 Contact::removeSharer($contact);
1676 if (($item["verb"] == Activity::LIKE)
1677 || ($item["verb"] == Activity::DISLIKE)
1678 || ($item["verb"] == Activity::ATTEND)
1679 || ($item["verb"] == Activity::ATTENDNO)
1680 || ($item["verb"] == Activity::ATTENDMAYBE)
1681 || ($item["verb"] == Activity::ANNOUNCE)
1684 $item["gravity"] = GRAVITY_ACTIVITY;
1685 // only one like or dislike per person
1686 // split into two queries for performance issues
1687 $condition = ['uid' => $item["uid"], 'author-id' => $item["author-id"], 'gravity' => GRAVITY_ACTIVITY,
1688 'verb' => $item['verb'], 'parent-uri' => $item['thr-parent']];
1689 if (Post::exists($condition)) {
1693 $condition = ['uid' => $item["uid"], 'author-id' => $item["author-id"], 'gravity' => GRAVITY_ACTIVITY,
1694 'verb' => $item['verb'], 'thr-parent' => $item['thr-parent']];
1695 if (Post::exists($condition)) {
1699 // The owner of an activity must be the author
1700 $item["owner-name"] = $item["author-name"];
1701 $item["owner-link"] = $item["author-link"];
1702 $item["owner-avatar"] = $item["author-avatar"];
1703 $item["owner-id"] = $item["author-id"];
1708 if (($item["verb"] == Activity::TAG) && ($item["object-type"] == Activity\ObjectType::TAGTERM)) {
1709 $xo = XML::parseString($item["object"]);
1710 $xt = XML::parseString($item["target"]);
1712 if ($xt->type == Activity\ObjectType::NOTE) {
1713 $item_tag = Post::selectFirst(['id', 'uri-id'], ['uri' => $xt->id, 'uid' => $importer["importer_uid"]]);
1715 if (!DBA::isResult($item_tag)) {
1716 Logger::notice("Query failed to execute, no result returned in " . __FUNCTION__);
1720 // extract tag, if not duplicate, add to parent item
1722 Tag::store($item_tag['uri-id'], Tag::HASHTAG, $xo->content);
1731 * Processes the link elements
1733 * @param object $links link elements
1734 * @param array $item the item record
1736 * @todo set proper type-hints
1738 private static function parseLinks($links, &$item)
1745 foreach ($links as $link) {
1746 foreach ($link->attributes as $attributes) {
1747 switch ($attributes->name) {
1748 case "href" : $href = $attributes->textContent; break;
1749 case "rel" : $rel = $attributes->textContent; break;
1750 case "type" : $type = $attributes->textContent; break;
1751 case "length": $length = $attributes->textContent; break;
1752 case "title" : $title = $attributes->textContent; break;
1755 if (($rel != "") && ($href != "")) {
1758 $item["plink"] = $href;
1761 Post\Media::insert(['uri-id' => $item['uri-id'], 'type' => Post\Media::DOCUMENT,
1762 'url' => $href, 'mimetype' => $type, 'size' => $length, 'description' => $title]);
1770 * Checks if an incoming message is wanted
1772 * @param array $item
1773 * @param array $imporer
1774 * @return boolean Is the message wanted?
1776 private static function isSolicitedMessage(array $item, array $importer)
1778 if (DBA::exists('contact', ["`nurl` = ? AND `uid` != ? AND `rel` IN (?, ?)",
1779 Strings::normaliseLink($item["author-link"]), 0, Contact::FRIEND, Contact::SHARING])) {
1780 Logger::debug('Author has got followers - accepted', ['uri-id' => $item['uri-id'], 'guid' => $item['guid'], 'url' => $item['uri'], 'author' => $item["author-link"]]);
1784 if ($importer['importer_uid'] != 0) {
1785 Logger::debug('Message is directed to a user - accepted', ['uri-id' => $item['uri-id'], 'guid' => $item['guid'], 'url' => $item['uri'], 'importer' => $importer['importer_uid']]);
1789 if ($item['uri'] != $item['thr-parent']) {
1790 Logger::debug('Message is no parent - accepted', ['uri-id' => $item['uri-id'], 'guid' => $item['guid'], 'url' => $item['uri']]);
1794 $tags = array_column(Tag::getByURIId($item['uri-id'], [Tag::HASHTAG]), 'name');
1795 if (Relay::isSolicitedPost($tags, $item['body'], $item['author-id'], $item['uri'], Protocol::DFRN)) {
1796 Logger::debug('Post is accepted because of the relay settings', ['uri-id' => $item['uri-id'], 'guid' => $item['guid'], 'url' => $item['uri'], 'author' => $item["author-link"]]);
1804 * Processes the entry elements which contain the items and comments
1806 * @param array $header Array of the header elements that always stay the same
1807 * @param object $xpath XPath object
1808 * @param object $entry entry elements
1809 * @param array $importer Record of the importer user mixed with contact of the content
1810 * @param string $xml xml
1812 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1813 * @throws \ImagickException
1814 * @todo Add type-hints
1816 private static function processEntry($header, $xpath, $entry, $importer, $xml, $protocol)
1818 Logger::notice("Processing entries");
1822 $item["protocol"] = $protocol;
1824 $item["source"] = $xml;
1827 $item["uri"] = XML::getFirstNodeValue($xpath, "atom:id/text()", $entry);
1829 $item["edited"] = XML::getFirstNodeValue($xpath, "atom:updated/text()", $entry);
1831 $current = Post::selectFirst(['id', 'uid', 'edited', 'body'],
1832 ['uri' => $item["uri"], 'uid' => $importer["importer_uid"]]
1834 // Is there an existing item?
1835 if (DBA::isResult($current) && !self::isEditedTimestampNewer($current, $item)) {
1836 Logger::info("Item ".$item["uri"]." (".$item['edited'].") already existed.");
1841 $owner = self::fetchauthor($xpath, $entry, $importer, "dfrn:owner", true, $xml);
1843 $owner_unknown = (isset($owner["contact-unknown"]) && $owner["contact-unknown"]);
1845 $item["owner-name"] = $owner["name"];
1846 $item["owner-link"] = $owner["link"];
1847 $item["owner-avatar"] = $owner["avatar"];
1848 $item["owner-id"] = Contact::getIdForURL($owner["link"], 0);
1851 $author = self::fetchauthor($xpath, $entry, $importer, "atom:author", true, $xml);
1853 $item["author-name"] = $author["name"];
1854 $item["author-link"] = $author["link"];
1855 $item["author-avatar"] = $author["avatar"];
1856 $item["author-id"] = Contact::getIdForURL($author["link"], 0);
1858 $item["title"] = XML::getFirstNodeValue($xpath, "atom:title/text()", $entry);
1860 if (!empty($item["title"])) {
1861 $item["post-type"] = Item::PT_ARTICLE;
1863 $item["post-type"] = Item::PT_NOTE;
1866 $item["created"] = XML::getFirstNodeValue($xpath, "atom:published/text()", $entry);
1868 $item["body"] = XML::getFirstNodeValue($xpath, "dfrn:env/text()", $entry);
1869 $item["body"] = str_replace([' ',"\t","\r","\n"], ['','','',''], $item["body"]);
1871 $item["body"] = Strings::base64UrlDecode($item["body"]);
1873 $item["body"] = BBCode::limitBodySize($item["body"]);
1875 /// @todo We should check for a repeated post and if we know the repeated author.
1877 // We don't need the content element since "dfrn:env" is always present
1878 //$item["body"] = $xpath->query("atom:content/text()", $entry)->item(0)->nodeValue;
1880 $item["location"] = XML::getFirstNodeValue($xpath, "dfrn:location/text()", $entry);
1882 $item["coord"] = XML::getFirstNodeValue($xpath, "georss:point", $entry);
1884 $item["private"] = XML::getFirstNodeValue($xpath, "dfrn:private/text()", $entry);
1886 $unlisted = XML::getFirstNodeValue($xpath, "dfrn:unlisted/text()", $entry);
1887 if (!empty($unlisted) && ($item['private'] != Item::PRIVATE)) {
1888 $item['private'] = Item::UNLISTED;
1891 $item["extid"] = XML::getFirstNodeValue($xpath, "dfrn:extid/text()", $entry);
1893 if (XML::getFirstNodeValue($xpath, "dfrn:bookmark/text()", $entry) == "true") {
1894 $item["post-type"] = Item::PT_PAGE;
1897 $notice_info = $xpath->query("statusnet:notice_info", $entry);
1898 if ($notice_info && ($notice_info->length > 0)) {
1899 foreach ($notice_info->item(0)->attributes as $attributes) {
1900 if ($attributes->name == "source") {
1901 $item["app"] = strip_tags($attributes->textContent);
1906 $item["guid"] = XML::getFirstNodeValue($xpath, "dfrn:diaspora_guid/text()", $entry);
1908 $item['uri-id'] = ItemURI::insert(['uri' => $item['uri'], 'guid' => $item['guid']]);
1910 $item["body"] = Item::improveSharedDataInBody($item);
1912 Tag::storeFromBody($item['uri-id'], $item["body"]);
1914 // We store the data from "dfrn:diaspora_signature" in a different table, this is done in "Item::insert"
1915 $dsprsig = XML::unescape(XML::getFirstNodeValue($xpath, "dfrn:diaspora_signature/text()", $entry));
1916 if ($dsprsig != "") {
1917 $signature = json_decode(base64_decode($dsprsig));
1918 // We don't store the old style signatures anymore that also contained the "signature" and "signer"
1919 if (!empty($signature->signed_text) && empty($signature->signature) && empty($signature->signer)) {
1920 $item["diaspora_signed_text"] = $signature->signed_text;
1924 $item["verb"] = XML::getFirstNodeValue($xpath, "activity:verb/text()", $entry);
1926 if (XML::getFirstNodeValue($xpath, "activity:object-type/text()", $entry) != "") {
1927 $item["object-type"] = XML::getFirstNodeValue($xpath, "activity:object-type/text()", $entry);
1930 $object = $xpath->query("activity:object", $entry)->item(0);
1931 $item["object"] = self::transformActivity($xpath, $object, "object");
1933 if (trim($item["object"]) != "") {
1934 $r = XML::parseString($item["object"]);
1935 if (isset($r->type)) {
1936 $item["object-type"] = $r->type;
1940 $target = $xpath->query("activity:target", $entry)->item(0);
1941 $item["target"] = self::transformActivity($xpath, $target, "target");
1943 $categories = $xpath->query("atom:category", $entry);
1945 foreach ($categories as $category) {
1948 foreach ($category->attributes as $attributes) {
1949 if ($attributes->name == "term") {
1950 $term = $attributes->textContent;
1953 if ($attributes->name == "scheme") {
1954 $scheme = $attributes->textContent;
1958 if (($term != "") && ($scheme != "")) {
1959 $parts = explode(":", $scheme);
1960 if ((count($parts) >= 4) && (array_shift($parts) == "X-DFRN")) {
1961 $termurl = array_pop($parts);
1962 $termurl = array_pop($parts) . ':' . $termurl;
1963 Tag::store($item['uri-id'], Tag::IMPLICIT_MENTION, $term, $termurl);
1969 $links = $xpath->query("atom:link", $entry);
1971 self::parseLinks($links, $item);
1974 $item['conversation-uri'] = XML::getFirstNodeValue($xpath, 'ostatus:conversation/text()', $entry);
1976 $conv = $xpath->query('ostatus:conversation', $entry);
1977 if (is_object($conv->item(0))) {
1978 foreach ($conv->item(0)->attributes as $attributes) {
1979 if ($attributes->name == "ref") {
1980 $item['conversation-uri'] = $attributes->textContent;
1982 if ($attributes->name == "href") {
1983 $item['conversation-href'] = $attributes->textContent;
1988 // Is it a reply or a top level posting?
1989 $item['thr-parent'] = $item['uri'];
1991 $inreplyto = $xpath->query("thr:in-reply-to", $entry);
1992 if (is_object($inreplyto->item(0))) {
1993 foreach ($inreplyto->item(0)->attributes as $attributes) {
1994 if ($attributes->name == "ref") {
1995 $item['thr-parent'] = $attributes->textContent;
2000 // Check if the message is wanted
2001 if (!self::isSolicitedMessage($item, $importer)) {
2002 DBA::delete('item-uri', ['uri' => $item['uri']]);
2006 // Get the type of the item (Top level post, reply or remote reply)
2007 $entrytype = self::getEntryType($importer, $item);
2009 // Now assign the rest of the values that depend on the type of the message
2010 if (in_array($entrytype, [DFRN::REPLY, DFRN::REPLY_RC])) {
2011 if (!isset($item["object-type"])) {
2012 $item["object-type"] = Activity\ObjectType::COMMENT;
2015 if ($item["contact-id"] != $owner["contact-id"]) {
2016 $item["contact-id"] = $owner["contact-id"];
2019 if (($item["network"] != $owner["network"]) && ($owner["network"] != "")) {
2020 $item["network"] = $owner["network"];
2023 if ($item["contact-id"] != $author["contact-id"]) {
2024 $item["contact-id"] = $author["contact-id"];
2027 if (($item["network"] != $author["network"]) && ($author["network"] != "")) {
2028 $item["network"] = $author["network"];
2032 // Ensure to have the correct share data
2033 $item = Item::addShareDataFromOriginal($item);
2035 if ($entrytype == DFRN::REPLY_RC) {
2037 } elseif ($entrytype == DFRN::TOP_LEVEL) {
2038 if (!isset($item["object-type"])) {
2039 $item["object-type"] = Activity\ObjectType::NOTE;
2043 if (($item["object-type"] == Activity\ObjectType::EVENT) && !$owner_unknown) {
2044 Logger::info("Item ".$item["uri"]." seems to contain an event.");
2045 $ev = Event::fromBBCode($item["body"]);
2046 if ((!empty($ev['desc']) || !empty($ev['summary'])) && !empty($ev['start'])) {
2047 Logger::info("Event in item ".$item["uri"]." was found.");
2048 $ev["cid"] = $importer["id"];
2049 $ev["uid"] = $importer["importer_uid"];
2050 $ev["uri"] = $item["uri"];
2051 $ev["edited"] = $item["edited"];
2052 $ev["private"] = $item["private"];
2053 $ev["guid"] = $item["guid"];
2054 $ev["plink"] = $item["plink"];
2055 $ev["network"] = $item["network"];
2056 $ev["protocol"] = $item["protocol"];
2057 $ev["direction"] = $item["direction"];
2058 $ev["source"] = $item["source"];
2060 $condition = ['uri' => $item["uri"], 'uid' => $importer["importer_uid"]];
2061 $event = DBA::selectFirst('event', ['id'], $condition);
2062 if (DBA::isResult($event)) {
2063 $ev["id"] = $event["id"];
2066 $event_id = Event::store($ev);
2067 Logger::info('Event was stored', ['id' => $event_id]);
2069 $item = Event::getItemArrayForImportedId($event_id, $item);
2074 if (!self::processVerbs($entrytype, $importer, $item, $is_like)) {
2075 Logger::info("Exiting because 'processVerbs' told us so");
2079 // This check is done here to be able to receive connection requests in "processVerbs"
2080 if (($entrytype == DFRN::TOP_LEVEL) && $owner_unknown) {
2081 Logger::info("Item won't be stored because user " . $importer["importer_uid"] . " doesn't follow " . $item["owner-link"] . ".");
2086 // Update content if 'updated' changes
2087 if (DBA::isResult($current)) {
2088 if (self::updateContent($current, $item, $importer, $entrytype)) {
2089 Logger::info("Item ".$item["uri"]." was updated.");
2091 Logger::info("Item " . $item["uri"] . " already existed.");
2096 if (in_array($entrytype, [DFRN::REPLY, DFRN::REPLY_RC])) {
2097 // Will be overwritten for sharing accounts in Item::insert
2098 if (empty($item['post-reason']) && ($entrytype == DFRN::REPLY)) {
2099 $item['post-reason'] = Item::PR_COMMENT;
2102 $posted_id = Item::insert($item);
2104 Logger::info("Reply from contact ".$item["contact-id"]." was stored with id ".$posted_id);
2106 if ($item['uid'] == 0) {
2107 Item::distribute($posted_id);
2112 } else { // $entrytype == DFRN::TOP_LEVEL
2113 if (($importer["uid"] == 0) && ($importer["importer_uid"] != 0)) {
2114 Logger::info("Contact ".$importer["id"]." isn't known to user ".$importer["importer_uid"].". The post will be ignored.");
2117 if (!Strings::compareLink($item["owner-link"], $importer["url"])) {
2119 * The item owner info is not our contact. It's OK and is to be expected if this is a tgroup delivery,
2120 * but otherwise there's a possible data mixup on the sender's system.
2121 * the tgroup delivery code called from Item::insert will correct it if it's a forum,
2122 * but we're going to unconditionally correct it here so that the post will always be owned by our contact.
2124 Logger::info('Correcting item owner.');
2125 $item["owner-link"] = $importer["url"];
2126 $item["owner-id"] = Contact::getIdForURL($importer["url"], 0);
2129 if (($importer["rel"] == Contact::FOLLOWER) && (!self::tgroupCheck($importer["importer_uid"], $item))) {
2130 Logger::info("Contact ".$importer["id"]." is only follower and tgroup check was negative.");
2134 // This is my contact on another system, but it's really me.
2135 // Turn this into a wall post.
2136 $notify = Item::isRemoteSelf($importer, $item);
2138 $posted_id = Item::insert($item, $notify);
2141 $posted_id = $notify;
2144 Logger::info("Item was stored with id ".$posted_id);
2146 if ($item['uid'] == 0) {
2147 Item::distribute($posted_id);
2150 if (stristr($item["verb"], Activity::POKE)) {
2151 $item['id'] = $posted_id;
2152 self::doPoke($item, $importer);
2160 * @param object $xpath XPath object
2161 * @param object $deletion deletion elements
2162 * @param array $importer Record of the importer user mixed with contact of the content
2164 * @throws \Exception
2165 * @todo set proper type-hints
2167 private static function processDeletion($xpath, $deletion, $importer)
2169 Logger::notice("Processing deletions");
2172 foreach ($deletion->attributes as $attributes) {
2173 if ($attributes->name == "ref") {
2174 $uri = $attributes->textContent;
2178 if (!$uri || !$importer["id"]) {
2182 $condition = ['uri' => $uri, 'uid' => $importer["importer_uid"]];
2183 $item = Post::selectFirst(['id', 'parent', 'contact-id', 'uri-id', 'deleted', 'gravity'], $condition);
2184 if (!DBA::isResult($item)) {
2185 Logger::info("Item with uri " . $uri . " for user " . $importer["importer_uid"] . " wasn't found.");
2189 if (DBA::exists('post-category', ['uri-id' => $item['uri-id'], 'uid' => $importer['importer_uid'], 'type' => Post\Category::FILE])) {
2190 Logger::notice("Item is filed. It won't be deleted.", ['uri' => $uri, 'uri-id' => $item['uri_id'], 'uid' => $importer["importer_uid"]]);
2194 // When it is a starting post it has to belong to the person that wants to delete it
2195 if (($item['gravity'] == GRAVITY_PARENT) && ($item['contact-id'] != $importer["id"])) {
2196 Logger::info("Item with uri " . $uri . " don't belong to contact " . $importer["id"] . " - ignoring deletion.");
2200 // Comments can be deleted by the thread owner or comment owner
2201 if (($item['gravity'] != GRAVITY_PARENT) && ($item['contact-id'] != $importer["id"])) {
2202 $condition = ['id' => $item['parent'], 'contact-id' => $importer["id"]];
2203 if (!Post::exists($condition)) {
2204 Logger::info("Item with uri " . $uri . " wasn't found or mustn't be deleted by contact " . $importer["id"] . " - ignoring deletion.");
2209 if ($item["deleted"]) {
2213 Logger::info('deleting item '.$item['id'].' uri='.$uri);
2215 Item::markForDeletion(['id' => $item['id']]);
2219 * Imports a DFRN message
2221 * @param string $xml The DFRN message
2222 * @param array $importer Record of the importer user mixed with contact of the content
2223 * @param int $protocol Transport protocol
2224 * @param int $direction Is the message pushed or pulled?
2225 * @return integer Import status
2226 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2227 * @throws \ImagickException
2228 * @todo set proper type-hints
2230 public static function import($xml, $importer, $protocol, $direction)
2236 $doc = new DOMDocument();
2237 @$doc->loadXML($xml);
2239 $xpath = new DOMXPath($doc);
2240 $xpath->registerNamespace("atom", ActivityNamespace::ATOM1);
2241 $xpath->registerNamespace("thr", ActivityNamespace::THREAD);
2242 $xpath->registerNamespace("at", ActivityNamespace::TOMB);
2243 $xpath->registerNamespace("media", ActivityNamespace::MEDIA);
2244 $xpath->registerNamespace("dfrn", ActivityNamespace::DFRN);
2245 $xpath->registerNamespace("activity", ActivityNamespace::ACTIVITY);
2246 $xpath->registerNamespace("georss", ActivityNamespace::GEORSS);
2247 $xpath->registerNamespace("poco", ActivityNamespace::POCO);
2248 $xpath->registerNamespace("ostatus", ActivityNamespace::OSTATUS);
2249 $xpath->registerNamespace("statusnet", ActivityNamespace::STATUSNET);
2252 $header["uid"] = $importer["importer_uid"];
2253 $header["network"] = Protocol::DFRN;
2254 $header["wall"] = 0;
2255 $header["origin"] = 0;
2256 $header["contact-id"] = $importer["id"];
2257 $header["direction"] = $direction;
2259 if ($direction === Conversation::RELAY) {
2260 $header['post-reason'] = Item::PR_RELAY;
2263 // Update the contact table if the data has changed
2265 // The "atom:author" is only present in feeds
2266 if ($xpath->query("/atom:feed/atom:author")->length > 0) {
2267 self::fetchauthor($xpath, $doc->firstChild, $importer, "atom:author", false, $xml);
2270 // Only the "dfrn:owner" in the head section contains all data
2271 if ($xpath->query("/atom:feed/dfrn:owner")->length > 0) {
2272 self::fetchauthor($xpath, $doc->firstChild, $importer, "dfrn:owner", false, $xml);
2275 Logger::info("Import DFRN message for user " . $importer["importer_uid"] . " from contact " . $importer["id"]);
2277 if (!empty($importer['gsid']) && ($protocol == Conversation::PARCEL_DIASPORA_DFRN)) {
2278 GServer::setProtocol($importer['gsid'], Post\DeliveryData::DFRN);
2281 // is it a public forum? Private forums aren't exposed with this method
2282 $forum = intval(XML::getFirstNodeValue($xpath, "/atom:feed/dfrn:community/text()"));
2284 // The account type is new since 3.5.1
2285 if ($xpath->query("/atom:feed/dfrn:account_type")->length > 0) {
2286 // Hint: We are using separate update calls for uid=0 and uid!=0 since a combined call is bad for the database performance
2288 $accounttype = intval(XML::getFirstNodeValue($xpath, "/atom:feed/dfrn:account_type/text()"));
2290 if ($accounttype != $importer["contact-type"]) {
2291 Contact::update(['contact-type' => $accounttype], ['id' => $importer['id']]);
2293 // Updating the public contact as well
2294 Contact::update(['contact-type' => $accounttype], ['uid' => 0, 'nurl' => $importer['nurl']]);
2296 // A forum contact can either have set "forum" or "prv" - but not both
2297 if ($accounttype == User::ACCOUNT_TYPE_COMMUNITY) {
2298 // It's a forum, so either set the public or private forum flag
2299 $condition = ['(`forum` != ? OR `prv` != ?) AND `id` = ?', $forum, !$forum, $importer['id']];
2300 Contact::update(['forum' => $forum, 'prv' => !$forum], $condition);
2302 // Updating the public contact as well
2303 $condition = ['(`forum` != ? OR `prv` != ?) AND `uid` = 0 AND `nurl` = ?', $forum, !$forum, $importer['nurl']];
2304 Contact::update(['forum' => $forum, 'prv' => !$forum], $condition);
2306 // It's not a forum, so remove the flags
2307 $condition = ['(`forum` OR `prv`) AND `id` = ?', $importer['id']];
2308 Contact::update(['forum' => false, 'prv' => false], $condition);
2310 // Updating the public contact as well
2311 $condition = ['(`forum` OR `prv`) AND `uid` = 0 AND `nurl` = ?', $importer['nurl']];
2312 Contact::update(['forum' => false, 'prv' => false], $condition);
2314 } elseif ($forum != $importer["forum"]) { // Deprecated since 3.5.1
2315 $condition = ['`forum` != ? AND `id` = ?', $forum, $importer["id"]];
2316 Contact::update(['forum' => $forum], $condition);
2318 // Updating the public contact as well
2319 $condition = ['`forum` != ? AND `uid` = 0 AND `nurl` = ?', $forum, $importer['nurl']];
2320 Contact::update(['forum' => $forum], $condition);
2324 // We are processing relocations even if we are ignoring a contact
2325 $relocations = $xpath->query("/atom:feed/dfrn:relocate");
2326 foreach ($relocations as $relocation) {
2327 self::processRelocation($xpath, $relocation, $importer);
2330 if (($importer["uid"] != 0) && !$importer["readonly"]) {
2331 $mails = $xpath->query("/atom:feed/dfrn:mail");
2332 foreach ($mails as $mail) {
2333 self::processMail($xpath, $mail, $importer);
2336 $suggestions = $xpath->query("/atom:feed/dfrn:suggest");
2337 foreach ($suggestions as $suggestion) {
2338 self::processSuggestion($xpath, $suggestion, $importer);
2342 $deletions = $xpath->query("/atom:feed/at:deleted-entry");
2343 if (!empty($deletions)) {
2344 foreach ($deletions as $deletion) {
2345 self::processDeletion($xpath, $deletion, $importer);
2347 if (count($deletions) > 0) {
2348 Logger::notice('Deletions had been processed');
2353 $entries = $xpath->query("/atom:feed/atom:entry");
2354 foreach ($entries as $entry) {
2355 self::processEntry($header, $xpath, $entry, $importer, $xml, $protocol);
2358 Logger::info("Import done for user " . $importer["importer_uid"] . " from contact " . $importer["id"]);
2363 * Returns the activity verb
2365 * @param array $item Item array
2367 * @return string activity verb
2369 private static function constructVerb(array $item)
2371 if ($item['verb']) {
2372 return $item['verb'];
2374 return Activity::POST;
2377 private static function tgroupCheck($uid, $item)
2381 // check that the message originated elsewhere and is a top-level post
2383 if ($item['wall'] || $item['origin'] || ($item['uri'] != $item['thr-parent'])) {
2387 $user = DBA::selectFirst('user', ['account-type', 'nickname'], ['uid' => $uid]);
2388 if (!DBA::isResult($user)) {
2392 $link = Strings::normaliseLink(DI::baseUrl() . '/profile/' . $user['nickname']);
2395 * Diaspora uses their own hardwired link URL in @-tags
2396 * instead of the one we supply with webfinger
2398 $dlink = Strings::normaliseLink(DI::baseUrl() . '/u/' . $user['nickname']);
2400 $cnt = preg_match_all('/[\@\!]\[url\=(.*?)\](.*?)\[\/url\]/ism', $item['body'], $matches, PREG_SET_ORDER);
2402 foreach ($matches as $mtch) {
2403 if (Strings::compareLink($link, $mtch[1]) || Strings::compareLink($dlink, $mtch[1])) {
2405 Logger::notice('mention found: ' . $mtch[2]);
2414 return ($user['account-type'] == User::ACCOUNT_TYPE_COMMUNITY);
2418 * This function returns true if $update has an edited timestamp newer
2419 * than $existing, i.e. $update contains new data which should override
2420 * what's already there. If there is no timestamp yet, the update is
2421 * assumed to be newer. If the update has no timestamp, the existing
2422 * item is assumed to be up-to-date. If the timestamps are equal it
2423 * assumes the update has been seen before and should be ignored.
2428 * @throws \Exception
2430 private static function isEditedTimestampNewer($existing, $update)
2432 if (empty($existing['edited'])) {
2435 if (empty($update['edited'])) {
2439 $existing_edited = DateTimeFormat::utc($existing['edited']);
2440 $update_edited = DateTimeFormat::utc($update['edited']);
2442 return (strcmp($existing_edited, $update_edited) < 0);
2446 * Checks if the given contact url does support DFRN
2448 * @param string $url profile url
2450 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2451 * @throws \ImagickException
2453 public static function isSupportedByContactUrl($url)
2455 $probe = Probe::uri($url, Protocol::DFRN);
2456 return $probe['network'] == Protocol::DFRN;