]> git.mxchange.org Git - friendica.git/blob - src/Protocol/DFRN.php
Improved event storing / improved performance when fetching events
[friendica.git] / src / Protocol / DFRN.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2010-2021, the Friendica project
4  *
5  * @license GNU AGPL version 3 or any later version
6  *
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.
11  *
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.
16  *
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/>.
19  *
20  */
21
22 namespace Friendica\Protocol;
23
24 use DOMDocument;
25 use DOMXPath;
26 use Friendica\Content\Text\BBCode;
27 use Friendica\Core\Logger;
28 use Friendica\Core\Protocol;
29 use Friendica\Database\DBA;
30 use Friendica\DI;
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;
52
53 /**
54  * This class contain functions to create and send DFRN XML files
55  */
56 class DFRN
57 {
58
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
62
63         /**
64          * Generates an array of contact and user for DFRN imports
65          *
66          * This array contains not only the receiver but also the sender of the message.
67          *
68          * @param integer $cid Contact id
69          * @param integer $uid User id
70          *
71          * @return array importer
72          * @throws \Exception
73          */
74         public static function getImporter($cid, $uid = 0)
75         {
76                 $condition = ['id' => $cid, 'blocked' => false, 'pending' => false];
77                 $contact = DBA::selectFirst('contact', [], $condition);
78                 if (!DBA::isResult($contact)) {
79                         return [];
80                 }
81
82                 $contact['cpubkey'] = $contact['pubkey'];
83                 $contact['cprvkey'] = $contact['prvkey'];
84                 $contact['senderName'] = $contact['name'];
85
86                 if ($uid != 0) {
87                         $condition = ['uid' => $uid, 'account_expired' => false, 'account_removed' => false];
88                         $user = DBA::selectFirst('user', [], $condition);
89                         if (!DBA::isResult($user)) {
90                                 return [];
91                         }
92
93                         $user['importer_uid'] = $user['uid'];
94                         $user['uprvkey'] = $user['prvkey'];
95                 } else {
96                         $user = ['importer_uid' => 0, 'uprvkey' => '', 'timezone' => 'UTC',
97                                 'nickname' => '', 'sprvkey' => '', 'spubkey' => '',
98                                 'page-flags' => 0, 'account-type' => 0, 'prvnets' => 0];
99                 }
100
101                 return array_merge($contact, $user);
102         }
103
104         /**
105          * Generates the atom entries for delivery.php
106          *
107          * This function is used whenever content is transmitted via DFRN.
108          *
109          * @param array $items Item elements
110          * @param array $owner Owner record
111          *
112          * @return string DFRN entries
113          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
114          * @throws \ImagickException
115          * @todo  Find proper type-hints
116          */
117         public static function entries($items, $owner)
118         {
119                 $doc = new DOMDocument('1.0', 'utf-8');
120                 $doc->formatOutput = true;
121
122                 $root = self::addHeader($doc, $owner, "dfrn:owner", "", false);
123
124                 if (! count($items)) {
125                         return trim($doc->saveXML());
126                 }
127
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;
133
134                         $entry = self::entry($doc, "text", $item, $owner, $item["entry:comment-allow"], $item["entry:cid"]);
135                         if (isset($entry)) {
136                                 $root->appendChild($entry);
137                         }
138                 }
139
140                 return trim($doc->saveXML());
141         }
142
143         /**
144          * Generate an atom entry for a given uri id and user
145          *
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.
149          *
150          * @return string DFRN feed entry
151          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
152          * @throws \ImagickException
153          */
154         public static function itemFeed(int $uri_id, int $uid, bool $conversation = false)
155         {
156                 if ($conversation) {
157                         $condition = ['parent-uri-id' => $uri_id];
158                 } else {
159                         $condition = ['uri-id' => $uri_id];
160                 }
161
162                 $condition['uid'] = $uid;
163
164                 $items = Post::selectToArray(Item::DELIVER_FIELDLIST, $condition);
165                 if (!DBA::isResult($items)) {
166                         return '';
167                 }
168
169                 $item = $items[0];
170
171                 if ($item['uid'] != 0) {
172                         $owner = User::getOwnerDataById($item['uid']);
173                         if (!$owner) {
174                                 return '';
175                         }
176                 } else {
177                         $owner = ['uid' => 0, 'nick' => 'feed-item'];
178                 }
179
180                 $doc = new DOMDocument('1.0', 'utf-8');
181                 $doc->formatOutput = true;
182                 $type = 'html';
183
184                 if ($conversation) {
185                         $root = $doc->createElementNS(ActivityNamespace::ATOM1, 'feed');
186                         $doc->appendChild($root);
187
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);
197
198                         //$root = self::addHeader($doc, $owner, "dfrn:owner", "", false);
199
200                         foreach ($items as $item) {
201                                 $entry = self::entry($doc, $type, $item, $owner, true, 0);
202                                 if (isset($entry)) {
203                                         $root->appendChild($entry);
204                                 }
205                         }
206                 } else {
207                         self::entry($doc, $type, $item, $owner, true, 0, true);
208                 }
209
210                 $atom = trim($doc->saveXML());
211                 return $atom;
212         }
213
214         /**
215          * Create XML text for DFRN mails
216          *
217          * @param array $mail  Mail record
218          * @param array $owner Owner record
219          *
220          * @return string DFRN mail
221          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
222          * @todo  Find proper type-hints
223          */
224         public static function mail(array $mail, array $owner)
225         {
226                 $doc = new DOMDocument('1.0', 'utf-8');
227                 $doc->formatOutput = true;
228
229                 $root = self::addHeader($doc, $owner, "dfrn:owner", "", false);
230
231                 $mailElement = $doc->createElement("dfrn:mail");
232                 $senderElement = $doc->createElement("dfrn:sender");
233
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']);
237
238                 $mailElement->appendChild($senderElement);
239
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']);
245
246                 $root->appendChild($mailElement);
247
248                 return trim($doc->saveXML());
249         }
250
251         /**
252          * Create XML text for DFRN friend suggestions
253          *
254          * @param array $item  suggestion elements
255          * @param array $owner Owner record
256          *
257          * @return string DFRN suggestions
258          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
259          * @todo  Find proper type-hints
260          */
261         public static function fsuggest($item, $owner)
262         {
263                 $doc = new DOMDocument('1.0', 'utf-8');
264                 $doc->formatOutput = true;
265
266                 $root = self::addHeader($doc, $owner, "dfrn:owner", "", false);
267
268                 $suggest = $doc->createElement("dfrn:suggest");
269
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']);
275
276                 $root->appendChild($suggest);
277
278                 return trim($doc->saveXML());
279         }
280
281         /**
282          * Create XML text for DFRN relocations
283          *
284          * @param array $owner Owner record
285          * @param int   $uid   User ID
286          *
287          * @return string DFRN relocations
288          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
289          * @todo  Find proper type-hints
290          */
291         public static function relocate($owner, $uid)
292         {
293
294                 /* get site pubkey. this could be a new installation with no site keys*/
295                 $pubkey = DI::config()->get('system', 'site_pubkey');
296                 if (! $pubkey) {
297                         $res = Crypto::newKeypair(1024);
298                         DI::config()->set('system', 'site_prvkey', $res['prvkey']);
299                         DI::config()->set('system', 'site_pubkey', $res['pubkey']);
300                 }
301
302                 $rp = q(
303                         "SELECT `resource-id` , `scale`, type FROM `photo`
304                                 WHERE `profile` = 1 AND `uid` = %d ORDER BY scale;",
305                         $uid
306                 );
307                 $photos = [];
308                 $ext = Images::supportedTypes();
309
310                 foreach ($rp as $p) {
311                         $photos[$p['scale']] = DI::baseUrl().'/photo/'.$p['resource-id'].'-'.$p['scale'].'.'.$ext[$p['type']];
312                 }
313
314
315                 $doc = new DOMDocument('1.0', 'utf-8');
316                 $doc->formatOutput = true;
317
318                 $root = self::addHeader($doc, $owner, "dfrn:owner", "", false);
319
320                 $relocate = $doc->createElement("dfrn:relocate");
321
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'));
334
335                 $root->appendChild($relocate);
336
337                 return trim($doc->saveXML());
338         }
339
340         /**
341          * Adds the header elements for the DFRN protocol
342          *
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?
348          *
349          * @return object XML root object
350          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
351          * @todo  Find proper type-hints
352          */
353         private static function addHeader(DOMDocument $doc, $owner, $authorelement, $alternatelink = "", $public = false)
354         {
355
356                 if ($alternatelink == "") {
357                         $alternatelink = $owner['url'];
358                 }
359
360                 $root = $doc->createElementNS(ActivityNamespace::ATOM1, 'feed');
361                 $doc->appendChild($root);
362
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);
372
373                 XML::addElement($doc, $root, "id", DI::baseUrl()."/profile/".$owner["nick"]);
374                 XML::addElement($doc, $root, "title", $owner["name"]);
375
376                 $attributes = ["uri" => "https://friendi.ca", "version" => FRIENDICA_VERSION."-".DB_UPDATE_VERSION];
377                 XML::addElement($doc, $root, "generator", FRIENDICA_PLATFORM, $attributes);
378
379                 $attributes = ["rel" => "license", "href" => "http://creativecommons.org/licenses/by/3.0/"];
380                 XML::addElement($doc, $root, "link", "", $attributes);
381
382                 $attributes = ["rel" => "alternate", "type" => "text/html", "href" => $alternatelink];
383                 XML::addElement($doc, $root, "link", "", $attributes);
384
385
386                 if ($public) {
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"]);
389
390                         $attributes = ["rel" => "salmon", "href" => DI::baseUrl()."/salmon/".$owner["nick"]];
391                         XML::addElement($doc, $root, "link", "", $attributes);
392
393                         $attributes = ["rel" => "http://salmon-protocol.org/ns/salmon-replies", "href" => DI::baseUrl()."/salmon/".$owner["nick"]];
394                         XML::addElement($doc, $root, "link", "", $attributes);
395
396                         $attributes = ["rel" => "http://salmon-protocol.org/ns/salmon-mention", "href" => DI::baseUrl()."/salmon/".$owner["nick"]];
397                         XML::addElement($doc, $root, "link", "", $attributes);
398                 }
399
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);
403                 }
404
405                 // The former element is replaced by this one
406                 XML::addElement($doc, $root, "dfrn:account_type", $owner["account-type"]);
407
408                 /// @todo We need a way to transmit the different page flags like "User::PAGE_FLAGS_PRVGROUP"
409
410                 XML::addElement($doc, $root, "updated", DateTimeFormat::utcNow(DateTimeFormat::ATOM));
411
412                 $author = self::addAuthor($doc, $owner, $authorelement, $public);
413                 $root->appendChild($author);
414
415                 return $root;
416         }
417
418         /**
419          * Adds the author element in the header for the DFRN protocol
420          *
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
425          *
426          * @return \DOMElement XML author object
427          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
428          * @todo  Find proper type-hints
429          */
430         private static function addAuthor(DOMDocument $doc, array $owner, $authorelement, $public)
431         {
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]);
434
435                 $author = $doc->createElement($authorelement);
436
437                 $namdate = DateTimeFormat::utc($owner['name-date'].'+00:00', DateTimeFormat::ATOM);
438                 $picdate = DateTimeFormat::utc($owner['avatar-date'].'+00:00', DateTimeFormat::ATOM);
439
440                 $attributes = [];
441
442                 if (!$public || !$hide) {
443                         $attributes = ["dfrn:updated" => $namdate];
444                 }
445
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);
449
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'])];
453
454                 if (!$public || !$hide) {
455                         $attributes["dfrn:updated"] = $picdate;
456                 }
457
458                 XML::addElement($doc, $author, "link", "", $attributes);
459
460                 $attributes["rel"] = "avatar";
461                 XML::addElement($doc, $author, "link", "", $attributes);
462
463                 if ($hide) {
464                         XML::addElement($doc, $author, "dfrn:hide", "true");
465                 }
466
467                 // The following fields will only be generated if the data isn't meant for a public feed
468                 if ($public) {
469                         return $author;
470                 }
471
472                 $birthday = feed_birthday($owner['uid'], $owner['timezone']);
473
474                 if ($birthday) {
475                         XML::addElement($doc, $author, "dfrn:birthday", $birthday);
476                 }
477
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);
485
486                         if (trim($profile["dob"]) > DBA::NULL_DATE) {
487                                 XML::addElement($doc, $author, "poco:birthday", "0000-".date("m-d", strtotime($profile["dob"])));
488                         }
489
490                         XML::addElement($doc, $author, "poco:note", $profile["about"]);
491                         XML::addElement($doc, $author, "poco:preferredUsername", $profile["nickname"]);
492
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);
497
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);
504                         }
505
506                         if (trim($profile["pub_keywords"]) != "") {
507                                 $keywords = explode(",", $profile["pub_keywords"]);
508
509                                 foreach ($keywords as $keyword) {
510                                         XML::addElement($doc, $author, "poco:tags", trim($keyword));
511                                 }
512                         }
513
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);
520                         }
521
522                         if (trim($profile["locality"].$profile["region"].$profile["country-name"]) != "") {
523                                 $element = $doc->createElement("poco:address");
524
525                                 XML::addElement($doc, $element, "poco:formatted", Profile::formatLocation($profile));
526
527                                 if (trim($profile["locality"]) != "") {
528                                         XML::addElement($doc, $element, "poco:locality", $profile["locality"]);
529                                 }
530
531                                 if (trim($profile["region"]) != "") {
532                                         XML::addElement($doc, $element, "poco:region", $profile["region"]);
533                                 }
534
535                                 if (trim($profile["country-name"]) != "") {
536                                         XML::addElement($doc, $element, "poco:country", $profile["country-name"]);
537                                 }
538
539                                 $author->appendChild($element);
540                         }
541                 }
542
543                 return $author;
544         }
545
546         /**
547          * Adds the author elements in the "entry" elements of the DFRN protocol
548          *
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
553          *
554          * @return \DOMElement XML author object
555          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
556          * @todo  Find proper type-hints
557          */
558         private static function addEntryAuthor(DOMDocument $doc, $element, $contact_url, $item)
559         {
560                 $author = $doc->createElement($element);
561
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"]);
567
568                         /// @Todo
569                         /// - Check real image type and image size
570                         /// - Check which of these boths elements we should use
571                         $attributes = [
572                                 "rel" => "photo",
573                                 "type" => "image/jpeg",
574                                 "media:width" => 80,
575                                 "media:height" => 80,
576                                 "href" => $contact["photo"]];
577                         XML::addElement($doc, $author, "link", "", $attributes);
578
579                         $attributes = [
580                                 "rel" => "avatar",
581                                 "type" => "image/jpeg",
582                                 "media:width" => 80,
583                                 "media:height" => 80,
584                                 "href" => $contact["photo"]];
585                         XML::addElement($doc, $author, "link", "", $attributes);
586                 }
587
588                 return $author;
589         }
590
591         /**
592          * Adds the activity elements
593          *
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
598          *
599          * @return \DOMElement XML activity object
600          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
601          * @todo  Find proper type-hints
602          */
603         private static function createActivity(DOMDocument $doc, $element, $activity, $uriid)
604         {
605                 if ($activity) {
606                         $entry = $doc->createElement($element);
607
608                         $r = XML::parseString($activity);
609                         if (!$r) {
610                                 return false;
611                         }
612
613                         if ($r->type) {
614                                 XML::addElement($doc, $entry, "activity:object-type", $r->type);
615                         }
616
617                         if ($r->id) {
618                                 XML::addElement($doc, $entry, "id", $r->id);
619                         }
620
621                         if ($r->title) {
622                                 XML::addElement($doc, $entry, "title", $r->title);
623                         }
624
625                         if ($r->link) {
626                                 if (substr($r->link, 0, 1) == '<') {
627                                         if (strstr($r->link, '&') && (! strstr($r->link, '&amp;'))) {
628                                                 $r->link = str_replace('&', '&amp;', $r->link);
629                                         }
630
631                                         $r->link = preg_replace('/\<link(.*?)\"\>/', '<link$1"/>', $r->link);
632
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) {
637                                                         $attributes = [];
638                                                         foreach ($link->attributes() as $parameter => $value) {
639                                                                 $attributes[$parameter] = $value;
640                                                         }
641                                                         XML::addElement($doc, $entry, "link", "", $attributes);
642                                                 }
643                                         }
644                                 } else {
645                                         $attributes = ["rel" => "alternate", "type" => "text/html", "href" => $r->link];
646                                         XML::addElement($doc, $entry, "link", "", $attributes);
647                                 }
648                         }
649                         if ($r->content) {
650                                 XML::addElement($doc, $entry, "content", BBCode::convertForUriId($uriid, $r->content, BBCode::EXTERNAL), ["type" => "html"]);
651                         }
652
653                         return $entry;
654                 }
655
656                 return false;
657         }
658
659         /**
660          * Adds the elements for attachments
661          *
662          * @param object $doc  XML document
663          * @param object $root XML root
664          * @param array  $item Item element
665          *
666          * @return void XML attachment object
667          * @todo  Find proper type-hints
668          */
669         private static function getAttachment($doc, $root, $item)
670         {
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']];
675
676                         if (!empty($attachment['size'])) {
677                                 $attributes['length'] = intval($attachment['size']);
678                         }
679                         if (!empty($attachment['description'])) {
680                                 $attributes['title'] = $attachment['description'];
681                         }
682
683                         XML::addElement($doc, $root, 'link', '', $attributes);
684                 }
685         }
686
687         /**
688          * Adds the "entry" elements for the DFRN protocol
689          *
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
697          *
698          * @return null|\DOMElement XML entry object
699          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
700          * @throws \ImagickException
701          * @todo  Find proper type-hints
702          */
703         private static function entry(DOMDocument $doc, $type, array $item, array $owner, $comment = false, $cid = 0, $single = false)
704         {
705                 $mentioned = [];
706
707                 if (!$item['parent']) {
708                         Logger::notice('Item without parent found.', ['type' => $type, 'item' => $item]);
709                         return null;
710                 }
711
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);
715                 }
716
717                 if (!$single) {
718                         $entry = $doc->createElement("entry");
719                 } else {
720                         $entry = $doc->createElementNS(ActivityNamespace::ATOM1, 'entry');
721                         $doc->appendChild($entry);
722
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);
732                 }
733
734                 $body = Post\Media::addAttachmentsToBody($item['uri-id'], $item['body'] ?? '');
735
736                 if ($item['private'] == Item::PRIVATE) {
737                         $body = Item::fixPrivatePhotos($body, $owner['uid'], $item, $cid);
738                 }
739
740                 // Remove the abstract element. It is only locally important.
741                 $body = BBCode::stripAbstract($body);
742
743                 $htmlbody = '';
744                 if ($type == 'html') {
745                         $htmlbody = $body;
746
747                         if ($item['title'] != "") {
748                                 $htmlbody = "[b]" . $item['title'] . "[/b]\n\n" . $htmlbody;
749                         }
750
751                         $htmlbody = BBCode::convertForUriId($item['uri-id'], $htmlbody, BBCode::ACTIVITYPUB);
752                 }
753
754                 $author = self::addEntryAuthor($doc, "author", $item["author-link"], $item);
755                 $entry->appendChild($author);
756
757                 $dfrnowner = self::addEntryAuthor($doc, "dfrn:owner", $item["owner-link"], $item);
758                 $entry->appendChild($dfrnowner);
759
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);
767                         }
768                 }
769
770                 // Add conversation data. This is used for OStatus
771                 $conversation_href = DI::baseUrl()."/display/".$item["parent-guid"];
772                 $conversation_uri = $conversation_href;
773
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'];
779                                 }
780                                 if ($conversation['conversation-href'] != '') {
781                                         $conversation_href = $conversation['conversation-href'];
782                                 }
783                         }
784                 }
785
786                 $attributes = [
787                                 "href" => $conversation_href,
788                                 "ref" => $conversation_uri];
789
790                 XML::addElement($doc, $entry, "ostatus:conversation", $conversation_uri, $attributes);
791
792                 XML::addElement($doc, $entry, "id", $item["uri"]);
793                 XML::addElement($doc, $entry, "title", $item["title"]);
794
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));
797
798                 // "dfrn:env" is used to read the content
799                 XML::addElement($doc, $entry, "dfrn:env", Strings::base64UrlEncode($body, true));
800
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]);
804
805                 // We save this value in "plink". Maybe we should read it from there as well?
806                 XML::addElement(
807                         $doc,
808                         $entry,
809                         "link",
810                         "",
811                         ["rel" => "alternate", "type" => "text/html",
812                                  "href" => DI::baseUrl() . "/display/" . $item["guid"]]
813                 );
814
815                 // "comment-allow" is some old fashioned stuff for old Friendica versions.
816                 // It is included in the rewritten code for completeness
817                 if ($comment) {
818                         XML::addElement($doc, $entry, "dfrn:comment-allow", 1);
819                 }
820
821                 if ($item['location']) {
822                         XML::addElement($doc, $entry, "dfrn:location", $item['location']);
823                 }
824
825                 if ($item['coord']) {
826                         XML::addElement($doc, $entry, "georss:point", $item['coord']);
827                 }
828
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);
833                 }
834
835                 if ($item['extid']) {
836                         XML::addElement($doc, $entry, "dfrn:extid", $item['extid']);
837                 }
838
839                 if ($item['post-type'] == Item::PT_PAGE) {
840                         XML::addElement($doc, $entry, "dfrn:bookmark", "true");
841                 }
842
843                 if ($item['app']) {
844                         XML::addElement($doc, $entry, "statusnet:notice_info", "", ["local_id" => $item['id'], "source" => $item['app']]);
845                 }
846
847                 XML::addElement($doc, $entry, "dfrn:diaspora_guid", $item["guid"]);
848
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);
854                 }
855
856                 XML::addElement($doc, $entry, "activity:verb", self::constructVerb($item));
857
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);
862                 } else {
863                         XML::addElement($doc, $entry, "activity:object-type", Activity\ObjectType::COMMENT);
864                 }
865
866                 $actobj = self::createActivity($doc, "activity:object", $item['object'], $item['uri-id']);
867                 if ($actobj) {
868                         $entry->appendChild($actobj);
869                 }
870
871                 $actarg = self::createActivity($doc, "activity:target", $item['target'], $item['uri-id']);
872                 if ($actarg) {
873                         $entry->appendChild($actarg);
874                 }
875
876                 $tags = Tag::getByURIId($item['uri-id']);
877
878                 if (count($tags)) {
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']]);
882                                 }
883                                 if ($tag['type'] != Tag::HASHTAG) {
884                                         $mentioned[$tag['url']] = $tag['url'];
885                                 }
886                         }
887                 }
888
889                 foreach ($mentioned as $mention) {
890                         $condition = ['uid' => $owner["uid"], 'nurl' => Strings::normaliseLink($mention)];
891                         $contact = DBA::selectFirst('contact', ['forum', 'prv'], $condition);
892
893                         if (DBA::isResult($contact) && ($contact["forum"] || $contact["prv"])) {
894                                 XML::addElement(
895                                         $doc,
896                                         $entry,
897                                         "link",
898                                         "",
899                                         ["rel" => "mentioned",
900                                                         "ostatus:object-type" => Activity\ObjectType::GROUP,
901                                                         "href" => $mention]
902                                 );
903                         } else {
904                                 XML::addElement(
905                                         $doc,
906                                         $entry,
907                                         "link",
908                                         "",
909                                         ["rel" => "mentioned",
910                                                         "ostatus:object-type" => Activity\ObjectType::PERSON,
911                                                         "href" => $mention]
912                                 );
913                         }
914                 }
915
916                 self::getAttachment($doc, $entry, $item);
917
918                 return $entry;
919         }
920
921         /**
922          * Transmits atom content to the contacts via the Diaspora transport layer
923          *
924          * @param array  $owner   Owner record
925          * @param array  $contact Contact record of the receiver
926          * @param string $atom    Content that will be transmitted
927          *
928          * @param bool   $public_batch
929          * @return int Deliver status. Negative values mean an error.
930          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
931          * @throws \ImagickException
932          */
933         public static function transmit($owner, $contact, $atom, $public_batch = false)
934         {
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'];
941                                 }
942
943                                 if (empty($contact['addr'])) {
944                                         Logger::log('Unable to find contact handle for ' . $contact['id'] . ' - ' . $contact['url']);
945                                         return -21;
946                                 }
947                         }
948
949                         $fcontact = FContact::getByURL($contact['addr']);
950                         if (empty($fcontact)) {
951                                 Logger::log('Unable to find contact details for ' . $contact['id'] . ' - ' . $contact['addr']);
952                                 return -22;
953                         }
954                         $pubkey = $fcontact['pubkey'];
955                 } else {
956                         $pubkey = '';
957                 }
958
959                 $envelope = Diaspora::buildMessage($atom, $owner, $contact, $owner['uprvkey'], $pubkey, $public_batch);
960
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);
968                 }
969
970                 $dest_url = ($public_batch ? $contact["batch"] : $contact["notify"]);
971
972                 if (empty($dest_url)) {
973                         Logger::info('Empty destination', ['public' => $public_batch, 'contact' => $contact]);
974                         return -24;
975                 }
976
977                 $content_type = ($public_batch ? "application/magic-envelope+xml" : "application/json");
978
979                 $postResult = DI::httpRequest()->post($dest_url, $envelope, ["Content-Type: " . $content_type]);
980                 $xml = $postResult->getBody();
981
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
986                 }
987
988                 if (($curl_stat == 503) && (stristr($postResult->getHeader(), 'retry-after'))) {
989                         return -10;
990                 }
991
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);
995                         return 3;
996                 }
997
998                 $res = XML::parseString($xml);
999
1000                 if (empty($res->status)) {
1001                         return -23;
1002                 }
1003
1004                 if (!empty($res->message)) {
1005                         Logger::log('Transmit to ' . $dest_url . ' returned status '.$res->status.' - '.$res->message, Logger::DEBUG);
1006                 }
1007
1008                 return intval($res->status);
1009         }
1010
1011         /**
1012          * Fetch the author data from head or entry items
1013          *
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
1020          *
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
1025          */
1026         private static function fetchauthor(\DOMXPath $xpath, \DOMNode $context, $importer, $element, $onlyfetch, $xml = "")
1027         {
1028                 $author = [];
1029                 $author["name"] = XML::getFirstNodeValue($xpath, $element."/atom:name/text()", $context);
1030                 $author["link"] = XML::getFirstNodeValue($xpath, $element."/atom:uri/text()", $context);
1031
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];
1036
1037                 if ($importer['account-type'] != User::ACCOUNT_TYPE_COMMUNITY) {
1038                         $condition = DBA::mergeConditions($condition, ['rel' => [Contact::SHARING, Contact::FRIEND]]);
1039                 }
1040
1041                 $contact_old = DBA::selectFirst('contact', $fields, $condition);
1042
1043                 if (DBA::isResult($contact_old)) {
1044                         $author["contact-id"] = $contact_old["id"];
1045                         $author["network"] = $contact_old["network"];
1046                 } else {
1047                         Logger::info('Contact not found', ['condition' => $condition]);
1048
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"];
1053                         $onlyfetch = true;
1054                 }
1055
1056                 // Until now we aren't serving different sizes - but maybe later
1057                 $avatarlist = [];
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) {
1061                         $href = "";
1062                         $width = 0;
1063                         foreach ($avatar->attributes as $attributes) {
1064                                 /// @TODO Rewrite these similar if() to one switch
1065                                 if ($attributes->name == "href") {
1066                                         $href = $attributes->textContent;
1067                                 }
1068                                 if ($attributes->name == "width") {
1069                                         $width = $attributes->textContent;
1070                                 }
1071                                 if ($attributes->name == "updated") {
1072                                         $author["avatar-date"] = $attributes->textContent;
1073                                 }
1074                         }
1075                         if (($width > 0) && ($href != "")) {
1076                                 $avatarlist[$width] = $href;
1077                         }
1078                 }
1079
1080                 if (count($avatarlist) > 0) {
1081                         krsort($avatarlist);
1082                         $author["avatar"] = current($avatarlist);
1083                 }
1084
1085                 if (empty($author['avatar']) && !empty($author['link'])) {
1086                         $cid = Contact::getIdForURL($author['link'], 0);
1087                         if (!empty($cid)) {
1088                                 $contact = DBA::selectFirst('contact', ['avatar'], ['id' => $cid]);
1089                                 if (DBA::isResult($contact)) {
1090                                         $author['avatar'] = $contact['avatar'];
1091                                 }
1092                         }
1093                 }
1094
1095                 if (empty($author['avatar'])) {
1096                         Logger::log('Empty author: ' . $xml);
1097                         $author['avatar'] = '';
1098                 }
1099
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);
1102
1103                         $poco = ["url" => $contact_old["url"], "network" => $contact_old["network"]];
1104
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;
1110                                 }
1111                         }
1112
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;
1117                                 }
1118                         }
1119
1120                         // Update contact data
1121                         $value = XML::getFirstNodeValue($xpath, $element . "/dfrn:handle/text()", $context);
1122                         if ($value != "") {
1123                                 $poco["addr"] = $value;
1124                         }
1125
1126                         $value = XML::getFirstNodeValue($xpath, $element . "/poco:displayName/text()", $context);
1127                         if ($value != "") {
1128                                 $poco["name"] = $value;
1129                         }
1130
1131                         $value = XML::getFirstNodeValue($xpath, $element . "/poco:preferredUsername/text()", $context);
1132                         if ($value != "") {
1133                                 $poco["nick"] = $value;
1134                         }
1135
1136                         $value = XML::getFirstNodeValue($xpath, $element . "/poco:note/text()", $context);
1137                         if ($value != "") {
1138                                 $poco["about"] = $value;
1139                         }
1140
1141                         $value = XML::getFirstNodeValue($xpath, $element . "/poco:address/poco:formatted/text()", $context);
1142                         if ($value != "") {
1143                                 $poco["location"] = $value;
1144                         }
1145
1146                         /// @todo Only search for elements with "poco:type" = "xmpp"
1147                         $value = XML::getFirstNodeValue($xpath, $element . "/poco:ims/poco:value/text()", $context);
1148                         if ($value != "") {
1149                                 $poco["xmpp"] = $value;
1150                         }
1151
1152                         /// @todo Add support for the following fields that we don't support by now in the contact table:
1153                         /// - poco:utcOffset
1154                         /// - poco:urls
1155                         /// - poco:locality
1156                         /// - poco:region
1157                         /// - poco:country
1158
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");
1161
1162                         Logger::log("Hidden status for contact " . $contact_old["url"] . ": " . $hide, Logger::DEBUG);
1163
1164                         // If the contact isn't searchable then set the contact to "hidden".
1165                         // Problem: This can be manually overridden by the user.
1166                         if ($hide) {
1167                                 $contact_old["hidden"] = true;
1168                         }
1169
1170                         // Save the keywords into the contact table
1171                         $tags = [];
1172                         $tagelements = $xpath->evaluate($element . "/poco:tags/text()", $context);
1173                         foreach ($tagelements as $tag) {
1174                                 $tags[$tag->nodeValue] = $tag->nodeValue;
1175                         }
1176
1177                         if (count($tags)) {
1178                                 $poco["keywords"] = implode(", ", $tags);
1179                         }
1180
1181                         // "dfrn:birthday" contains the birthday converted to UTC
1182                         $birthday = XML::getFirstNodeValue($xpath, $element . "/dfrn:birthday/text()", $context);
1183                         try {
1184                                 $birthday_date = new \DateTime($birthday);
1185                                 if ($birthday_date > new \DateTime()) {
1186                                         $poco["bdyear"] = $birthday_date->format("Y");
1187                                 }
1188                         } catch (\Exception $e) {
1189                                 // Invalid birthday
1190                         }
1191
1192                         // "poco:birthday" is the birthday in the format "yyyy-mm-dd"
1193                         $value = XML::getFirstNodeValue($xpath, $element . "/poco:birthday/text()", $context);
1194
1195                         if (!in_array($value, ["", "0000-00-00", DBA::NULL_DATE])) {
1196                                 $bdyear = date("Y");
1197                                 $value = str_replace(["0000", "0001"], $bdyear, $value);
1198
1199                                 if (strtotime($value) < time()) {
1200                                         $value = str_replace($bdyear, $bdyear + 1, $value);
1201                                 }
1202
1203                                 $poco["bd"] = $value;
1204                         }
1205
1206                         $contact = array_merge($contact_old, $poco);
1207
1208                         if ($contact_old["bdyear"] != $contact["bdyear"]) {
1209                                 Event::createBirthday($contact, $birthday);
1210                         }
1211
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'])];
1217
1218                         DBA::update('contact', $fields, ['id' => $contact['id'], 'network' => $contact['network']], $contact_old);
1219
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);
1224
1225                         Contact::updateAvatar($contact['id'], $author['avatar']);
1226
1227                         $pcid = Contact::getIdForURL($contact_old['url']);
1228                         if (!empty($pcid)) {
1229                                 Contact::updateAvatar($pcid, $author['avatar']);
1230                         }
1231                 }
1232
1233                 return $author;
1234         }
1235
1236         /**
1237          * Transforms activity objects into an XML string
1238          *
1239          * @param object $xpath    XPath object
1240          * @param object $activity Activity object
1241          * @param string $element  element name
1242          *
1243          * @return string XML string
1244          * @todo Find good type-hints for all parameter
1245          */
1246         private static function transformActivity($xpath, $activity, $element)
1247         {
1248                 if (!is_object($activity)) {
1249                         return "";
1250                 }
1251
1252                 $obj_doc = new DOMDocument("1.0", "utf-8");
1253                 $obj_doc->formatOutput = true;
1254
1255                 $obj_element = $obj_doc->createElementNS( ActivityNamespace::ATOM1, $element);
1256
1257                 $activity_type = $xpath->query("activity:object-type/text()", $activity)->item(0)->nodeValue;
1258                 XML::addElement($obj_doc, $obj_element, "type", $activity_type);
1259
1260                 $id = $xpath->query("atom:id", $activity)->item(0);
1261                 if (is_object($id)) {
1262                         $obj_element->appendChild($obj_doc->importNode($id, true));
1263                 }
1264
1265                 $title = $xpath->query("atom:title", $activity)->item(0);
1266                 if (is_object($title)) {
1267                         $obj_element->appendChild($obj_doc->importNode($title, true));
1268                 }
1269
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));
1274                         }
1275                 }
1276
1277                 $content = $xpath->query("atom:content", $activity)->item(0);
1278                 if (is_object($content)) {
1279                         $obj_element->appendChild($obj_doc->importNode($content, true));
1280                 }
1281
1282                 $obj_doc->appendChild($obj_element);
1283
1284                 $objxml = $obj_doc->saveXML($obj_element);
1285
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);
1288                 return($objxml);
1289         }
1290
1291         /**
1292          * Processes the mail elements
1293          *
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
1297          * @return void
1298          * @throws \Exception
1299          * @todo  Find good type-hints for all parameter
1300          */
1301         private static function processMail($xpath, $mail, $importer)
1302         {
1303                 Logger::log("Processing mails");
1304
1305                 $msg = [];
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);
1316
1317                 Mail::insert($msg);
1318         }
1319
1320         /**
1321          * Processes the suggestion elements
1322          *
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
1326          * @return boolean
1327          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1328          * @todo  Find good type-hints for all parameter
1329          */
1330         private static function processSuggestion($xpath, $suggestion, $importer)
1331         {
1332                 Logger::notice('Processing suggestions');
1333
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);
1337
1338                 return FContact::addSuggestion($importer['importer_uid'], $cid, $importer['id'], $note);
1339         }
1340
1341         /**
1342          * Processes the relocation elements
1343          *
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
1347          * @return boolean
1348          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1349          * @throws \ImagickException
1350          * @todo  Find good type-hints for all parameter
1351          */
1352         private static function processRelocation($xpath, $relocation, $importer)
1353         {
1354                 Logger::log("Processing relocations");
1355
1356                 /// @TODO Rewrite this to one statement
1357                 $relocate = [];
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;
1372
1373                 if (($relocate["avatar"] == "") && ($relocate["photo"] != "")) {
1374                         $relocate["avatar"] = $relocate["photo"];
1375                 }
1376
1377                 if ($relocate["addr"] == "") {
1378                         $relocate["addr"] = preg_replace("=(https?://)(.*)/profile/(.*)=ism", "$3@$2", $relocate["url"]);
1379                 }
1380
1381                 // update contact
1382                 $r = q(
1383                         "SELECT `photo`, `url` FROM `contact` WHERE `id` = %d AND `uid` = %d",
1384                         intval($importer["id"]),
1385                         intval($importer["importer_uid"])
1386                 );
1387
1388                 if (!DBA::isResult($r)) {
1389                         Logger::log("Query failed to execute, no result returned in " . __FUNCTION__);
1390                         return false;
1391                 }
1392
1393                 $old = $r[0];
1394
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"])];
1402
1403                 DBA::update('contact', $fields, $condition);
1404
1405                 Contact::updateAvatar($importer["id"], $relocate["avatar"], true);
1406
1407                 Logger::log('Contacts are updated.');
1408
1409                 /// @TODO
1410                 /// merge with current record, current contents have priority
1411                 /// update record, set url-updated
1412                 /// update profile photos
1413                 /// schedule a scan?
1414                 return true;
1415         }
1416
1417         /**
1418          * Updates an item
1419          *
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?
1424          * @return mixed
1425          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1426          * @todo  set proper type-hints (array?)
1427          */
1428         private static function updateContent($current, $item, $importer, $entrytype)
1429         {
1430                 $changed = false;
1431
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"]) {
1435                                 return false;
1436                         }
1437
1438                         $fields = ['title' => $item['title'] ?? '', 'body' => $item['body'] ?? '',
1439                                         'changed' => DateTimeFormat::utcNow(),
1440                                         'edited' => DateTimeFormat::utc($item["edited"])];
1441
1442                         $condition = ["`uri` = ? AND `uid` IN (0, ?)", $item["uri"], $importer["importer_uid"]];
1443                         Item::update($fields, $condition);
1444
1445                         $changed = true;
1446                 }
1447                 return $changed;
1448         }
1449
1450         /**
1451          * Detects the entry type of the item
1452          *
1453          * @param array $importer Record of the importer user mixed with contact of the content
1454          * @param array $item     the new item record
1455          *
1456          * @return int Is it a toplevel entry, a comment or a relayed comment?
1457          * @throws \Exception
1458          * @todo  set proper type-hints (array?)
1459          */
1460         private static function getEntryType($importer, $item)
1461         {
1462                 if ($item["thr-parent"] != $item["uri"]) {
1463                         $community = false;
1464
1465                         if ($importer["page-flags"] == User::PAGE_FLAGS_COMMUNITY || $importer["page-flags"] == User::PAGE_FLAGS_PRVGROUP) {
1466                                 $sql_extra = "";
1467                                 $community = true;
1468                                 Logger::log("possible community action");
1469                         } else {
1470                                 $sql_extra = " AND `self` AND `wall`";
1471                         }
1472
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"]]);
1477
1478                         $is_a_remote_action = DBA::isResult($parent);
1479
1480                         /*
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.
1485                          */
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");
1489                         }
1490
1491                         if ($is_a_remote_action) {
1492                                 return DFRN::REPLY_RC;
1493                         } else {
1494                                 return DFRN::REPLY;
1495                         }
1496                 } else {
1497                         return DFRN::TOP_LEVEL;
1498                 }
1499         }
1500
1501         /**
1502          * Send a "poke"
1503          *
1504          * @param array $item      The new item record
1505          * @param array $importer  Record of the importer user mixed with contact of the content
1506          * @return void
1507          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1508          * @todo  set proper type-hints (array?)
1509          */
1510         private static function doPoke(array $item, array $importer)
1511         {
1512                 $verb = urldecode(substr($item["verb"], strpos($item["verb"], "#")+1));
1513                 if (!$verb) {
1514                         return;
1515                 }
1516                 $xo = XML::parseString($item["object"]);
1517
1518                 if (($xo->type == Activity\ObjectType::PERSON) && ($xo->id)) {
1519                         // somebody was poked/prodded. Was it me?
1520                         $Blink = '';
1521                         foreach ($xo->link as $l) {
1522                                 $atts = $l->attributes();
1523                                 switch ($atts["rel"]) {
1524                                         case "alternate":
1525                                                 $Blink = $atts["href"];
1526                                                 break;
1527                                         default:
1528                                                 break;
1529                                 }
1530                         }
1531
1532                         if ($Blink && Strings::compareLink($Blink, DI::baseUrl() . "/profile/" . $importer["nickname"])) {
1533                                 $author = DBA::selectFirst('contact', ['id', 'name', 'thumb', 'url'], ['id' => $item['author-id']]);
1534
1535                                 $parent = Post::selectFirst(['id'], ['uri' => $item['thr-parent'], 'uid' => $importer["importer_uid"]]);
1536                                 $item['parent'] = $parent['id'];
1537
1538                                 // send a notification
1539                                 notification(
1540                                         [
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"],
1547                                         "item"     => $item,
1548                                         "link"     => DI::baseUrl() . "/display/" . urlencode($item['guid']),
1549                                         ]
1550                                 );
1551                         }
1552                 }
1553         }
1554
1555         /**
1556          * Processes several actions, depending on the verb
1557          *
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"?
1562          *
1563          * @return bool Should the processing of the entries be continued?
1564          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1565          * @todo  set proper type-hints (array?)
1566          */
1567         private static function processVerbs($entrytype, $importer, &$item, &$is_like)
1568         {
1569                 Logger::log("Process verb ".$item["verb"]." and object-type ".$item["object-type"]." for entrytype ".$entrytype, Logger::DEBUG);
1570
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']]);
1575
1576                         $activity = DI::activity();
1577
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);
1583                                 return false;
1584                         }
1585                         if ($activity->match($item["verb"], Activity::UNFOLLOW)) {
1586                                 Logger::log("Lost follower");
1587                                 Contact::removeFollower($importer, $contact, $item);
1588                                 return false;
1589                         }
1590                         if ($activity->match($item["verb"], Activity::REQ_FRIEND)) {
1591                                 Logger::log("New friend request");
1592                                 Contact::addRelationship($importer, $contact, $item, true);
1593                                 return false;
1594                         }
1595                         if ($activity->match($item["verb"], Activity::UNFRIEND)) {
1596                                 Logger::log("Lost sharer");
1597                                 Contact::removeSharer($importer, $contact, $item);
1598                                 return false;
1599                         }
1600                 } else {
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)
1607                         ) {
1608                                 $is_like = true;
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)) {
1615                                         return false;
1616                                 }
1617
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)) {
1621                                         return false;
1622                                 }
1623
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"];
1629                         } else {
1630                                 $is_like = false;
1631                         }
1632
1633                         if (($item["verb"] == Activity::TAG) && ($item["object-type"] == Activity\ObjectType::TAGTERM)) {
1634                                 $xo = XML::parseString($item["object"]);
1635                                 $xt = XML::parseString($item["target"]);
1636
1637                                 if ($xt->type == Activity\ObjectType::NOTE) {
1638                                         $item_tag = Post::selectFirst(['id', 'uri-id'], ['uri' => $xt->id, 'uid' => $importer["importer_uid"]]);
1639
1640                                         if (!DBA::isResult($item_tag)) {
1641                                                 Logger::log("Query failed to execute, no result returned in " . __FUNCTION__);
1642                                                 return false;
1643                                         }
1644
1645                                         // extract tag, if not duplicate, add to parent item
1646                                         if ($xo->content) {
1647                                                 Tag::store($item_tag['uri-id'], Tag::HASHTAG, $xo->content);
1648                                         }
1649                                 }
1650                         }
1651                 }
1652                 return true;
1653         }
1654
1655         /**
1656          * Processes the link elements
1657          *
1658          * @param object $links link elements
1659          * @param array  $item  the item record
1660          * @return void
1661          * @todo set proper type-hints
1662          */
1663         private static function parseLinks($links, &$item)
1664         {
1665                 $rel = "";
1666                 $href = "";
1667                 $type = null;
1668                 $length = null;
1669                 $title = null;
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;
1678                                 }
1679                         }
1680                         if (($rel != "") && ($href != "")) {
1681                                 switch ($rel) {
1682                                         case "alternate":
1683                                                 $item["plink"] = $href;
1684                                                 break;
1685                                         case "enclosure":
1686                                                 Post\Media::insert(['uri-id' => $item['uri-id'], 'type' => Post\Media::DOCUMENT,
1687                                                         'url' => $href, 'mimetype' => $type, 'size' => $length, 'description' => $title]);
1688                                                 break;
1689                                 }
1690                         }
1691                 }
1692         }
1693
1694         /**
1695          * Checks if an incoming message is wanted
1696          *
1697          * @param array $item
1698          * @return boolean Is the message wanted?
1699          */
1700         private static function isSolicitedMessage(array $item)
1701         {
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"]]);
1705                         return true;
1706                 }
1707
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);
1711         }
1712
1713         /**
1714          * Processes the entry elements which contain the items and comments
1715          *
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
1721          * @return void
1722          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1723          * @throws \ImagickException
1724          * @todo  Add type-hints
1725          */
1726         private static function processEntry($header, $xpath, $entry, $importer, $xml, $protocol)
1727         {
1728                 Logger::log("Processing entries");
1729
1730                 $item = $header;
1731
1732                 $item["protocol"] = $protocol;
1733
1734                 $item["source"] = $xml;
1735
1736                 // Get the uri
1737                 $item["uri"] = XML::getFirstNodeValue($xpath, "atom:id/text()", $entry);
1738
1739                 $item["edited"] = XML::getFirstNodeValue($xpath, "atom:updated/text()", $entry);
1740
1741                 $current = Post::selectFirst(['id', 'uid', 'edited', 'body'],
1742                         ['uri' => $item["uri"], 'uid' => $importer["importer_uid"]]
1743                 );
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);
1747                         return;
1748                 }
1749
1750                 // Fetch the owner
1751                 $owner = self::fetchauthor($xpath, $entry, $importer, "dfrn:owner", true, $xml);
1752
1753                 $owner_unknown = (isset($owner["contact-unknown"]) && $owner["contact-unknown"]);
1754
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);
1759
1760                 // fetch the author
1761                 $author = self::fetchauthor($xpath, $entry, $importer, "atom:author", true, $xml);
1762
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);
1767
1768                 $item["title"] = XML::getFirstNodeValue($xpath, "atom:title/text()", $entry);
1769
1770                 if (!empty($item["title"])) {
1771                         $item["post-type"] = Item::PT_ARTICLE;
1772                 } else {
1773                         $item["post-type"] = Item::PT_NOTE;
1774                 }
1775
1776                 $item["created"] = XML::getFirstNodeValue($xpath, "atom:published/text()", $entry);
1777
1778                 $item["body"] = XML::getFirstNodeValue($xpath, "dfrn:env/text()", $entry);
1779                 $item["body"] = str_replace([' ',"\t","\r","\n"], ['','','',''], $item["body"]);
1780
1781                 $item["body"] = Strings::base64UrlDecode($item["body"]);
1782
1783                 $item["body"] = BBCode::limitBodySize($item["body"]);
1784
1785                 /// @todo We should check for a repeated post and if we know the repeated author.
1786
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;
1789
1790                 $item["location"] = XML::getFirstNodeValue($xpath, "dfrn:location/text()", $entry);
1791
1792                 $item["coord"] = XML::getFirstNodeValue($xpath, "georss:point", $entry);
1793
1794                 $item["private"] = XML::getFirstNodeValue($xpath, "dfrn:private/text()", $entry);
1795
1796                 $unlisted = XML::getFirstNodeValue($xpath, "dfrn:unlisted/text()", $entry);
1797                 if (!empty($unlisted) && ($item['private'] != Item::PRIVATE)) {
1798                         $item['private'] = Item::UNLISTED;
1799                 }
1800
1801                 $item["extid"] = XML::getFirstNodeValue($xpath, "dfrn:extid/text()", $entry);
1802
1803                 if (XML::getFirstNodeValue($xpath, "dfrn:bookmark/text()", $entry) == "true") {
1804                         $item["post-type"] = Item::PT_PAGE;
1805                 }
1806
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);
1812                                 }
1813                         }
1814                 }
1815
1816                 $item["guid"] = XML::getFirstNodeValue($xpath, "dfrn:diaspora_guid/text()", $entry);
1817
1818                 $item['uri-id'] = ItemURI::insert(['uri' => $item['uri'], 'guid' => $item['guid']]);
1819
1820                 $item["body"] = Item::improveSharedDataInBody($item);
1821
1822                 Tag::storeFromBody($item['uri-id'], $item["body"]);
1823
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;
1831                         }
1832                 }
1833
1834                 $item["verb"] = XML::getFirstNodeValue($xpath, "activity:verb/text()", $entry);
1835
1836                 if (XML::getFirstNodeValue($xpath, "activity:object-type/text()", $entry) != "") {
1837                         $item["object-type"] = XML::getFirstNodeValue($xpath, "activity:object-type/text()", $entry);
1838                 }
1839
1840                 $object = $xpath->query("activity:object", $entry)->item(0);
1841                 $item["object"] = self::transformActivity($xpath, $object, "object");
1842
1843                 if (trim($item["object"]) != "") {
1844                         $r = XML::parseString($item["object"]);
1845                         if (isset($r->type)) {
1846                                 $item["object-type"] = $r->type;
1847                         }
1848                 }
1849
1850                 $target = $xpath->query("activity:target", $entry)->item(0);
1851                 $item["target"] = self::transformActivity($xpath, $target, "target");
1852
1853                 $categories = $xpath->query("atom:category", $entry);
1854                 if ($categories) {
1855                         foreach ($categories as $category) {
1856                                 $term = "";
1857                                 $scheme = "";
1858                                 foreach ($category->attributes as $attributes) {
1859                                         if ($attributes->name == "term") {
1860                                                 $term = $attributes->textContent;
1861                                         }
1862
1863                                         if ($attributes->name == "scheme") {
1864                                                 $scheme = $attributes->textContent;
1865                                         }
1866                                 }
1867
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);
1874                                         }
1875                                 }
1876                         }
1877                 }
1878
1879                 $links = $xpath->query("atom:link", $entry);
1880                 if ($links) {
1881                         self::parseLinks($links, $item);
1882                 }
1883
1884                 $item['conversation-uri'] = XML::getFirstNodeValue($xpath, 'ostatus:conversation/text()', $entry);
1885
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;
1891                                 }
1892                                 if ($attributes->name == "href") {
1893                                         $item['conversation-href'] = $attributes->textContent;
1894                                 }
1895                         }
1896                 }
1897
1898                 // Is it a reply or a top level posting?
1899                 $item['thr-parent'] = $item['uri'];
1900
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;
1906                                 }
1907                         }
1908                 }
1909
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']]);
1914                                 return 403;
1915                         }
1916                 }
1917
1918                 // Get the type of the item (Top level post, reply or remote reply)
1919                 $entrytype = self::getEntryType($importer, $item);
1920
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;
1925                         }
1926
1927                         if ($item["contact-id"] != $owner["contact-id"]) {
1928                                 $item["contact-id"] = $owner["contact-id"];
1929                         }
1930
1931                         if (($item["network"] != $owner["network"]) && ($owner["network"] != "")) {
1932                                 $item["network"] = $owner["network"];
1933                         }
1934
1935                         if ($item["contact-id"] != $author["contact-id"]) {
1936                                 $item["contact-id"] = $author["contact-id"];
1937                         }
1938
1939                         if (($item["network"] != $author["network"]) && ($author["network"] != "")) {
1940                                 $item["network"] = $author["network"];
1941                         }
1942                 }
1943
1944                 // Ensure to have the correct share data
1945                 $item = Item::addShareDataFromOriginal($item);
1946
1947                 if ($entrytype == DFRN::REPLY_RC) {
1948                         $item["wall"] = 1;
1949                 } elseif ($entrytype == DFRN::TOP_LEVEL) {
1950                         if (!isset($item["object-type"])) {
1951                                 $item["object-type"] = Activity\ObjectType::NOTE;
1952                         }
1953
1954                         // Is it an event?
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"];
1971
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"];
1976                                         }
1977
1978                                         $event_id = Event::store($ev);
1979                                         Logger::info('Event was stored', ['id' => $event_id]);
1980
1981                                         $item = Event::getItemArrayForId($event_id, $item);
1982                                 }
1983                         }
1984                 }
1985
1986                 if (!self::processVerbs($entrytype, $importer, $item, $is_like)) {
1987                         Logger::log("Exiting because 'processVerbs' told us so", Logger::DEBUG);
1988                         return;
1989                 }
1990
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);
1994                         return;
1995                 }
1996
1997
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);
2002                         } else {
2003                                 Logger::log("Item " . $item["uri"] . " already existed.", Logger::DEBUG);
2004                         }
2005                         return;
2006                 }
2007
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;
2012                         }
2013
2014                         $posted_id = Item::insert($item);
2015                         if ($posted_id) {
2016                                 Logger::log("Reply from contact ".$item["contact-id"]." was stored with id ".$posted_id, Logger::DEBUG);
2017
2018                                 if ($item['uid'] == 0) {
2019                                         Item::distribute($posted_id);
2020                                 }
2021
2022                                 return true;
2023                         }
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);
2027                                 return;
2028                         }
2029                         if (!Strings::compareLink($item["owner-link"], $importer["url"])) {
2030                                 /*
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.
2035                                  */
2036                                 Logger::log('Correcting item owner.', Logger::DEBUG);
2037                                 $item["owner-link"] = $importer["url"];
2038                                 $item["owner-id"] = Contact::getIdForURL($importer["url"], 0);
2039                         }
2040
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);
2043                                 return;
2044                         }
2045
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);
2049
2050                         $posted_id = Item::insert($item, $notify);
2051
2052                         if ($notify) {
2053                                 $posted_id = $notify;
2054                         }
2055
2056                         Logger::log("Item was stored with id ".$posted_id, Logger::DEBUG);
2057
2058                         if ($item['uid'] == 0) {
2059                                 Item::distribute($posted_id);
2060                         }
2061
2062                         if (stristr($item["verb"], Activity::POKE)) {
2063                                 $item['id'] = $posted_id;
2064                                 self::doPoke($item, $importer);
2065                         }
2066                 }
2067         }
2068
2069         /**
2070          * Deletes items
2071          *
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
2075          * @return void
2076          * @throws \Exception
2077          * @todo  set proper type-hints
2078          */
2079         private static function processDeletion($xpath, $deletion, $importer)
2080         {
2081                 Logger::log("Processing deletions");
2082                 $uri = null;
2083
2084                 foreach ($deletion->attributes as $attributes) {
2085                         if ($attributes->name == "ref") {
2086                                 $uri = $attributes->textContent;
2087                         }
2088                 }
2089
2090                 if (!$uri || !$importer["id"]) {
2091                         return false;
2092                 }
2093
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);
2098                         return;
2099                 }
2100
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"]]);
2103                         return;
2104                 }
2105
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);
2109                         return;
2110                 }
2111
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);
2117                                 return;
2118                         }
2119                 }
2120
2121                 if ($item["deleted"]) {
2122                         return;
2123                 }
2124
2125                 Logger::log('deleting item '.$item['id'].' uri='.$uri, Logger::DEBUG);
2126
2127                 Item::markForDeletion(['id' => $item['id']]);
2128         }
2129
2130         /**
2131          * Imports a DFRN message
2132          *
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
2141          */
2142         public static function import($xml, $importer, $protocol, $direction)
2143         {
2144                 if ($xml == "") {
2145                         return 400;
2146                 }
2147
2148                 $doc = new DOMDocument();
2149                 @$doc->loadXML($xml);
2150
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);
2162
2163                 $header = [];
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;
2170
2171                 if ($direction === Conversation::RELAY) {
2172                         $header['post-reason'] = Item::PR_RELAY;
2173                 }
2174
2175                 // Update the contact table if the data has changed
2176
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);
2180                 }
2181
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);
2185                 }
2186
2187                 Logger::log("Import DFRN message for user " . $importer["importer_uid"] . " from contact " . $importer["id"], Logger::DEBUG);
2188
2189                 if (!empty($importer['gsid']) && ($protocol == Conversation::PARCEL_DIASPORA_DFRN)) {
2190                         GServer::setProtocol($importer['gsid'], Post\DeliveryData::DFRN);
2191                 }
2192
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()"));
2195
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
2199
2200                         $accounttype = intval(XML::getFirstNodeValue($xpath, "/atom:feed/dfrn:account_type/text()"));
2201
2202                         if ($accounttype != $importer["contact-type"]) {
2203                                 DBA::update('contact', ['contact-type' => $accounttype], ['id' => $importer['id']]);
2204
2205                                 // Updating the public contact as well
2206                                 DBA::update('contact', ['contact-type' => $accounttype], ['uid' => 0, 'nurl' => $importer['nurl']]);
2207                         }
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);
2213
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);
2217                         } else {
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);
2221
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);
2225                         }
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);
2229
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);
2233                 }
2234
2235
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);
2240                 }
2241
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);
2246                         }
2247
2248                         $suggestions = $xpath->query("/atom:feed/dfrn:suggest");
2249                         foreach ($suggestions as $suggestion) {
2250                                 self::processSuggestion($xpath, $suggestion, $importer);
2251                         }
2252                 }
2253
2254                 $deletions = $xpath->query("/atom:feed/at:deleted-entry");
2255                 if (!empty($deletions)) {
2256                         foreach ($deletions as $deletion) {
2257                                 self::processDeletion($xpath, $deletion, $importer);
2258                         }
2259                         if (count($deletions) > 0) {
2260                                 Logger::notice('Deletions had been processed');
2261                                 return 200;
2262                         }
2263                 }
2264
2265                 $entries = $xpath->query("/atom:feed/atom:entry");
2266                 foreach ($entries as $entry) {
2267                         self::processEntry($header, $xpath, $entry, $importer, $xml, $protocol);
2268                 }
2269
2270                 Logger::log("Import done for user " . $importer["importer_uid"] . " from contact " . $importer["id"], Logger::DEBUG);
2271                 return 200;
2272         }
2273
2274         /**
2275          * Returns the activity verb
2276          *
2277          * @param array $item Item array
2278          *
2279          * @return string activity verb
2280          */
2281         private static function constructVerb(array $item)
2282         {
2283                 if ($item['verb']) {
2284                         return $item['verb'];
2285                 }
2286                 return Activity::POST;
2287         }
2288
2289         private static function tgroupCheck($uid, $item)
2290         {
2291                 $mention = false;
2292
2293                 // check that the message originated elsewhere and is a top-level post
2294
2295                 if ($item['wall'] || $item['origin'] || ($item['uri'] != $item['thr-parent'])) {
2296                         return false;
2297                 }
2298
2299                 $user = DBA::selectFirst('user', ['page-flags', 'nickname'], ['uid' => $uid]);
2300                 if (!DBA::isResult($user)) {
2301                         return false;
2302                 }
2303
2304                 $community_page = ($user['page-flags'] == User::PAGE_FLAGS_COMMUNITY);
2305                 $prvgroup = ($user['page-flags'] == User::PAGE_FLAGS_PRVGROUP);
2306
2307                 $link = Strings::normaliseLink(DI::baseUrl() . '/profile/' . $user['nickname']);
2308
2309                 /*
2310                  * Diaspora uses their own hardwired link URL in @-tags
2311                  * instead of the one we supply with webfinger
2312                  */
2313                 $dlink = Strings::normaliseLink(DI::baseUrl() . '/u/' . $user['nickname']);
2314
2315                 $cnt = preg_match_all('/[\@\!]\[url\=(.*?)\](.*?)\[\/url\]/ism', $item['body'], $matches, PREG_SET_ORDER);
2316                 if ($cnt) {
2317                         foreach ($matches as $mtch) {
2318                                 if (Strings::compareLink($link, $mtch[1]) || Strings::compareLink($dlink, $mtch[1])) {
2319                                         $mention = true;
2320                                         Logger::log('mention found: ' . $mtch[2]);
2321                                 }
2322                         }
2323                 }
2324
2325                 if (!$mention) {
2326                         return false;
2327                 }
2328
2329                 return $community_page || $prvgroup;
2330         }
2331
2332         /**
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.
2339          *
2340          * @param $existing
2341          * @param $update
2342          * @return bool
2343          * @throws \Exception
2344          */
2345         private static function isEditedTimestampNewer($existing, $update)
2346         {
2347                 if (empty($existing['edited'])) {
2348                         return true;
2349                 }
2350                 if (empty($update['edited'])) {
2351                         return false;
2352                 }
2353
2354                 $existing_edited = DateTimeFormat::utc($existing['edited']);
2355                 $update_edited = DateTimeFormat::utc($update['edited']);
2356
2357                 return (strcmp($existing_edited, $update_edited) < 0);
2358         }
2359
2360         /**
2361          * Checks if the given contact url does support DFRN
2362          *
2363          * @param string  $url    profile url
2364          * @return boolean
2365          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2366          * @throws \ImagickException
2367          */
2368         public static function isSupportedByContactUrl($url)
2369         {
2370                 $probe = Probe::uri($url, Protocol::DFRN);
2371                 return $probe['network'] == Protocol::DFRN;
2372         }
2373 }