]> git.mxchange.org Git - friendica.git/blob - src/Protocol/DFRN.php
c9ad69cc10a250bbdd4722241fdf0cf636a3d577
[friendica.git] / src / Protocol / DFRN.php
1 <?php
2 /**
3  * @file include/dfrn.php
4  * @brief The implementation of the dfrn protocol
5  *
6  * @see https://github.com/friendica/friendica/wiki/Protocol and
7  * https://github.com/friendica/friendica/blob/master/spec/dfrn2.pdf
8  */
9 namespace Friendica\Protocol;
10
11 use DOMDocument;
12 use DOMXPath;
13 use Friendica\App;
14 use Friendica\Content\OEmbed;
15 use Friendica\Content\Text\BBCode;
16 use Friendica\Content\Text\HTML;
17 use Friendica\Core\Addon;
18 use Friendica\Core\Config;
19 use Friendica\Core\L10n;
20 use Friendica\Core\Logger;
21 use Friendica\Core\Protocol;
22 use Friendica\Core\System;
23 use Friendica\Database\DBA;
24 use Friendica\Model\Contact;
25 use Friendica\Model\Conversation;
26 use Friendica\Model\Event;
27 use Friendica\Model\GContact;
28 use Friendica\Model\Item;
29 use Friendica\Model\PermissionSet;
30 use Friendica\Model\Profile;
31 use Friendica\Model\User;
32 use Friendica\Object\Image;
33 use Friendica\Util\Crypto;
34 use Friendica\Util\DateTimeFormat;
35 use Friendica\Util\Network;
36 use Friendica\Util\Strings;
37 use Friendica\Util\XML;
38 use HTMLPurifier;
39 use HTMLPurifier_Config;
40
41 require_once 'boot.php';
42 require_once 'include/dba.php';
43 require_once "include/enotify.php";
44 require_once "include/items.php";
45 require_once "include/text.php";
46
47 /**
48  * @brief This class contain functions to create and send DFRN XML files
49  */
50 class DFRN
51 {
52
53         const TOP_LEVEL = 0;    // Top level posting
54         const REPLY = 1;                // Regular reply that is stored locally
55         const REPLY_RC = 2;     // Reply that will be relayed
56
57         /**
58          * @brief Generates an array of contact and user for DFRN imports
59          *
60          * This array contains not only the receiver but also the sender of the message.
61          *
62          * @param integer $cid Contact id
63          * @param integer $uid User id
64          *
65          * @return array importer
66          */
67         public static function getImporter($cid, $uid = 0)
68         {
69                 $condition = ['id' => $cid, 'blocked' => false, 'pending' => false];
70                 $contact = DBA::selectFirst('contact', [], $condition);
71                 if (!DBA::isResult($contact)) {
72                         return [];
73                 }
74
75                 $contact['cpubkey'] = $contact['pubkey'];
76                 $contact['cprvkey'] = $contact['prvkey'];
77                 $contact['senderName'] = $contact['name'];
78
79                 if ($uid != 0) {
80                         $condition = ['uid' => $uid, 'account_expired' => false, 'account_removed' => false];
81                         $user = DBA::selectFirst('user', [], $condition);
82                         if (!DBA::isResult($user)) {
83                                 return [];
84                         }
85
86                         $user['importer_uid'] = $user['uid'];
87                         $user['uprvkey'] = $user['prvkey'];
88                 } else {
89                         $user = ['importer_uid' => 0, 'uprvkey' => '', 'timezone' => 'UTC',
90                                 'nickname' => '', 'sprvkey' => '', 'spubkey' => '',
91                                 'page-flags' => 0, 'account-type' => 0, 'prvnets' => 0];
92                 }
93
94                 return array_merge($contact, $user);
95         }
96
97         /**
98          * @brief Generates the atom entries for delivery.php
99          *
100          * This function is used whenever content is transmitted via DFRN.
101          *
102          * @param array $items Item elements
103          * @param array $owner Owner record
104          *
105          * @return string DFRN entries
106          * @todo Find proper type-hints
107          */
108         public static function entries($items, $owner)
109         {
110                 $doc = new DOMDocument('1.0', 'utf-8');
111                 $doc->formatOutput = true;
112
113                 $root = self::addHeader($doc, $owner, "dfrn:owner", "", false);
114
115                 if (! count($items)) {
116                         return trim($doc->saveXML());
117                 }
118
119                 foreach ($items as $item) {
120                         // These values aren't sent when sending from the queue.
121                         /// @todo Check if we can set these values from the queue or if they are needed at all.
122                         $item["entry:comment-allow"] = defaults($item, "entry:comment-allow", true);
123                         $item["entry:cid"] = defaults($item, "entry:cid", 0);
124
125                         $entry = self::entry($doc, "text", $item, $owner, $item["entry:comment-allow"], $item["entry:cid"]);
126                         $root->appendChild($entry);
127                 }
128
129                 return trim($doc->saveXML());
130         }
131
132         /**
133          * @brief Generate an atom feed for the given user
134          *
135          * This function is called when another server is pulling data from the user feed.
136          *
137          * @param string  $dfrn_id     DFRN ID from the requesting party
138          * @param string  $owner_nick  Owner nick name
139          * @param string  $last_update Date of the last update
140          * @param int     $direction   Can be -1, 0 or 1.
141          * @param boolean $onlyheader  Output only the header without content? (Default is "no")
142          *
143          * @return string DFRN feed entries
144          */
145         public static function feed($dfrn_id, $owner_nick, $last_update, $direction = 0, $onlyheader = false)
146         {
147                 $a = get_app();
148
149                 $sitefeed    = ((strlen($owner_nick)) ? false : true); // not yet implemented, need to rewrite huge chunks of following logic
150                 $public_feed = (($dfrn_id) ? false : true);
151                 $starred     = false;   // not yet implemented, possible security issues
152                 $converse    = false;
153
154                 if ($public_feed && $a->argc > 2) {
155                         for ($x = 2; $x < $a->argc; $x++) {
156                                 if ($a->argv[$x] == 'converse') {
157                                         $converse = true;
158                                 }
159                                 if ($a->argv[$x] == 'starred') {
160                                         $starred = true;
161                                 }
162                                 if ($a->argv[$x] == 'category' && $a->argc > ($x + 1) && strlen($a->argv[$x+1])) {
163                                         $category = $a->argv[$x+1];
164                                 }
165                         }
166                 }
167
168                 // default permissions - anonymous user
169
170                 $sql_extra = " AND NOT `item`.`private` ";
171
172                 $r = q(
173                         "SELECT `contact`.*, `user`.`nickname`, `user`.`timezone`, `user`.`page-flags`, `user`.`account-type`
174                         FROM `contact` INNER JOIN `user` ON `user`.`uid` = `contact`.`uid`
175                         WHERE `contact`.`self` AND `user`.`nickname` = '%s' LIMIT 1",
176                         DBA::escape($owner_nick)
177                 );
178
179                 if (! DBA::isResult($r)) {
180                         Logger::log(sprintf('No contact found for nickname=%d', $owner_nick), Logger::WARNING);
181                         killme();
182                 }
183
184                 $owner = $r[0];
185                 $owner_id = $owner['uid'];
186                 $owner_nick = $owner['nickname'];
187
188                 $sql_post_table = "";
189
190                 if (! $public_feed) {
191                         $sql_extra = '';
192                         switch ($direction) {
193                                 case (-1):
194                                         $sql_extra = sprintf(" AND `issued-id` = '%s' ", DBA::escape($dfrn_id));
195                                         $my_id = $dfrn_id;
196                                         break;
197                                 case 0:
198                                         $sql_extra = sprintf(" AND `issued-id` = '%s' AND `duplex` = 1 ", DBA::escape($dfrn_id));
199                                         $my_id = '1:' . $dfrn_id;
200                                         break;
201                                 case 1:
202                                         $sql_extra = sprintf(" AND `dfrn-id` = '%s' AND `duplex` = 1 ", DBA::escape($dfrn_id));
203                                         $my_id = '0:' . $dfrn_id;
204                                         break;
205                                 default:
206                                         return false;
207                                         break; // NOTREACHED
208                         }
209
210                         $r = q(
211                                 "SELECT * FROM `contact` WHERE NOT `blocked` AND `contact`.`uid` = %d $sql_extra LIMIT 1",
212                                 intval($owner_id)
213                         );
214
215                         if (! DBA::isResult($r)) {
216                                 Logger::log(sprintf('No contact found for uid=%d', $owner_id), Logger::WARNING);
217                                 killme();
218                         }
219
220                         $contact = $r[0];
221
222                         $set = PermissionSet::get($owner_id, $contact['id']);
223
224                         if (!empty($set)) {
225                                 $sql_extra = " AND `item`.`psid` IN (" . implode(',', $set) .")";
226                         } else {
227                                 $sql_extra = " AND NOT `item`.`private`";
228                         }
229                 }
230
231                 if ($public_feed) {
232                         $sort = 'DESC';
233                 } else {
234                         $sort = 'ASC';
235                 }
236
237                 if (! strlen($last_update)) {
238                         $last_update = 'now -30 days';
239                 }
240
241                 if (isset($category)) {
242                         $sql_post_table = sprintf(
243                                 "INNER JOIN (SELECT `oid` FROM `term` WHERE `term` = '%s' AND `otype` = %d AND `type` = %d AND `uid` = %d ORDER BY `tid` DESC) AS `term` ON `item`.`id` = `term`.`oid` ",
244                                 DBA::escape(protect_sprintf($category)),
245                                 intval(TERM_OBJ_POST),
246                                 intval(TERM_CATEGORY),
247                                 intval($owner_id)
248                         );
249                         //$sql_extra .= FileTag::fileQuery('item',$category,'category');
250                 }
251
252                 if ($public_feed && ! $converse) {
253                         $sql_extra .= " AND `contact`.`self` = 1 ";
254                 }
255
256                 $check_date = DateTimeFormat::utc($last_update);
257
258                 $r = q(
259                         "SELECT `item`.`id`
260                         FROM `item` USE INDEX (`uid_wall_changed`) $sql_post_table
261                         STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
262                         WHERE `item`.`uid` = %d AND `item`.`wall` AND `item`.`changed` > '%s'
263                         $sql_extra
264                         ORDER BY `item`.`parent` ".$sort.", `item`.`created` ASC LIMIT 0, 300",
265                         intval($owner_id),
266                         DBA::escape($check_date),
267                         DBA::escape($sort)
268                 );
269
270                 $ids = [];
271                 foreach ($r as $item) {
272                         $ids[] = $item['id'];
273                 }
274
275                 if (!empty($ids)) {
276                         $ret = Item::select(Item::DELIVER_FIELDLIST, ['id' => $ids]);
277                         $items = Item::inArray($ret);
278                 } else {
279                         $items = [];
280                 }
281
282                 /*
283                  * Will check further below if this actually returned results.
284                  * We will provide an empty feed if that is the case.
285                  */
286
287                 $doc = new DOMDocument('1.0', 'utf-8');
288                 $doc->formatOutput = true;
289
290                 $alternatelink = $owner['url'];
291
292                 if (isset($category)) {
293                         $alternatelink .= "/category/".$category;
294                 }
295
296                 if ($public_feed) {
297                         $author = "dfrn:owner";
298                 } else {
299                         $author = "author";
300                 }
301
302                 $root = self::addHeader($doc, $owner, $author, $alternatelink, true);
303
304                 /// @TODO This hook can't work anymore
305                 //      Addon::callHooks('atom_feed', $atom);
306
307                 if (!DBA::isResult($items) || $onlyheader) {
308                         $atom = trim($doc->saveXML());
309
310                         Addon::callHooks('atom_feed_end', $atom);
311
312                         return $atom;
313                 }
314
315                 foreach ($items as $item) {
316                         // prevent private email from leaking.
317                         if ($item['network'] == Protocol::MAIL) {
318                                 continue;
319                         }
320
321                         // public feeds get html, our own nodes use bbcode
322
323                         if ($public_feed) {
324                                 $type = 'html';
325                                 // catch any email that's in a public conversation and make sure it doesn't leak
326                                 if ($item['private']) {
327                                         continue;
328                                 }
329                         } else {
330                                 $type = 'text';
331                         }
332
333                         $entry = self::entry($doc, $type, $item, $owner, true);
334                         $root->appendChild($entry);
335                 }
336
337                 $atom = trim($doc->saveXML());
338
339                 Addon::callHooks('atom_feed_end', $atom);
340
341                 return $atom;
342         }
343
344         /**
345          * @brief Generate an atom entry for a given item id
346          *
347          * @param int     $item_id      The item id
348          * @param boolean $conversation Show the conversation. If false show the single post.
349          *
350          * @return string DFRN feed entry
351          */
352         public static function itemFeed($item_id, $conversation = false)
353         {
354                 if ($conversation) {
355                         $condition = ['parent' => $item_id];
356                 } else {
357                         $condition = ['id' => $item_id];
358                 }
359
360                 $ret = Item::select(Item::DELIVER_FIELDLIST, $condition);
361                 $items = Item::inArray($ret);
362                 if (!DBA::isResult($items)) {
363                         killme();
364                 }
365
366                 $item = $items[0];
367
368                 if ($item['uid'] != 0) {
369                         $owner = User::getOwnerDataById($item['uid']);
370                         if (!$owner) {
371                                 killme();
372                         }
373                 } else {
374                         $owner = ['uid' => 0, 'nick' => 'feed-item'];
375                 }
376
377                 $doc = new DOMDocument('1.0', 'utf-8');
378                 $doc->formatOutput = true;
379                 $type = 'html';
380
381                 if ($conversation) {
382                         $root = $doc->createElementNS(NAMESPACE_ATOM1, 'feed');
383                         $doc->appendChild($root);
384
385                         $root->setAttribute("xmlns:thr", NAMESPACE_THREAD);
386                         $root->setAttribute("xmlns:at", NAMESPACE_TOMB);
387                         $root->setAttribute("xmlns:media", NAMESPACE_MEDIA);
388                         $root->setAttribute("xmlns:dfrn", NAMESPACE_DFRN);
389                         $root->setAttribute("xmlns:activity", NAMESPACE_ACTIVITY);
390                         $root->setAttribute("xmlns:georss", NAMESPACE_GEORSS);
391                         $root->setAttribute("xmlns:poco", NAMESPACE_POCO);
392                         $root->setAttribute("xmlns:ostatus", NAMESPACE_OSTATUS);
393                         $root->setAttribute("xmlns:statusnet", NAMESPACE_STATUSNET);
394
395                         //$root = self::addHeader($doc, $owner, "dfrn:owner", "", false);
396
397                         foreach ($items as $item) {
398                                 $entry = self::entry($doc, $type, $item, $owner, true, 0);
399                                 $root->appendChild($entry);
400                         }
401                 } else {
402                         $root = self::entry($doc, $type, $item, $owner, true, 0, true);
403                 }
404
405                 $atom = trim($doc->saveXML());
406                 return $atom;
407         }
408
409         /**
410          * @brief Create XML text for DFRN mails
411          *
412          * @param array $item  message elements
413          * @param array $owner Owner record
414          *
415          * @return string DFRN mail
416          * @todo Find proper type-hints
417          */
418         public static function mail($item, $owner)
419         {
420                 $doc = new DOMDocument('1.0', 'utf-8');
421                 $doc->formatOutput = true;
422
423                 $root = self::addHeader($doc, $owner, "dfrn:owner", "", false);
424
425                 $mail = $doc->createElement("dfrn:mail");
426                 $sender = $doc->createElement("dfrn:sender");
427
428                 XML::addElement($doc, $sender, "dfrn:name", $owner['name']);
429                 XML::addElement($doc, $sender, "dfrn:uri", $owner['url']);
430                 XML::addElement($doc, $sender, "dfrn:avatar", $owner['thumb']);
431
432                 $mail->appendChild($sender);
433
434                 XML::addElement($doc, $mail, "dfrn:id", $item['uri']);
435                 XML::addElement($doc, $mail, "dfrn:in-reply-to", $item['parent-uri']);
436                 XML::addElement($doc, $mail, "dfrn:sentdate", DateTimeFormat::utc($item['created'] . '+00:00', DateTimeFormat::ATOM));
437                 XML::addElement($doc, $mail, "dfrn:subject", $item['title']);
438                 XML::addElement($doc, $mail, "dfrn:content", $item['body']);
439
440                 $root->appendChild($mail);
441
442                 return trim($doc->saveXML());
443         }
444
445         /**
446          * @brief Create XML text for DFRN friend suggestions
447          *
448          * @param array $item  suggestion elements
449          * @param array $owner Owner record
450          *
451          * @return string DFRN suggestions
452          * @todo Find proper type-hints
453          */
454         public static function fsuggest($item, $owner)
455         {
456                 $doc = new DOMDocument('1.0', 'utf-8');
457                 $doc->formatOutput = true;
458
459                 $root = self::addHeader($doc, $owner, "dfrn:owner", "", false);
460
461                 $suggest = $doc->createElement("dfrn:suggest");
462
463                 XML::addElement($doc, $suggest, "dfrn:url", $item['url']);
464                 XML::addElement($doc, $suggest, "dfrn:name", $item['name']);
465                 XML::addElement($doc, $suggest, "dfrn:photo", $item['photo']);
466                 XML::addElement($doc, $suggest, "dfrn:request", $item['request']);
467                 XML::addElement($doc, $suggest, "dfrn:note", $item['note']);
468
469                 $root->appendChild($suggest);
470
471                 return trim($doc->saveXML());
472         }
473
474         /**
475          * @brief Create XML text for DFRN relocations
476          *
477          * @param array $owner Owner record
478          * @param int   $uid   User ID
479          *
480          * @return string DFRN relocations
481          * @todo Find proper type-hints
482          */
483         public static function relocate($owner, $uid)
484         {
485
486                 /* get site pubkey. this could be a new installation with no site keys*/
487                 $pubkey = Config::get('system', 'site_pubkey');
488                 if (! $pubkey) {
489                         $res = Crypto::newKeypair(1024);
490                         Config::set('system', 'site_prvkey', $res['prvkey']);
491                         Config::set('system', 'site_pubkey', $res['pubkey']);
492                 }
493
494                 $rp = q(
495                         "SELECT `resource-id` , `scale`, type FROM `photo`
496                                 WHERE `profile` = 1 AND `uid` = %d ORDER BY scale;",
497                         $uid
498                 );
499                 $photos = [];
500                 $ext = Image::supportedTypes();
501
502                 foreach ($rp as $p) {
503                         $photos[$p['scale']] = System::baseUrl().'/photo/'.$p['resource-id'].'-'.$p['scale'].'.'.$ext[$p['type']];
504                 }
505
506
507                 $doc = new DOMDocument('1.0', 'utf-8');
508                 $doc->formatOutput = true;
509
510                 $root = self::addHeader($doc, $owner, "dfrn:owner", "", false);
511
512                 $relocate = $doc->createElement("dfrn:relocate");
513
514                 XML::addElement($doc, $relocate, "dfrn:url", $owner['url']);
515                 XML::addElement($doc, $relocate, "dfrn:name", $owner['name']);
516                 XML::addElement($doc, $relocate, "dfrn:addr", $owner['addr']);
517                 XML::addElement($doc, $relocate, "dfrn:avatar", $owner['avatar']);
518                 XML::addElement($doc, $relocate, "dfrn:photo", $photos[4]);
519                 XML::addElement($doc, $relocate, "dfrn:thumb", $photos[5]);
520                 XML::addElement($doc, $relocate, "dfrn:micro", $photos[6]);
521                 XML::addElement($doc, $relocate, "dfrn:request", $owner['request']);
522                 XML::addElement($doc, $relocate, "dfrn:confirm", $owner['confirm']);
523                 XML::addElement($doc, $relocate, "dfrn:notify", $owner['notify']);
524                 XML::addElement($doc, $relocate, "dfrn:poll", $owner['poll']);
525                 XML::addElement($doc, $relocate, "dfrn:sitepubkey", Config::get('system', 'site_pubkey'));
526
527                 $root->appendChild($relocate);
528
529                 return trim($doc->saveXML());
530         }
531
532         /**
533          * @brief Adds the header elements for the DFRN protocol
534          *
535          * @param object $doc           XML document
536          * @param array  $owner         Owner record
537          * @param string $authorelement Element name for the author
538          * @param string $alternatelink link to profile or category
539          * @param bool   $public        Is it a header for public posts?
540          *
541          * @return object XML root object
542          * @todo Find proper type-hints
543          */
544         private static function addHeader($doc, $owner, $authorelement, $alternatelink = "", $public = false)
545         {
546
547                 if ($alternatelink == "") {
548                         $alternatelink = $owner['url'];
549                 }
550
551                 $root = $doc->createElementNS(NAMESPACE_ATOM1, 'feed');
552                 $doc->appendChild($root);
553
554                 $root->setAttribute("xmlns:thr", NAMESPACE_THREAD);
555                 $root->setAttribute("xmlns:at", NAMESPACE_TOMB);
556                 $root->setAttribute("xmlns:media", NAMESPACE_MEDIA);
557                 $root->setAttribute("xmlns:dfrn", NAMESPACE_DFRN);
558                 $root->setAttribute("xmlns:activity", NAMESPACE_ACTIVITY);
559                 $root->setAttribute("xmlns:georss", NAMESPACE_GEORSS);
560                 $root->setAttribute("xmlns:poco", NAMESPACE_POCO);
561                 $root->setAttribute("xmlns:ostatus", NAMESPACE_OSTATUS);
562                 $root->setAttribute("xmlns:statusnet", NAMESPACE_STATUSNET);
563
564                 XML::addElement($doc, $root, "id", System::baseUrl()."/profile/".$owner["nick"]);
565                 XML::addElement($doc, $root, "title", $owner["name"]);
566
567                 $attributes = ["uri" => "https://friendi.ca", "version" => FRIENDICA_VERSION."-".DB_UPDATE_VERSION];
568                 XML::addElement($doc, $root, "generator", FRIENDICA_PLATFORM, $attributes);
569
570                 $attributes = ["rel" => "license", "href" => "http://creativecommons.org/licenses/by/3.0/"];
571                 XML::addElement($doc, $root, "link", "", $attributes);
572
573                 $attributes = ["rel" => "alternate", "type" => "text/html", "href" => $alternatelink];
574                 XML::addElement($doc, $root, "link", "", $attributes);
575
576
577                 if ($public) {
578                         // DFRN itself doesn't uses this. But maybe someone else wants to subscribe to the public feed.
579                         OStatus::hublinks($doc, $root, $owner["nick"]);
580
581                         $attributes = ["rel" => "salmon", "href" => System::baseUrl()."/salmon/".$owner["nick"]];
582                         XML::addElement($doc, $root, "link", "", $attributes);
583
584                         $attributes = ["rel" => "http://salmon-protocol.org/ns/salmon-replies", "href" => System::baseUrl()."/salmon/".$owner["nick"]];
585                         XML::addElement($doc, $root, "link", "", $attributes);
586
587                         $attributes = ["rel" => "http://salmon-protocol.org/ns/salmon-mention", "href" => System::baseUrl()."/salmon/".$owner["nick"]];
588                         XML::addElement($doc, $root, "link", "", $attributes);
589                 }
590
591                 // For backward compatibility we keep this element
592                 if ($owner['page-flags'] == Contact::PAGE_COMMUNITY) {
593                         XML::addElement($doc, $root, "dfrn:community", 1);
594                 }
595
596                 // The former element is replaced by this one
597                 XML::addElement($doc, $root, "dfrn:account_type", $owner["account-type"]);
598
599                 /// @todo We need a way to transmit the different page flags like "Contact::PAGE_PRVGROUP"
600
601                 XML::addElement($doc, $root, "updated", DateTimeFormat::utcNow(DateTimeFormat::ATOM));
602
603                 $author = self::addAuthor($doc, $owner, $authorelement, $public);
604                 $root->appendChild($author);
605
606                 return $root;
607         }
608
609         /**
610          * @brief Adds the author element in the header for the DFRN protocol
611          *
612          * @param object  $doc           XML document
613          * @param array   $owner         Owner record
614          * @param string  $authorelement Element name for the author
615          * @param boolean $public        boolean
616          *
617          * @return object XML author object
618          * @todo Find proper type-hints
619          */
620         private static function addAuthor($doc, $owner, $authorelement, $public)
621         {
622                 // Is the profile hidden or shouldn't be published in the net? Then add the "hide" element
623                 $r = q(
624                         "SELECT `id` FROM `profile` INNER JOIN `user` ON `user`.`uid` = `profile`.`uid`
625                                 WHERE (`hidewall` OR NOT `net-publish`) AND `user`.`uid` = %d",
626                         intval($owner['uid'])
627                 );
628                 if (DBA::isResult($r)) {
629                         $hidewall = true;
630                 } else {
631                         $hidewall = false;
632                 }
633
634                 $author = $doc->createElement($authorelement);
635
636                 $namdate = DateTimeFormat::utc($owner['name-date'].'+00:00', DateTimeFormat::ATOM);
637                 $uridate = DateTimeFormat::utc($owner['uri-date'].'+00:00', DateTimeFormat::ATOM);
638                 $picdate = DateTimeFormat::utc($owner['avatar-date'].'+00:00', DateTimeFormat::ATOM);
639
640                 $attributes = [];
641
642                 if (!$public || !$hidewall) {
643                         $attributes = ["dfrn:updated" => $namdate];
644                 }
645
646                 XML::addElement($doc, $author, "name", $owner["name"], $attributes);
647                 XML::addElement($doc, $author, "uri", System::baseUrl().'/profile/'.$owner["nickname"], $attributes);
648                 XML::addElement($doc, $author, "dfrn:handle", $owner["addr"], $attributes);
649
650                 $attributes = ["rel" => "photo", "type" => "image/jpeg",
651                                         "media:width" => 300, "media:height" => 300, "href" => $owner['photo']];
652
653                 if (!$public || !$hidewall) {
654                         $attributes["dfrn:updated"] = $picdate;
655                 }
656
657                 XML::addElement($doc, $author, "link", "", $attributes);
658
659                 $attributes["rel"] = "avatar";
660                 XML::addElement($doc, $author, "link", "", $attributes);
661
662                 if ($hidewall) {
663                         XML::addElement($doc, $author, "dfrn:hide", "true");
664                 }
665
666                 // The following fields will only be generated if the data isn't meant for a public feed
667                 if ($public) {
668                         return $author;
669                 }
670
671                 $birthday = feed_birthday($owner['uid'], $owner['timezone']);
672
673                 if ($birthday) {
674                         XML::addElement($doc, $author, "dfrn:birthday", $birthday);
675                 }
676
677                 // Only show contact details when we are allowed to
678                 $r = q(
679                         "SELECT `profile`.`about`, `profile`.`name`, `profile`.`homepage`, `user`.`nickname`,
680                                 `user`.`timezone`, `profile`.`locality`, `profile`.`region`, `profile`.`country-name`,
681                                 `profile`.`pub_keywords`, `profile`.`xmpp`, `profile`.`dob`
682                         FROM `profile`
683                                 INNER JOIN `user` ON `user`.`uid` = `profile`.`uid`
684                                 WHERE `profile`.`is-default` AND NOT `user`.`hidewall` AND `user`.`uid` = %d",
685                         intval($owner['uid'])
686                 );
687                 if (DBA::isResult($r)) {
688                         $profile = $r[0];
689
690                         XML::addElement($doc, $author, "poco:displayName", $profile["name"]);
691                         XML::addElement($doc, $author, "poco:updated", $namdate);
692
693                         if (trim($profile["dob"]) > '0001-01-01') {
694                                 XML::addElement($doc, $author, "poco:birthday", "0000-".date("m-d", strtotime($profile["dob"])));
695                         }
696
697                         XML::addElement($doc, $author, "poco:note", $profile["about"]);
698                         XML::addElement($doc, $author, "poco:preferredUsername", $profile["nickname"]);
699
700                         $savetz = date_default_timezone_get();
701                         date_default_timezone_set($profile["timezone"]);
702                         XML::addElement($doc, $author, "poco:utcOffset", date("P"));
703                         date_default_timezone_set($savetz);
704
705                         if (trim($profile["homepage"]) != "") {
706                                 $urls = $doc->createElement("poco:urls");
707                                 XML::addElement($doc, $urls, "poco:type", "homepage");
708                                 XML::addElement($doc, $urls, "poco:value", $profile["homepage"]);
709                                 XML::addElement($doc, $urls, "poco:primary", "true");
710                                 $author->appendChild($urls);
711                         }
712
713                         if (trim($profile["pub_keywords"]) != "") {
714                                 $keywords = explode(",", $profile["pub_keywords"]);
715
716                                 foreach ($keywords as $keyword) {
717                                         XML::addElement($doc, $author, "poco:tags", trim($keyword));
718                                 }
719                         }
720
721                         if (trim($profile["xmpp"]) != "") {
722                                 $ims = $doc->createElement("poco:ims");
723                                 XML::addElement($doc, $ims, "poco:type", "xmpp");
724                                 XML::addElement($doc, $ims, "poco:value", $profile["xmpp"]);
725                                 XML::addElement($doc, $ims, "poco:primary", "true");
726                                 $author->appendChild($ims);
727                         }
728
729                         if (trim($profile["locality"].$profile["region"].$profile["country-name"]) != "") {
730                                 $element = $doc->createElement("poco:address");
731
732                                 XML::addElement($doc, $element, "poco:formatted", Profile::formatLocation($profile));
733
734                                 if (trim($profile["locality"]) != "") {
735                                         XML::addElement($doc, $element, "poco:locality", $profile["locality"]);
736                                 }
737
738                                 if (trim($profile["region"]) != "") {
739                                         XML::addElement($doc, $element, "poco:region", $profile["region"]);
740                                 }
741
742                                 if (trim($profile["country-name"]) != "") {
743                                         XML::addElement($doc, $element, "poco:country", $profile["country-name"]);
744                                 }
745
746                                 $author->appendChild($element);
747                         }
748                 }
749
750                 return $author;
751         }
752
753         /**
754          * @brief Adds the author elements in the "entry" elements of the DFRN protocol
755          *
756          * @param object $doc         XML document
757          * @param string $element     Element name for the author
758          * @param string $contact_url Link of the contact
759          * @param array  $item        Item elements
760          *
761          * @return object XML author object
762          * @todo Find proper type-hints
763          */
764         private static function addEntryAuthor($doc, $element, $contact_url, $item)
765         {
766                 $contact = Contact::getDetailsByURL($contact_url, $item["uid"]);
767
768                 $author = $doc->createElement($element);
769                 XML::addElement($doc, $author, "name", $contact["name"]);
770                 XML::addElement($doc, $author, "uri", $contact["url"]);
771                 XML::addElement($doc, $author, "dfrn:handle", $contact["addr"]);
772
773                 /// @Todo
774                 /// - Check real image type and image size
775                 /// - Check which of these boths elements we should use
776                 $attributes = [
777                                 "rel" => "photo",
778                                 "type" => "image/jpeg",
779                                 "media:width" => 80,
780                                 "media:height" => 80,
781                                 "href" => $contact["photo"]];
782                 XML::addElement($doc, $author, "link", "", $attributes);
783
784                 $attributes = [
785                                 "rel" => "avatar",
786                                 "type" => "image/jpeg",
787                                 "media:width" => 80,
788                                 "media:height" => 80,
789                                 "href" => $contact["photo"]];
790                 XML::addElement($doc, $author, "link", "", $attributes);
791
792                 return $author;
793         }
794
795         /**
796          * @brief Adds the activity elements
797          *
798          * @param object $doc      XML document
799          * @param string $element  Element name for the activity
800          * @param string $activity activity value
801          *
802          * @return object XML activity object
803          * @todo Find proper type-hints
804          */
805         private static function createActivity($doc, $element, $activity)
806         {
807                 if ($activity) {
808                         $entry = $doc->createElement($element);
809
810                         $r = XML::parseString($activity, false);
811                         if (!$r) {
812                                 return false;
813                         }
814
815                         if ($r->type) {
816                                 XML::addElement($doc, $entry, "activity:object-type", $r->type);
817                         }
818
819                         if ($r->id) {
820                                 XML::addElement($doc, $entry, "id", $r->id);
821                         }
822
823                         if ($r->title) {
824                                 XML::addElement($doc, $entry, "title", $r->title);
825                         }
826
827                         if ($r->link) {
828                                 if (substr($r->link, 0, 1) == '<') {
829                                         if (strstr($r->link, '&') && (! strstr($r->link, '&amp;'))) {
830                                                 $r->link = str_replace('&', '&amp;', $r->link);
831                                         }
832
833                                         $r->link = preg_replace('/\<link(.*?)\"\>/', '<link$1"/>', $r->link);
834
835                                         // XML does need a single element as root element so we add a dummy element here
836                                         $data = XML::parseString("<dummy>" . $r->link . "</dummy>", false);
837                                         if (is_object($data)) {
838                                                 foreach ($data->link as $link) {
839                                                         $attributes = [];
840                                                         foreach ($link->attributes() as $parameter => $value) {
841                                                                 $attributes[$parameter] = $value;
842                                                         }
843                                                         XML::addElement($doc, $entry, "link", "", $attributes);
844                                                 }
845                                         }
846                                 } else {
847                                         $attributes = ["rel" => "alternate", "type" => "text/html", "href" => $r->link];
848                                         XML::addElement($doc, $entry, "link", "", $attributes);
849                                 }
850                         }
851                         if ($r->content) {
852                                 XML::addElement($doc, $entry, "content", BBCode::convert($r->content), ["type" => "html"]);
853                         }
854
855                         return $entry;
856                 }
857
858                 return false;
859         }
860
861         /**
862          * @brief Adds the elements for attachments
863          *
864          * @param object $doc  XML document
865          * @param object $root XML root
866          * @param array  $item Item element
867          *
868          * @return object XML attachment object
869          * @todo Find proper type-hints
870          */
871         private static function getAttachment($doc, $root, $item)
872         {
873                 $arr = explode('[/attach],', $item['attach']);
874                 if (count($arr)) {
875                         foreach ($arr as $r) {
876                                 $matches = false;
877                                 $cnt = preg_match('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\" title=\"(.*?)\"|', $r, $matches);
878                                 if ($cnt) {
879                                         $attributes = ["rel" => "enclosure",
880                                                         "href" => $matches[1],
881                                                         "type" => $matches[3]];
882
883                                         if (intval($matches[2])) {
884                                                 $attributes["length"] = intval($matches[2]);
885                                         }
886
887                                         if (trim($matches[4]) != "") {
888                                                 $attributes["title"] = trim($matches[4]);
889                                         }
890
891                                         XML::addElement($doc, $root, "link", "", $attributes);
892                                 }
893                         }
894                 }
895         }
896
897         /**
898          * @brief Adds the "entry" elements for the DFRN protocol
899          *
900          * @param object $doc     XML document
901          * @param string $type    "text" or "html"
902          * @param array  $item    Item element
903          * @param array  $owner   Owner record
904          * @param bool   $comment Trigger the sending of the "comment" element
905          * @param int    $cid     Contact ID of the recipient
906          * @param bool   $single  If set, the entry is created as an XML document with a single "entry" element
907          *
908          * @return object XML entry object
909          * @todo Find proper type-hints
910          */
911         private static function entry($doc, $type, array $item, array $owner, $comment = false, $cid = 0, $single = false)
912         {
913                 $mentioned = [];
914
915                 if (!$item['parent']) {
916                         return;
917                 }
918
919                 if ($item['deleted']) {
920                         $attributes = ["ref" => $item['uri'], "when" => DateTimeFormat::utc($item['edited'] . '+00:00', DateTimeFormat::ATOM)];
921                         return XML::createElement($doc, "at:deleted-entry", "", $attributes);
922                 }
923
924                 if (!$single) {
925                         $entry = $doc->createElement("entry");
926                 } else {
927                         $entry = $doc->createElementNS(NAMESPACE_ATOM1, 'entry');
928                         $doc->appendChild($entry);
929
930                         $entry->setAttribute("xmlns:thr", NAMESPACE_THREAD);
931                         $entry->setAttribute("xmlns:at", NAMESPACE_TOMB);
932                         $entry->setAttribute("xmlns:media", NAMESPACE_MEDIA);
933                         $entry->setAttribute("xmlns:dfrn", NAMESPACE_DFRN);
934                         $entry->setAttribute("xmlns:activity", NAMESPACE_ACTIVITY);
935                         $entry->setAttribute("xmlns:georss", NAMESPACE_GEORSS);
936                         $entry->setAttribute("xmlns:poco", NAMESPACE_POCO);
937                         $entry->setAttribute("xmlns:ostatus", NAMESPACE_OSTATUS);
938                         $entry->setAttribute("xmlns:statusnet", NAMESPACE_STATUSNET);
939                 }
940
941                 if ($item['private']) {
942                         $body = Item::fixPrivatePhotos($item['body'], $owner['uid'], $item, $cid);
943                 } else {
944                         $body = $item['body'];
945                 }
946
947                 // Remove the abstract element. It is only locally important.
948                 $body = BBCode::stripAbstract($body);
949
950                 $htmlbody = '';
951                 if ($type == 'html') {
952                         $htmlbody = $body;
953
954                         if ($item['title'] != "") {
955                                 $htmlbody = "[b]" . $item['title'] . "[/b]\n\n" . $htmlbody;
956                         }
957
958                         $htmlbody = BBCode::convert($htmlbody, false, 7);
959                 }
960
961                 $author = self::addEntryAuthor($doc, "author", $item["author-link"], $item);
962                 $entry->appendChild($author);
963
964                 $dfrnowner = self::addEntryAuthor($doc, "dfrn:owner", $item["owner-link"], $item);
965                 $entry->appendChild($dfrnowner);
966
967                 if (($item['parent'] != $item['id']) || ($item['parent-uri'] !== $item['uri']) || (($item['thr-parent'] !== '') && ($item['thr-parent'] !== $item['uri']))) {
968                         $parent_item = (($item['thr-parent']) ? $item['thr-parent'] : $item['parent-uri']);
969                         $parent = Item::selectFirst(['guid', 'plink'], ['uri' => $parent_item, 'uid' => $item['uid']]);
970                         $attributes = ["ref" => $parent_item, "type" => "text/html",
971                                                 "href" => $parent['plink'],
972                                                 "dfrn:diaspora_guid" => $parent['guid']];
973                         XML::addElement($doc, $entry, "thr:in-reply-to", "", $attributes);
974                 }
975
976                 // Add conversation data. This is used for OStatus
977                 $conversation_href = System::baseUrl()."/display/".$owner["nick"]."/".$item["parent"];
978                 $conversation_uri = $conversation_href;
979
980                 if (isset($parent_item)) {
981                         $conversation = DBA::selectFirst('conversation', ['conversation-uri', 'conversation-href'], ['item-uri' => $item['parent-uri']]);
982                         if (DBA::isResult($conversation)) {
983                                 if ($conversation['conversation-uri'] != '') {
984                                         $conversation_uri = $conversation['conversation-uri'];
985                                 }
986                                 if ($conversation['conversation-href'] != '') {
987                                         $conversation_href = $conversation['conversation-href'];
988                                 }
989                         }
990                 }
991
992                 $attributes = [
993                                 "href" => $conversation_href,
994                                 "ref" => $conversation_uri];
995
996                 XML::addElement($doc, $entry, "ostatus:conversation", $conversation_uri, $attributes);
997
998                 XML::addElement($doc, $entry, "id", $item["uri"]);
999                 XML::addElement($doc, $entry, "title", $item["title"]);
1000
1001                 XML::addElement($doc, $entry, "published", DateTimeFormat::utc($item["created"] . "+00:00", DateTimeFormat::ATOM));
1002                 XML::addElement($doc, $entry, "updated", DateTimeFormat::utc($item["edited"] . "+00:00", DateTimeFormat::ATOM));
1003
1004                 // "dfrn:env" is used to read the content
1005                 XML::addElement($doc, $entry, "dfrn:env", base64url_encode($body, true));
1006
1007                 // The "content" field is not read by the receiver. We could remove it when the type is "text"
1008                 // We keep it at the moment, maybe there is some old version that doesn't read "dfrn:env"
1009                 XML::addElement($doc, $entry, "content", (($type == 'html') ? $htmlbody : $body), ["type" => $type]);
1010
1011                 // We save this value in "plink". Maybe we should read it from there as well?
1012                 XML::addElement(
1013                         $doc,
1014                         $entry,
1015                         "link",
1016                         "",
1017                         ["rel" => "alternate", "type" => "text/html",
1018                                  "href" => System::baseUrl() . "/display/" . $item["guid"]]
1019                 );
1020
1021                 // "comment-allow" is some old fashioned stuff for old Friendica versions.
1022                 // It is included in the rewritten code for completeness
1023                 if ($comment) {
1024                         XML::addElement($doc, $entry, "dfrn:comment-allow", 1);
1025                 }
1026
1027                 if ($item['location']) {
1028                         XML::addElement($doc, $entry, "dfrn:location", $item['location']);
1029                 }
1030
1031                 if ($item['coord']) {
1032                         XML::addElement($doc, $entry, "georss:point", $item['coord']);
1033                 }
1034
1035                 if ($item['private']) {
1036                         XML::addElement($doc, $entry, "dfrn:private", ($item['private'] ? $item['private'] : 1));
1037                 }
1038
1039                 if ($item['extid']) {
1040                         XML::addElement($doc, $entry, "dfrn:extid", $item['extid']);
1041                 }
1042
1043                 if ($item['post-type'] == Item::PT_PAGE) {
1044                         XML::addElement($doc, $entry, "dfrn:bookmark", "true");
1045                 }
1046
1047                 if ($item['app']) {
1048                         XML::addElement($doc, $entry, "statusnet:notice_info", "", ["local_id" => $item['id'], "source" => $item['app']]);
1049                 }
1050
1051                 XML::addElement($doc, $entry, "dfrn:diaspora_guid", $item["guid"]);
1052
1053                 // The signed text contains the content in Markdown, the sender handle and the signatur for the content
1054                 // It is needed for relayed comments to Diaspora.
1055                 if ($item['signed_text']) {
1056                         $sign = base64_encode(json_encode(['signed_text' => $item['signed_text'],'signature' => $item['signature'],'signer' => $item['signer']]));
1057                         XML::addElement($doc, $entry, "dfrn:diaspora_signature", $sign);
1058                 }
1059
1060                 XML::addElement($doc, $entry, "activity:verb", self::constructVerb($item));
1061
1062                 if ($item['object-type'] != "") {
1063                         XML::addElement($doc, $entry, "activity:object-type", $item['object-type']);
1064                 } elseif ($item['id'] == $item['parent']) {
1065                         XML::addElement($doc, $entry, "activity:object-type", ACTIVITY_OBJ_NOTE);
1066                 } else {
1067                         XML::addElement($doc, $entry, "activity:object-type", ACTIVITY_OBJ_COMMENT);
1068                 }
1069
1070                 $actobj = self::createActivity($doc, "activity:object", $item['object']);
1071                 if ($actobj) {
1072                         $entry->appendChild($actobj);
1073                 }
1074
1075                 $actarg = self::createActivity($doc, "activity:target", $item['target']);
1076                 if ($actarg) {
1077                         $entry->appendChild($actarg);
1078                 }
1079
1080                 $tags = Item::getFeedTags($item);
1081
1082                 /// @TODO Combine this with similar below if() block?
1083                 if (count($tags)) {
1084                         foreach ($tags as $t) {
1085                                 if (($type != 'html') || ($t[0] != "@")) {
1086                                         XML::addElement($doc, $entry, "category", "", ["scheme" => "X-DFRN:".$t[0].":".$t[1], "term" => $t[2]]);
1087                                 }
1088                         }
1089                 }
1090
1091                 if (count($tags)) {
1092                         foreach ($tags as $t) {
1093                                 if ($t[0] == "@") {
1094                                         $mentioned[$t[1]] = $t[1];
1095                                 }
1096                         }
1097                 }
1098
1099                 foreach ($mentioned as $mention) {
1100                         $condition = ['uid' => $owner["uid"], 'nurl' => normalise_link($mention)];
1101                         $contact = DBA::selectFirst('contact', ['forum', 'prv'], $condition);
1102
1103                         if (DBA::isResult($contact) && ($contact["forum"] || $contact["prv"])) {
1104                                 XML::addElement(
1105                                         $doc,
1106                                         $entry,
1107                                         "link",
1108                                         "",
1109                                         ["rel" => "mentioned",
1110                                                         "ostatus:object-type" => ACTIVITY_OBJ_GROUP,
1111                                                         "href" => $mention]
1112                                 );
1113                         } else {
1114                                 XML::addElement(
1115                                         $doc,
1116                                         $entry,
1117                                         "link",
1118                                         "",
1119                                         ["rel" => "mentioned",
1120                                                         "ostatus:object-type" => ACTIVITY_OBJ_PERSON,
1121                                                         "href" => $mention]
1122                                 );
1123                         }
1124                 }
1125
1126                 self::getAttachment($doc, $entry, $item);
1127
1128                 return $entry;
1129         }
1130
1131         /**
1132          * @brief encrypts data via AES
1133          *
1134          * @param string $data The data that is to be encrypted
1135          * @param string $key  The AES key
1136          *
1137          * @return string encrypted data
1138          */
1139         private static function aesEncrypt($data, $key)
1140         {
1141                 return openssl_encrypt($data, 'aes-128-ecb', $key, OPENSSL_RAW_DATA);
1142         }
1143
1144         /**
1145          * @brief decrypts data via AES
1146          *
1147          * @param string $encrypted The encrypted data
1148          * @param string $key       The AES key
1149          *
1150          * @return string decrypted data
1151          */
1152         public static function aesDecrypt($encrypted, $key)
1153         {
1154                 return openssl_decrypt($encrypted, 'aes-128-ecb', $key, OPENSSL_RAW_DATA);
1155         }
1156
1157         /**
1158          * @brief Delivers the atom content to the contacts
1159          *
1160          * @param array  $owner    Owner record
1161          * @param array  $contact  Contact record of the receiver
1162          * @param string $atom     Content that will be transmitted
1163          * @param bool   $dissolve (to be documented)
1164          *
1165          * @return int Deliver status. Negative values mean an error.
1166          * @todo Add array type-hint for $owner, $contact
1167          */
1168         public static function deliver($owner, $contact, $atom, $dissolve = false, $legacy_transport = false)
1169         {
1170                 $a = get_app();
1171
1172                 // At first try the Diaspora transport layer
1173                 if (!$dissolve && !$legacy_transport) {
1174                         $curlResult = self::transmit($owner, $contact, $atom);
1175                         if ($curlResult >= 200) {
1176                                 Logger::log('Delivery via Diaspora transport layer was successful with status ' . $curlResult);
1177                                 return $curlResult;
1178                         }
1179                 }
1180
1181                 $idtosend = $orig_id = (($contact['dfrn-id']) ? $contact['dfrn-id'] : $contact['issued-id']);
1182
1183                 if ($contact['duplex'] && $contact['dfrn-id']) {
1184                         $idtosend = '0:' . $orig_id;
1185                 }
1186                 if ($contact['duplex'] && $contact['issued-id']) {
1187                         $idtosend = '1:' . $orig_id;
1188                 }
1189
1190                 $rino = Config::get('system', 'rino_encrypt');
1191                 $rino = intval($rino);
1192
1193                 Logger::log("Local rino version: ". $rino, Logger::DEBUG);
1194
1195                 $ssl_val = intval(Config::get('system', 'ssl_policy'));
1196                 $ssl_policy = '';
1197
1198                 switch ($ssl_val) {
1199                         case SSL_POLICY_FULL:
1200                                 $ssl_policy = 'full';
1201                                 break;
1202                         case SSL_POLICY_SELFSIGN:
1203                                 $ssl_policy = 'self';
1204                                 break;
1205                         case SSL_POLICY_NONE:
1206                         default:
1207                                 $ssl_policy = 'none';
1208                                 break;
1209                 }
1210
1211                 $url = $contact['notify'] . '&dfrn_id=' . $idtosend . '&dfrn_version=' . DFRN_PROTOCOL_VERSION . (($rino) ? '&rino='.$rino : '');
1212
1213                 Logger::log('dfrn_deliver: ' . $url);
1214
1215                 $curlResult = Network::curl($url);
1216
1217                 if ($curlResult->isTimeout()) {
1218                         Contact::markForArchival($contact);
1219                         return -2; // timed out
1220                 }
1221
1222                 $xml = $curlResult->getBody();
1223
1224                 $curl_stat = $curlResult->getReturnCode();
1225                 if (empty($curl_stat)) {
1226                         Contact::markForArchival($contact);
1227                         return -3; // timed out
1228                 }
1229
1230                 Logger::log('dfrn_deliver: ' . $xml, Logger::DATA);
1231
1232                 if (empty($xml)) {
1233                         Contact::markForArchival($contact);
1234                         return 3;
1235                 }
1236
1237                 if (strpos($xml, '<?xml') === false) {
1238                         Logger::log('dfrn_deliver: no valid XML returned');
1239                         Logger::log('dfrn_deliver: returned XML: ' . $xml, Logger::DATA);
1240                         Contact::markForArchival($contact);
1241                         return 3;
1242                 }
1243
1244                 $res = XML::parseString($xml);
1245
1246                 if (!is_object($res) || (intval($res->status) != 0) || !strlen($res->challenge) || !strlen($res->dfrn_id)) {
1247                         Contact::markForArchival($contact);
1248
1249                         if (empty($res->status)) {
1250                                 $status = 3;
1251                         } else {
1252                                 $status = $res->status;
1253                         }
1254
1255                         return $status;
1256                 }
1257
1258                 $postvars     = [];
1259                 $sent_dfrn_id = hex2bin((string) $res->dfrn_id);
1260                 $challenge    = hex2bin((string) $res->challenge);
1261                 $perm         = (($res->perm) ? $res->perm : null);
1262                 $dfrn_version = (float) (($res->dfrn_version) ? $res->dfrn_version : 2.0);
1263                 $rino_remote_version = intval($res->rino);
1264                 $page         = (($owner['page-flags'] == Contact::PAGE_COMMUNITY) ? 1 : 0);
1265
1266                 Logger::log("Remote rino version: ".$rino_remote_version." for ".$contact["url"], Logger::DEBUG);
1267
1268                 if ($owner['page-flags'] == Contact::PAGE_PRVGROUP) {
1269                         $page = 2;
1270                 }
1271
1272                 $final_dfrn_id = '';
1273
1274                 if ($perm) {
1275                         if ((($perm == 'rw') && !intval($contact['writable']))
1276                                 || (($perm == 'r') && intval($contact['writable']))
1277                         ) {
1278                                 DBA::update('contact', ['writable' => ($perm == 'rw')], ['id' => $contact['id']]);
1279
1280                                 $contact['writable'] = (string) 1 - intval($contact['writable']);
1281                         }
1282                 }
1283
1284                 if (($contact['duplex'] && strlen($contact['pubkey']))
1285                         || ($owner['page-flags'] == Contact::PAGE_COMMUNITY && strlen($contact['pubkey']))
1286                         || ($contact['rel'] == Contact::SHARING && strlen($contact['pubkey']))
1287                 ) {
1288                         openssl_public_decrypt($sent_dfrn_id, $final_dfrn_id, $contact['pubkey']);
1289                         openssl_public_decrypt($challenge, $postvars['challenge'], $contact['pubkey']);
1290                 } else {
1291                         openssl_private_decrypt($sent_dfrn_id, $final_dfrn_id, $contact['prvkey']);
1292                         openssl_private_decrypt($challenge, $postvars['challenge'], $contact['prvkey']);
1293                 }
1294
1295                 $final_dfrn_id = substr($final_dfrn_id, 0, strpos($final_dfrn_id, '.'));
1296
1297                 if (strpos($final_dfrn_id, ':') == 1) {
1298                         $final_dfrn_id = substr($final_dfrn_id, 2);
1299                 }
1300
1301                 if ($final_dfrn_id != $orig_id) {
1302                         Logger::log('dfrn_deliver: wrong dfrn_id.');
1303                         // did not decode properly - cannot trust this site
1304                         Contact::markForArchival($contact);
1305                         return 3;
1306                 }
1307
1308                 $postvars['dfrn_id']      = $idtosend;
1309                 $postvars['dfrn_version'] = DFRN_PROTOCOL_VERSION;
1310                 if ($dissolve) {
1311                         $postvars['dissolve'] = '1';
1312                 }
1313
1314                 if ((($contact['rel']) && ($contact['rel'] != Contact::SHARING) && (! $contact['blocked'])) || ($owner['page-flags'] == Contact::PAGE_COMMUNITY)) {
1315                         $postvars['data'] = $atom;
1316                         $postvars['perm'] = 'rw';
1317                 } else {
1318                         $postvars['data'] = str_replace('<dfrn:comment-allow>1', '<dfrn:comment-allow>0', $atom);
1319                         $postvars['perm'] = 'r';
1320                 }
1321
1322                 $postvars['ssl_policy'] = $ssl_policy;
1323
1324                 if ($page) {
1325                         $postvars['page'] = $page;
1326                 }
1327
1328
1329                 if ($rino > 0 && $rino_remote_version > 0 && (! $dissolve)) {
1330                         Logger::log('rino version: '. $rino_remote_version);
1331
1332                         switch ($rino_remote_version) {
1333                                 case 1:
1334                                         $key = openssl_random_pseudo_bytes(16);
1335                                         $data = self::aesEncrypt($postvars['data'], $key);
1336                                         break;
1337
1338                                 default:
1339                                         Logger::log("rino: invalid requested version '$rino_remote_version'");
1340                                         Contact::markForArchival($contact);
1341                                         return -8;
1342                         }
1343
1344                         $postvars['rino'] = $rino_remote_version;
1345                         $postvars['data'] = bin2hex($data);
1346
1347                         if ($dfrn_version >= 2.1) {
1348                                 if (($contact['duplex'] && strlen($contact['pubkey']))
1349                                         || ($owner['page-flags'] == Contact::PAGE_COMMUNITY && strlen($contact['pubkey']))
1350                                         || ($contact['rel'] == Contact::SHARING && strlen($contact['pubkey']))
1351                                 ) {
1352                                         openssl_public_encrypt($key, $postvars['key'], $contact['pubkey']);
1353                                 } else {
1354                                         openssl_private_encrypt($key, $postvars['key'], $contact['prvkey']);
1355                                 }
1356                         } else {
1357                                 if (($contact['duplex'] && strlen($contact['prvkey'])) || ($owner['page-flags'] == Contact::PAGE_COMMUNITY)) {
1358                                         openssl_private_encrypt($key, $postvars['key'], $contact['prvkey']);
1359                                 } else {
1360                                         openssl_public_encrypt($key, $postvars['key'], $contact['pubkey']);
1361                                 }
1362                         }
1363
1364                         Logger::log('md5 rawkey ' . md5($postvars['key']));
1365
1366                         $postvars['key'] = bin2hex($postvars['key']);
1367                 }
1368
1369
1370                 Logger::log('dfrn_deliver: ' . "SENDING: " . print_r($postvars, true), Logger::DATA);
1371
1372                 $postResult = Network::post($contact['notify'], $postvars);
1373
1374                 $xml = $postResult->getBody();
1375
1376                 Logger::log('dfrn_deliver: ' . "RECEIVED: " . $xml, Logger::DATA);
1377
1378                 $curl_stat = $postResult->getReturnCode();
1379                 if (empty($curl_stat) || empty($xml)) {
1380                         Contact::markForArchival($contact);
1381                         return -9; // timed out
1382                 }
1383
1384                 if (($curl_stat == 503) && stristr($postResult->getHeader(), 'retry-after')) {
1385                         Contact::markForArchival($contact);
1386                         return -10;
1387                 }
1388
1389                 if (strpos($xml, '<?xml') === false) {
1390                         Logger::log('dfrn_deliver: phase 2: no valid XML returned');
1391                         Logger::log('dfrn_deliver: phase 2: returned XML: ' . $xml, Logger::DATA);
1392                         Contact::markForArchival($contact);
1393                         return 3;
1394                 }
1395
1396                 $res = XML::parseString($xml);
1397
1398                 if (!isset($res->status)) {
1399                         Contact::markForArchival($contact);
1400                         return -11;
1401                 }
1402
1403                 // Possibly old servers had returned an empty value when everything was okay
1404                 if (empty($res->status)) {
1405                         $res->status = 200;
1406                 }
1407
1408                 if (!empty($res->message)) {
1409                         Logger::log('Delivery returned status '.$res->status.' - '.$res->message, Logger::DEBUG);
1410                 }
1411
1412                 if (($res->status >= 200) && ($res->status <= 299)) {
1413                         Contact::unmarkForArchival($contact);
1414                 }
1415
1416                 return intval($res->status);
1417         }
1418
1419         /**
1420          * @brief Transmits atom content to the contacts via the Diaspora transport layer
1421          *
1422          * @param array  $owner    Owner record
1423          * @param array  $contact  Contact record of the receiver
1424          * @param string $atom     Content that will be transmitted
1425          *
1426          * @return int Deliver status. Negative values mean an error.
1427          */
1428         public static function transmit($owner, $contact, $atom, $public_batch = false)
1429         {
1430                 $a = get_app();
1431
1432                 if (!$public_batch) {
1433                         if (empty($contact['addr'])) {
1434                                 Logger::log('Empty contact handle for ' . $contact['id'] . ' - ' . $contact['url'] . ' - trying to update it.');
1435                                 if (Contact::updateFromProbe($contact['id'])) {
1436                                         $new_contact = DBA::selectFirst('contact', ['addr'], ['id' => $contact['id']]);
1437                                         $contact['addr'] = $new_contact['addr'];
1438                                 }
1439
1440                                 if (empty($contact['addr'])) {
1441                                         Logger::log('Unable to find contact handle for ' . $contact['id'] . ' - ' . $contact['url']);
1442                                         Contact::markForArchival($contact);
1443                                         return -21;
1444                                 }
1445                         }
1446
1447                         $fcontact = Diaspora::personByHandle($contact['addr']);
1448                         if (empty($fcontact)) {
1449                                 Logger::log('Unable to find contact details for ' . $contact['id'] . ' - ' . $contact['addr']);
1450                                 Contact::markForArchival($contact);
1451                                 return -22;
1452                         }
1453                         $pubkey = $fcontact['pubkey'];
1454                 } else {
1455                         $pubkey = '';
1456                 }
1457
1458                 $envelope = Diaspora::buildMessage($atom, $owner, $contact, $owner['uprvkey'], $pubkey, $public_batch);
1459
1460                 // Create the endpoint for public posts. This is some WIP and should later be added to the probing
1461                 if ($public_batch && empty($contact["batch"])) {
1462                         $parts = parse_url($contact["notify"]);
1463                         $path_parts = explode('/', $parts['path']);
1464                         array_pop($path_parts);
1465                         $parts['path'] =  implode('/', $path_parts);
1466                         $contact["batch"] = Network::unparseURL($parts);
1467                 }
1468
1469                 $dest_url = ($public_batch ? $contact["batch"] : $contact["notify"]);
1470
1471                 $content_type = ($public_batch ? "application/magic-envelope+xml" : "application/json");
1472
1473                 $postResult = Network::post($dest_url, $envelope, ["Content-Type: ".$content_type]);
1474                 $xml = $postResult->getBody();
1475
1476                 $curl_stat = $postResult->getReturnCode();
1477                 if (empty($curl_stat) || empty($xml)) {
1478                         Logger::log('Empty answer from ' . $contact['id'] . ' - ' . $dest_url);
1479                         Contact::markForArchival($contact);
1480                         return -9; // timed out
1481                 }
1482
1483                 if (($curl_stat == 503) && (stristr($postResult->getHeader(), 'retry-after'))) {
1484                         Contact::markForArchival($contact);
1485                         return -10;
1486                 }
1487
1488                 if (strpos($xml, '<?xml') === false) {
1489                         Logger::log('No valid XML returned from ' . $contact['id'] . ' - ' . $dest_url);
1490                         Logger::log('Returned XML: ' . $xml, Logger::DATA);
1491                         Contact::markForArchival($contact);
1492                         return 3;
1493                 }
1494
1495                 $res = XML::parseString($xml);
1496
1497                 if (empty($res->status)) {
1498                         Contact::markForArchival($contact);
1499                         return -23;
1500                 }
1501
1502                 if (!empty($res->message)) {
1503                         Logger::log('Transmit to ' . $dest_url . ' returned status '.$res->status.' - '.$res->message, Logger::DEBUG);
1504                 }
1505
1506                 if (($res->status >= 200) && ($res->status <= 299)) {
1507                         Contact::unmarkForArchival($contact);
1508                 }
1509
1510                 return intval($res->status);
1511         }
1512
1513         /**
1514          * @brief Add new birthday event for this person
1515          *
1516          * @param array  $contact  Contact record
1517          * @param string $birthday Birthday of the contact
1518          * @return void
1519          * @todo Add array type-hint for $contact
1520          */
1521         private static function birthdayEvent($contact, $birthday)
1522         {
1523                 // Check for duplicates
1524                 $condition = ['uid' => $contact['uid'], 'cid' => $contact['id'],
1525                         'start' => DateTimeFormat::utc($birthday), 'type' => 'birthday'];
1526                 if (DBA::exists('event', $condition)) {
1527                         return;
1528                 }
1529
1530                 Logger::log('updating birthday: ' . $birthday . ' for contact ' . $contact['id']);
1531
1532                 $bdtext = L10n::t('%s\'s birthday', $contact['name']);
1533                 $bdtext2 = L10n::t('Happy Birthday %s', ' [url=' . $contact['url'] . ']' . $contact['name'] . '[/url]');
1534
1535                 $r = q(
1536                         "INSERT INTO `event` (`uid`,`cid`,`created`,`edited`,`start`,`finish`,`summary`,`desc`,`type`)
1537                         VALUES ( %d, %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s') ",
1538                         intval($contact['uid']),
1539                         intval($contact['id']),
1540                         DBA::escape(DateTimeFormat::utcNow()),
1541                         DBA::escape(DateTimeFormat::utcNow()),
1542                         DBA::escape(DateTimeFormat::utc($birthday)),
1543                         DBA::escape(DateTimeFormat::utc($birthday . ' + 1 day ')),
1544                         DBA::escape($bdtext),
1545                         DBA::escape($bdtext2),
1546                         DBA::escape('birthday')
1547                 );
1548         }
1549
1550         /**
1551          * @brief Fetch the author data from head or entry items
1552          *
1553          * @param object $xpath     XPath object
1554          * @param object $context   In which context should the data be searched
1555          * @param array  $importer  Record of the importer user mixed with contact of the content
1556          * @param string $element   Element name from which the data is fetched
1557          * @param bool   $onlyfetch Should the data only be fetched or should it update the contact record as well
1558          * @param string $xml       optional, default empty
1559          *
1560          * @return array Relevant data of the author
1561          * @todo Find good type-hints for all parameter
1562          */
1563         private static function fetchauthor($xpath, $context, $importer, $element, $onlyfetch, $xml = "")
1564         {
1565                 $author = [];
1566                 $author["name"] = XML::getFirstNodeValue($xpath, $element."/atom:name/text()", $context);
1567                 $author["link"] = XML::getFirstNodeValue($xpath, $element."/atom:uri/text()", $context);
1568
1569                 $fields = ['id', 'uid', 'url', 'network', 'avatar-date', 'avatar', 'name-date', 'uri-date', 'addr',
1570                         'name', 'nick', 'about', 'location', 'keywords', 'xmpp', 'bdyear', 'bd', 'hidden', 'contact-type'];
1571                 $condition = ["`uid` = ? AND `nurl` = ? AND `network` != ?",
1572                         $importer["importer_uid"], normalise_link($author["link"]), Protocol::STATUSNET];
1573                 $contact_old = DBA::selectFirst('contact', $fields, $condition);
1574
1575                 if (DBA::isResult($contact_old)) {
1576                         $author["contact-id"] = $contact_old["id"];
1577                         $author["network"] = $contact_old["network"];
1578                 } else {
1579                         if (!$onlyfetch) {
1580                                 Logger::log("Contact ".$author["link"]." wasn't found for user ".$importer["importer_uid"]." XML: ".$xml, Logger::DEBUG);
1581                         }
1582
1583                         $author["contact-unknown"] = true;
1584                         $author["contact-id"] = $importer["id"];
1585                         $author["network"] = $importer["network"];
1586                         $onlyfetch = true;
1587                 }
1588
1589                 // Until now we aren't serving different sizes - but maybe later
1590                 $avatarlist = [];
1591                 /// @todo check if "avatar" or "photo" would be the best field in the specification
1592                 $avatars = $xpath->query($element . "/atom:link[@rel='avatar']", $context);
1593                 foreach ($avatars as $avatar) {
1594                         $href = "";
1595                         $width = 0;
1596                         foreach ($avatar->attributes as $attributes) {
1597                                 /// @TODO Rewrite these similar if() to one switch
1598                                 if ($attributes->name == "href") {
1599                                         $href = $attributes->textContent;
1600                                 }
1601                                 if ($attributes->name == "width") {
1602                                         $width = $attributes->textContent;
1603                                 }
1604                                 if ($attributes->name == "updated") {
1605                                         $author["avatar-date"] = $attributes->textContent;
1606                                 }
1607                         }
1608                         if (($width > 0) && ($href != "")) {
1609                                 $avatarlist[$width] = $href;
1610                         }
1611                 }
1612
1613                 if (count($avatarlist) > 0) {
1614                         krsort($avatarlist);
1615                         $author["avatar"] = current($avatarlist);
1616                 }
1617
1618                 if (empty($author['avatar']) && !empty($author['link'])) {
1619                         $cid = Contact::getIdForURL($author['link'], 0);
1620                         if (!empty($cid)) {
1621                                 $contact = DBA::selectFirst('contact', ['avatar'], ['id' => $cid]);
1622                                 if (DBA::isResult($contact)) {
1623                                         $author['avatar'] = $contact['avatar'];
1624                                 }
1625                         }
1626                 }
1627
1628                 if (empty($author['avatar'])) {
1629                         Logger::log('Empty author: ' . $xml);
1630                 }
1631
1632                 if (DBA::isResult($contact_old) && !$onlyfetch) {
1633                         Logger::log("Check if contact details for contact " . $contact_old["id"] . " (" . $contact_old["nick"] . ") have to be updated.", Logger::DEBUG);
1634
1635                         $poco = ["url" => $contact_old["url"]];
1636
1637                         // When was the last change to name or uri?
1638                         $name_element = $xpath->query($element . "/atom:name", $context)->item(0);
1639                         foreach ($name_element->attributes as $attributes) {
1640                                 if ($attributes->name == "updated") {
1641                                         $poco["name-date"] = $attributes->textContent;
1642                                 }
1643                         }
1644
1645                         $link_element = $xpath->query($element . "/atom:link", $context)->item(0);
1646                         foreach ($link_element->attributes as $attributes) {
1647                                 if ($attributes->name == "updated") {
1648                                         $poco["uri-date"] = $attributes->textContent;
1649                                 }
1650                         }
1651
1652                         // Update contact data
1653                         $value = XML::getFirstNodeValue($xpath, $element . "/dfrn:handle/text()", $context);
1654                         if ($value != "") {
1655                                 $poco["addr"] = $value;
1656                         }
1657
1658                         $value = XML::getFirstNodeValue($xpath, $element . "/poco:displayName/text()", $context);
1659                         if ($value != "") {
1660                                 $poco["name"] = $value;
1661                         }
1662
1663                         $value = XML::getFirstNodeValue($xpath, $element . "/poco:preferredUsername/text()", $context);
1664                         if ($value != "") {
1665                                 $poco["nick"] = $value;
1666                         }
1667
1668                         $value = XML::getFirstNodeValue($xpath, $element . "/poco:note/text()", $context);
1669                         if ($value != "") {
1670                                 $poco["about"] = $value;
1671                         }
1672
1673                         $value = XML::getFirstNodeValue($xpath, $element . "/poco:address/poco:formatted/text()", $context);
1674                         if ($value != "") {
1675                                 $poco["location"] = $value;
1676                         }
1677
1678                         /// @todo Only search for elements with "poco:type" = "xmpp"
1679                         $value = XML::getFirstNodeValue($xpath, $element . "/poco:ims/poco:value/text()", $context);
1680                         if ($value != "") {
1681                                 $poco["xmpp"] = $value;
1682                         }
1683
1684                         /// @todo Add support for the following fields that we don't support by now in the contact table:
1685                         /// - poco:utcOffset
1686                         /// - poco:urls
1687                         /// - poco:locality
1688                         /// - poco:region
1689                         /// - poco:country
1690
1691                         // If the "hide" element is present then the profile isn't searchable.
1692                         $hide = intval(XML::getFirstNodeValue($xpath, $element . "/dfrn:hide/text()", $context) == "true");
1693
1694                         Logger::log("Hidden status for contact " . $contact_old["url"] . ": " . $hide, Logger::DEBUG);
1695
1696                         // If the contact isn't searchable then set the contact to "hidden".
1697                         // Problem: This can be manually overridden by the user.
1698                         if ($hide) {
1699                                 $contact_old["hidden"] = true;
1700                         }
1701
1702                         // Save the keywords into the contact table
1703                         $tags = [];
1704                         $tagelements = $xpath->evaluate($element . "/poco:tags/text()", $context);
1705                         foreach ($tagelements as $tag) {
1706                                 $tags[$tag->nodeValue] = $tag->nodeValue;
1707                         }
1708
1709                         if (count($tags)) {
1710                                 $poco["keywords"] = implode(", ", $tags);
1711                         }
1712
1713                         // "dfrn:birthday" contains the birthday converted to UTC
1714                         $birthday = XML::getFirstNodeValue($xpath, $element . "/poco:birthday/text()", $context);
1715
1716                         if (strtotime($birthday) > time()) {
1717                                 $bd_timestamp = strtotime($birthday);
1718
1719                                 $poco["bdyear"] = date("Y", $bd_timestamp);
1720                         }
1721
1722                         // "poco:birthday" is the birthday in the format "yyyy-mm-dd"
1723                         $value = XML::getFirstNodeValue($xpath, $element . "/poco:birthday/text()", $context);
1724
1725                         if (!in_array($value, ["", "0000-00-00", "0001-01-01"])) {
1726                                 $bdyear = date("Y");
1727                                 $value = str_replace("0000", $bdyear, $value);
1728
1729                                 if (strtotime($value) < time()) {
1730                                         $value = str_replace($bdyear, $bdyear + 1, $value);
1731                                         $bdyear = $bdyear + 1;
1732                                 }
1733
1734                                 $poco["bd"] = $value;
1735                         }
1736
1737                         $contact = array_merge($contact_old, $poco);
1738
1739                         if ($contact_old["bdyear"] != $contact["bdyear"]) {
1740                                 self::birthdayEvent($contact, $birthday);
1741                         }
1742
1743                         // Get all field names
1744                         $fields = [];
1745                         foreach ($contact_old as $field => $data) {
1746                                 $fields[$field] = $data;
1747                         }
1748
1749                         unset($fields["id"]);
1750                         unset($fields["uid"]);
1751                         unset($fields["url"]);
1752                         unset($fields["avatar-date"]);
1753                         unset($fields["avatar"]);
1754                         unset($fields["name-date"]);
1755                         unset($fields["uri-date"]);
1756
1757                         $update = false;
1758                         // Update check for this field has to be done differently
1759                         $datefields = ["name-date", "uri-date"];
1760                         foreach ($datefields as $field) {
1761                                 // The date fields arrives as '2018-07-17T10:44:45Z' - the database return '2018-07-17 10:44:45'
1762                                 // The fields have to be in the same format to be comparable, since strtotime does add timezones.
1763                                 $contact[$field] = DateTimeFormat::utc($contact[$field]);
1764
1765                                 if (strtotime($contact[$field]) > strtotime($contact_old[$field])) {
1766                                         Logger::log("Difference for contact " . $contact["id"] . " in field '" . $field . "'. New value: '" . $contact[$field] . "', old value '" . $contact_old[$field] . "'", Logger::DEBUG);
1767                                         $update = true;
1768                                 }
1769                         }
1770
1771                         foreach ($fields as $field => $data) {
1772                                 if ($contact[$field] != $contact_old[$field]) {
1773                                         Logger::log("Difference for contact " . $contact["id"] . " in field '" . $field . "'. New value: '" . $contact[$field] . "', old value '" . $contact_old[$field] . "'", Logger::DEBUG);
1774                                         $update = true;
1775                                 }
1776                         }
1777
1778                         if ($update) {
1779                                 Logger::log("Update contact data for contact " . $contact["id"] . " (" . $contact["nick"] . ")", Logger::DEBUG);
1780
1781                                 q(
1782                                         "UPDATE `contact` SET `name` = '%s', `nick` = '%s', `about` = '%s', `location` = '%s',
1783                                         `addr` = '%s', `keywords` = '%s', `bdyear` = '%s', `bd` = '%s', `hidden` = %d,
1784                                         `xmpp` = '%s', `name-date`  = '%s', `uri-date` = '%s'
1785                                         WHERE `id` = %d AND `network` = '%s'",
1786                                         DBA::escape($contact["name"]), DBA::escape($contact["nick"]), DBA::escape($contact["about"]),   DBA::escape($contact["location"]),
1787                                         DBA::escape($contact["addr"]), DBA::escape($contact["keywords"]), DBA::escape($contact["bdyear"]),
1788                                         DBA::escape($contact["bd"]), intval($contact["hidden"]), DBA::escape($contact["xmpp"]),
1789                                         DBA::escape(DateTimeFormat::utc($contact["name-date"])), DBA::escape(DateTimeFormat::utc($contact["uri-date"])),
1790                                         intval($contact["id"]), DBA::escape($contact["network"])
1791                                 );
1792                         }
1793
1794                         Contact::updateAvatar(
1795                                 $author['avatar'],
1796                                 $importer['importer_uid'],
1797                                 $contact['id'],
1798                                 (strtotime($contact['avatar-date']) > strtotime($contact_old['avatar-date']) || ($author['avatar'] != $contact_old['avatar']))
1799                         );
1800
1801                         /*
1802                          * The generation is a sign for the reliability of the provided data.
1803                          * It is used in the socgraph.php to prevent that old contact data
1804                          * that was relayed over several servers can overwrite contact
1805                          * data that we received directly.
1806                          */
1807
1808                         $poco["generation"] = 2;
1809                         $poco["photo"] = $author["avatar"];
1810                         $poco["hide"] = $hide;
1811                         $poco["contact-type"] = $contact["contact-type"];
1812                         $gcid = GContact::update($poco);
1813
1814                         GContact::link($gcid, $importer["importer_uid"], $contact["id"]);
1815                 }
1816
1817                 return $author;
1818         }
1819
1820         /**
1821          * @brief Transforms activity objects into an XML string
1822          *
1823          * @param object $xpath    XPath object
1824          * @param object $activity Activity object
1825          * @param string $element  element name
1826          *
1827          * @return string XML string
1828          * @todo Find good type-hints for all parameter
1829          */
1830         private static function transformActivity($xpath, $activity, $element)
1831         {
1832                 if (!is_object($activity)) {
1833                         return "";
1834                 }
1835
1836                 $obj_doc = new DOMDocument("1.0", "utf-8");
1837                 $obj_doc->formatOutput = true;
1838
1839                 $obj_element = $obj_doc->createElementNS(NAMESPACE_ATOM1, $element);
1840
1841                 $activity_type = $xpath->query("activity:object-type/text()", $activity)->item(0)->nodeValue;
1842                 XML::addElement($obj_doc, $obj_element, "type", $activity_type);
1843
1844                 $id = $xpath->query("atom:id", $activity)->item(0);
1845                 if (is_object($id)) {
1846                         $obj_element->appendChild($obj_doc->importNode($id, true));
1847                 }
1848
1849                 $title = $xpath->query("atom:title", $activity)->item(0);
1850                 if (is_object($title)) {
1851                         $obj_element->appendChild($obj_doc->importNode($title, true));
1852                 }
1853
1854                 $links = $xpath->query("atom:link", $activity);
1855                 if (is_object($links)) {
1856                         foreach ($links as $link) {
1857                                 $obj_element->appendChild($obj_doc->importNode($link, true));
1858                         }
1859                 }
1860
1861                 $content = $xpath->query("atom:content", $activity)->item(0);
1862                 if (is_object($content)) {
1863                         $obj_element->appendChild($obj_doc->importNode($content, true));
1864                 }
1865
1866                 $obj_doc->appendChild($obj_element);
1867
1868                 $objxml = $obj_doc->saveXML($obj_element);
1869
1870                 /// @todo This isn't totally clean. We should find a way to transform the namespaces
1871                 $objxml = str_replace("<".$element.' xmlns="http://www.w3.org/2005/Atom">', "<".$element.">", $objxml);
1872                 return($objxml);
1873         }
1874
1875         /**
1876          * @brief Processes the mail elements
1877          *
1878          * @param object $xpath    XPath object
1879          * @param object $mail     mail elements
1880          * @param array  $importer Record of the importer user mixed with contact of the content
1881          * @return void
1882          * @todo Find good type-hints for all parameter
1883          */
1884         private static function processMail($xpath, $mail, $importer)
1885         {
1886                 Logger::log("Processing mails");
1887
1888                 /// @TODO Rewrite this to one statement
1889                 $msg = [];
1890                 $msg["uid"] = $importer["importer_uid"];
1891                 $msg["from-name"] = $xpath->query("dfrn:sender/dfrn:name/text()", $mail)->item(0)->nodeValue;
1892                 $msg["from-url"] = $xpath->query("dfrn:sender/dfrn:uri/text()", $mail)->item(0)->nodeValue;
1893                 $msg["from-photo"] = $xpath->query("dfrn:sender/dfrn:avatar/text()", $mail)->item(0)->nodeValue;
1894                 $msg["contact-id"] = $importer["id"];
1895                 $msg["uri"] = $xpath->query("dfrn:id/text()", $mail)->item(0)->nodeValue;
1896                 $msg["parent-uri"] = $xpath->query("dfrn:in-reply-to/text()", $mail)->item(0)->nodeValue;
1897                 $msg["created"] = DateTimeFormat::utc($xpath->query("dfrn:sentdate/text()", $mail)->item(0)->nodeValue);
1898                 $msg["title"] = $xpath->query("dfrn:subject/text()", $mail)->item(0)->nodeValue;
1899                 $msg["body"] = $xpath->query("dfrn:content/text()", $mail)->item(0)->nodeValue;
1900                 $msg["seen"] = 0;
1901                 $msg["replied"] = 0;
1902
1903                 DBA::insert('mail', $msg);
1904
1905                 $msg["id"] = DBA::lastInsertId();
1906
1907                 // send notifications.
1908                 /// @TODO Arange this mess
1909                 $notif_params = [
1910                         "type" => NOTIFY_MAIL,
1911                         "notify_flags" => $importer["notify-flags"],
1912                         "language" => $importer["language"],
1913                         "to_name" => $importer["username"],
1914                         "to_email" => $importer["email"],
1915                         "uid" => $importer["importer_uid"],
1916                         "item" => $msg,
1917                         "source_name" => $msg["from-name"],
1918                         "source_link" => $importer["url"],
1919                         "source_photo" => $importer["thumb"],
1920                         "verb" => ACTIVITY_POST,
1921                         "otype" => "mail"
1922                 ];
1923
1924                 notification($notif_params);
1925
1926                 Logger::log("Mail is processed, notification was sent.");
1927         }
1928
1929         /**
1930          * @brief Processes the suggestion elements
1931          *
1932          * @param object $xpath      XPath object
1933          * @param object $suggestion suggestion elements
1934          * @param array  $importer   Record of the importer user mixed with contact of the content
1935          * @return boolean
1936          * @todo Find good type-hints for all parameter
1937          */
1938         private static function processSuggestion($xpath, $suggestion, $importer)
1939         {
1940                 $a = get_app();
1941
1942                 Logger::log("Processing suggestions");
1943
1944                 /// @TODO Rewrite this to one statement
1945                 $suggest = [];
1946                 $suggest["uid"] = $importer["importer_uid"];
1947                 $suggest["cid"] = $importer["id"];
1948                 $suggest["url"] = $xpath->query("dfrn:url/text()", $suggestion)->item(0)->nodeValue;
1949                 $suggest["name"] = $xpath->query("dfrn:name/text()", $suggestion)->item(0)->nodeValue;
1950                 $suggest["photo"] = $xpath->query("dfrn:photo/text()", $suggestion)->item(0)->nodeValue;
1951                 $suggest["request"] = $xpath->query("dfrn:request/text()", $suggestion)->item(0)->nodeValue;
1952                 $suggest["body"] = $xpath->query("dfrn:note/text()", $suggestion)->item(0)->nodeValue;
1953
1954                 // Does our member already have a friend matching this description?
1955
1956                 /*
1957                  * The valid result means the friend we're about to send a friend
1958                  * suggestion already has them in their contact, which means no further
1959                  * action is required.
1960                  *
1961                  * @see https://github.com/friendica/friendica/pull/3254#discussion_r107315246
1962                  */
1963                 $condition = ['name' => $suggest["name"], 'nurl' => normalise_link($suggest["url"]),
1964                         'uid' => $suggest["uid"]];
1965                 if (DBA::exists('contact', $condition)) {
1966                         return false;
1967                 }
1968
1969                 // Do we already have an fcontact record for this person?
1970
1971                 $fid = 0;
1972                 $condition = ['url' => $suggest["url"], 'name' => $suggest["name"], 'request' => $suggest["request"]];
1973                 $fcontact = DBA::selectFirst('fcontact', ['id'], $condition);
1974                 if (DBA::isResult($fcontact)) {
1975                         $fid = $fcontact["id"];
1976
1977                         // OK, we do. Do we already have an introduction for this person?
1978                         if (DBA::exists('intro', ['uid' => $suggest["uid"], 'fid' => $fid])) {
1979                                 /*
1980                                  * The valid result means the friend we're about to send a friend
1981                                  * suggestion already has them in their contact, which means no further
1982                                  * action is required.
1983                                  *
1984                                  * @see https://github.com/friendica/friendica/pull/3254#discussion_r107315246
1985                                  */
1986                                 return false;
1987                         }
1988                 }
1989                 if (!$fid) {
1990                         $r = q(
1991                                 "INSERT INTO `fcontact` (`name`,`url`,`photo`,`request`) VALUES ('%s', '%s', '%s', '%s')",
1992                                 DBA::escape($suggest["name"]),
1993                                 DBA::escape($suggest["url"]),
1994                                 DBA::escape($suggest["photo"]),
1995                                 DBA::escape($suggest["request"])
1996                         );
1997                 }
1998
1999                 $condition = ['url' => $suggest["url"], 'name' => $suggest["name"], 'request' => $suggest["request"]];
2000                 $fcontact = DBA::selectFirst('fcontact', ['id'], $condition);
2001
2002                 /*
2003                  * If no record in fcontact is found, below INSERT statement will not
2004                  * link an introduction to it.
2005                  */
2006                 if (!DBA::isResult($fcontact)) {
2007                         // Database record did not get created. Quietly give up.
2008                         killme();
2009                 }
2010
2011                 $fid = $r[0]["id"];
2012
2013                 $hash = Strings::getRandomHex();
2014
2015                 $r = q(
2016                         "INSERT INTO `intro` (`uid`, `fid`, `contact-id`, `note`, `hash`, `datetime`, `blocked`)
2017                         VALUES(%d, %d, %d, '%s', '%s', '%s', %d)",
2018                         intval($suggest["uid"]),
2019                         intval($fid),
2020                         intval($suggest["cid"]),
2021                         DBA::escape($suggest["body"]),
2022                         DBA::escape($hash),
2023                         DBA::escape(DateTimeFormat::utcNow()),
2024                         intval(0)
2025                 );
2026
2027                 notification(
2028                         [
2029                                 "type"         => NOTIFY_SUGGEST,
2030                                 "notify_flags" => $importer["notify-flags"],
2031                                 "language"     => $importer["language"],
2032                                 "to_name"      => $importer["username"],
2033                                 "to_email"     => $importer["email"],
2034                                 "uid"          => $importer["importer_uid"],
2035                                 "item"         => $suggest,
2036                                 "link"         => System::baseUrl()."/notifications/intros",
2037                                 "source_name"  => $importer["name"],
2038                                 "source_link"  => $importer["url"],
2039                                 "source_photo" => $importer["photo"],
2040                                 "verb"         => ACTIVITY_REQ_FRIEND,
2041                                 "otype"        => "intro"]
2042                 );
2043
2044                 return true;
2045         }
2046
2047         /**
2048          * @brief Processes the relocation elements
2049          *
2050          * @param object $xpath      XPath object
2051          * @param object $relocation relocation elements
2052          * @param array  $importer   Record of the importer user mixed with contact of the content
2053          * @return boolean
2054          * @todo Find good type-hints for all parameter
2055          */
2056         private static function processRelocation($xpath, $relocation, $importer)
2057         {
2058                 Logger::log("Processing relocations");
2059
2060                 /// @TODO Rewrite this to one statement
2061                 $relocate = [];
2062                 $relocate["uid"] = $importer["importer_uid"];
2063                 $relocate["cid"] = $importer["id"];
2064                 $relocate["url"] = $xpath->query("dfrn:url/text()", $relocation)->item(0)->nodeValue;
2065                 $relocate["addr"] = $xpath->query("dfrn:addr/text()", $relocation)->item(0)->nodeValue;
2066                 $relocate["name"] = $xpath->query("dfrn:name/text()", $relocation)->item(0)->nodeValue;
2067                 $relocate["avatar"] = $xpath->query("dfrn:avatar/text()", $relocation)->item(0)->nodeValue;
2068                 $relocate["photo"] = $xpath->query("dfrn:photo/text()", $relocation)->item(0)->nodeValue;
2069                 $relocate["thumb"] = $xpath->query("dfrn:thumb/text()", $relocation)->item(0)->nodeValue;
2070                 $relocate["micro"] = $xpath->query("dfrn:micro/text()", $relocation)->item(0)->nodeValue;
2071                 $relocate["request"] = $xpath->query("dfrn:request/text()", $relocation)->item(0)->nodeValue;
2072                 $relocate["confirm"] = $xpath->query("dfrn:confirm/text()", $relocation)->item(0)->nodeValue;
2073                 $relocate["notify"] = $xpath->query("dfrn:notify/text()", $relocation)->item(0)->nodeValue;
2074                 $relocate["poll"] = $xpath->query("dfrn:poll/text()", $relocation)->item(0)->nodeValue;
2075                 $relocate["sitepubkey"] = $xpath->query("dfrn:sitepubkey/text()", $relocation)->item(0)->nodeValue;
2076
2077                 if (($relocate["avatar"] == "") && ($relocate["photo"] != "")) {
2078                         $relocate["avatar"] = $relocate["photo"];
2079                 }
2080
2081                 if ($relocate["addr"] == "") {
2082                         $relocate["addr"] = preg_replace("=(https?://)(.*)/profile/(.*)=ism", "$3@$2", $relocate["url"]);
2083                 }
2084
2085                 // update contact
2086                 $r = q(
2087                         "SELECT `photo`, `url` FROM `contact` WHERE `id` = %d AND `uid` = %d",
2088                         intval($importer["id"]),
2089                         intval($importer["importer_uid"])
2090                 );
2091
2092                 if (!DBA::isResult($r)) {
2093                         Logger::log("Query failed to execute, no result returned in " . __FUNCTION__);
2094                         return false;
2095                 }
2096
2097                 $old = $r[0];
2098
2099                 // Update the gcontact entry
2100                 $relocate["server_url"] = preg_replace("=(https?://)(.*)/profile/(.*)=ism", "$1$2", $relocate["url"]);
2101
2102                 $fields = ['name' => $relocate["name"], 'photo' => $relocate["avatar"],
2103                         'url' => $relocate["url"], 'nurl' => normalise_link($relocate["url"]),
2104                         'addr' => $relocate["addr"], 'connect' => $relocate["addr"],
2105                         'notify' => $relocate["notify"], 'server_url' => $relocate["server_url"]];
2106                 DBA::update('gcontact', $fields, ['nurl' => normalise_link($old["url"])]);
2107
2108                 // Update the contact table. We try to find every entry.
2109                 $fields = ['name' => $relocate["name"], 'avatar' => $relocate["avatar"],
2110                         'url' => $relocate["url"], 'nurl' => normalise_link($relocate["url"]),
2111                         'addr' => $relocate["addr"], 'request' => $relocate["request"],
2112                         'confirm' => $relocate["confirm"], 'notify' => $relocate["notify"],
2113                         'poll' => $relocate["poll"], 'site-pubkey' => $relocate["sitepubkey"]];
2114                 $condition = ["(`id` = ?) OR (`nurl` = ?)", $importer["id"], normalise_link($old["url"])];
2115
2116                 DBA::update('contact', $fields, $condition);
2117
2118                 Contact::updateAvatar($relocate["avatar"], $importer["importer_uid"], $importer["id"], true);
2119
2120                 Logger::log('Contacts are updated.');
2121
2122                 /// @TODO
2123                 /// merge with current record, current contents have priority
2124                 /// update record, set url-updated
2125                 /// update profile photos
2126                 /// schedule a scan?
2127                 return true;
2128         }
2129
2130         /**
2131          * @brief Updates an item
2132          *
2133          * @param array $current   the current item record
2134          * @param array $item      the new item record
2135          * @param array $importer  Record of the importer user mixed with contact of the content
2136          * @param int   $entrytype Is it a toplevel entry, a comment or a relayed comment?
2137          * @return mixed
2138          * @todo set proper type-hints (array?)
2139          */
2140         private static function updateContent($current, $item, $importer, $entrytype)
2141         {
2142                 $changed = false;
2143
2144                 if (self::isEditedTimestampNewer($current, $item)) {
2145                         // do not accept (ignore) an earlier edit than one we currently have.
2146                         if (DateTimeFormat::utc($item["edited"]) < $current["edited"]) {
2147                                 return false;
2148                         }
2149
2150                         $fields = ['title' => defaults($item, 'title', ''), 'body' => defaults($item, 'body', ''),
2151                                         'tag' => defaults($item, 'tag', ''), 'changed' => DateTimeFormat::utcNow(),
2152                                         'edited' => DateTimeFormat::utc($item["edited"])];
2153
2154                         $condition = ["`uri` = ? AND `uid` IN (0, ?)", $item["uri"], $importer["importer_uid"]];
2155                         Item::update($fields, $condition);
2156
2157                         $changed = true;
2158                 }
2159                 return $changed;
2160         }
2161
2162         /**
2163          * @brief Detects the entry type of the item
2164          *
2165          * @param array $importer Record of the importer user mixed with contact of the content
2166          * @param array $item     the new item record
2167          *
2168          * @return int Is it a toplevel entry, a comment or a relayed comment?
2169          * @todo set proper type-hints (array?)
2170          */
2171         private static function getEntryType($importer, $item)
2172         {
2173                 if ($item["parent-uri"] != $item["uri"]) {
2174                         $community = false;
2175
2176                         if ($importer["page-flags"] == Contact::PAGE_COMMUNITY || $importer["page-flags"] == Contact::PAGE_PRVGROUP) {
2177                                 $sql_extra = "";
2178                                 $community = true;
2179                                 Logger::log("possible community action");
2180                         } else {
2181                                 $sql_extra = " AND `contact`.`self` AND `item`.`wall` ";
2182                         }
2183
2184                         // was the top-level post for this action written by somebody on this site?
2185                         // Specifically, the recipient?
2186
2187                         $is_a_remote_action = false;
2188
2189                         $parent = Item::selectFirst(['parent-uri'], ['uri' => $item["parent-uri"]]);
2190                         if (DBA::isResult($parent)) {
2191                                 $r = q(
2192                                         "SELECT `item`.`forum_mode`, `item`.`wall` FROM `item`
2193                                         INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
2194                                         WHERE `item`.`uri` = '%s' AND (`item`.`parent-uri` = '%s' OR `item`.`thr-parent` = '%s')
2195                                         AND `item`.`uid` = %d
2196                                         $sql_extra
2197                                         LIMIT 1",
2198                                         DBA::escape($parent["parent-uri"]),
2199                                         DBA::escape($parent["parent-uri"]),
2200                                         DBA::escape($parent["parent-uri"]),
2201                                         intval($importer["importer_uid"])
2202                                 );
2203                                 if (DBA::isResult($r)) {
2204                                         $is_a_remote_action = true;
2205                                 }
2206                         }
2207
2208                         /*
2209                          * Does this have the characteristics of a community or private group action?
2210                          * If it's an action to a wall post on a community/prvgroup page it's a
2211                          * valid community action. Also forum_mode makes it valid for sure.
2212                          * If neither, it's not.
2213                          */
2214                         if ($is_a_remote_action && $community && (!$r[0]["forum_mode"]) && (!$r[0]["wall"])) {
2215                                 $is_a_remote_action = false;
2216                                 Logger::log("not a community action");
2217                         }
2218
2219                         if ($is_a_remote_action) {
2220                                 return DFRN::REPLY_RC;
2221                         } else {
2222                                 return DFRN::REPLY;
2223                         }
2224                 } else {
2225                         return DFRN::TOP_LEVEL;
2226                 }
2227         }
2228
2229         /**
2230          * @brief Send a "poke"
2231          *
2232          * @param array $item      the new item record
2233          * @param array $importer  Record of the importer user mixed with contact of the content
2234          * @param int   $posted_id The record number of item record that was just posted
2235          * @return void
2236          * @todo set proper type-hints (array?)
2237          */
2238         private static function doPoke($item, $importer, $posted_id)
2239         {
2240                 $verb = urldecode(substr($item["verb"], strpos($item["verb"], "#")+1));
2241                 if (!$verb) {
2242                         return;
2243                 }
2244                 $xo = XML::parseString($item["object"], false);
2245
2246                 if (($xo->type == ACTIVITY_OBJ_PERSON) && ($xo->id)) {
2247                         // somebody was poked/prodded. Was it me?
2248                         foreach ($xo->link as $l) {
2249                                 $atts = $l->attributes();
2250                                 switch ($atts["rel"]) {
2251                                         case "alternate":
2252                                                 $Blink = $atts["href"];
2253                                                 break;
2254                                         default:
2255                                                 break;
2256                                 }
2257                         }
2258
2259                         if ($Blink && link_compare($Blink, System::baseUrl() . "/profile/" . $importer["nickname"])) {
2260                                 $author = DBA::selectFirst('contact', ['name', 'thumb', 'url'], ['id' => $item['author-id']]);
2261
2262                                 $item['id'] = $posted_id;
2263
2264                                 $parent = Item::selectFirst(['id'], ['uri' => $item['parent-uri'], 'uid' => $importer["importer_uid"]]);
2265                                 $item["parent"] = $parent['id'];
2266
2267                                 // send a notification
2268                                 notification(
2269                                         [
2270                                         "type"         => NOTIFY_POKE,
2271                                         "notify_flags" => $importer["notify-flags"],
2272                                         "language"     => $importer["language"],
2273                                         "to_name"      => $importer["username"],
2274                                         "to_email"     => $importer["email"],
2275                                         "uid"          => $importer["importer_uid"],
2276                                         "item"         => $item,
2277                                         "link"         => System::baseUrl()."/display/".urlencode(Item::getGuidById($posted_id)),
2278                                         "source_name"  => $author["name"],
2279                                         "source_link"  => $author["url"],
2280                                         "source_photo" => $author["thumb"],
2281                                         "verb"         => $item["verb"],
2282                                         "otype"        => "person",
2283                                         "activity"     => $verb,
2284                                         "parent"       => $item["parent"]]
2285                                 );
2286                         }
2287                 }
2288         }
2289
2290         /**
2291          * @brief Processes several actions, depending on the verb
2292          *
2293          * @param int   $entrytype Is it a toplevel entry, a comment or a relayed comment?
2294          * @param array $importer  Record of the importer user mixed with contact of the content
2295          * @param array $item      the new item record
2296          * @param bool  $is_like   Is the verb a "like"?
2297          *
2298          * @return bool Should the processing of the entries be continued?
2299          * @todo set proper type-hints (array?)
2300          */
2301         private static function processVerbs($entrytype, $importer, &$item, &$is_like)
2302         {
2303                 Logger::log("Process verb ".$item["verb"]." and object-type ".$item["object-type"]." for entrytype ".$entrytype, Logger::DEBUG);
2304
2305                 if (($entrytype == DFRN::TOP_LEVEL)) {
2306                         // The filling of the the "contact" variable is done for legcy reasons
2307                         // The functions below are partly used by ostatus.php as well - where we have this variable
2308                         $r = q("SELECT * FROM `contact` WHERE `id` = %d", intval($importer["id"]));
2309                         $contact = $r[0];
2310                         $nickname = $contact["nick"];
2311
2312                         // Big question: Do we need these functions? They were part of the "consume_feed" function.
2313                         // This function once was responsible for DFRN and OStatus.
2314                         if (activity_match($item["verb"], ACTIVITY_FOLLOW)) {
2315                                 Logger::log("New follower");
2316                                 Contact::addRelationship($importer, $contact, $item, $nickname);
2317                                 return false;
2318                         }
2319                         if (activity_match($item["verb"], ACTIVITY_UNFOLLOW)) {
2320                                 Logger::log("Lost follower");
2321                                 Contact::removeFollower($importer, $contact, $item);
2322                                 return false;
2323                         }
2324                         if (activity_match($item["verb"], ACTIVITY_REQ_FRIEND)) {
2325                                 Logger::log("New friend request");
2326                                 Contact::addRelationship($importer, $contact, $item, $nickname, true);
2327                                 return false;
2328                         }
2329                         if (activity_match($item["verb"], ACTIVITY_UNFRIEND)) {
2330                                 Logger::log("Lost sharer");
2331                                 Contact::removeSharer($importer, $contact, $item);
2332                                 return false;
2333                         }
2334                 } else {
2335                         if (($item["verb"] == ACTIVITY_LIKE)
2336                                 || ($item["verb"] == ACTIVITY_DISLIKE)
2337                                 || ($item["verb"] == ACTIVITY_ATTEND)
2338                                 || ($item["verb"] == ACTIVITY_ATTENDNO)
2339                                 || ($item["verb"] == ACTIVITY_ATTENDMAYBE)
2340                         ) {
2341                                 $is_like = true;
2342                                 $item["gravity"] = GRAVITY_ACTIVITY;
2343                                 // only one like or dislike per person
2344                                 // splitted into two queries for performance issues
2345                                 $condition = ['uid' => $item["uid"], 'author-id' => $item["author-id"], 'gravity' => GRAVITY_ACTIVITY,
2346                                         'verb' => $item["verb"], 'parent-uri' => $item["parent-uri"]];
2347                                 if (Item::exists($condition)) {
2348                                         return false;
2349                                 }
2350
2351                                 $condition = ['uid' => $item["uid"], 'author-id' => $item["author-id"], 'gravity' => GRAVITY_ACTIVITY,
2352                                         'verb' => $item["verb"], 'thr-parent' => $item["parent-uri"]];
2353                                 if (Item::exists($condition)) {
2354                                         return false;
2355                                 }
2356
2357                                 // The owner of an activity must be the author
2358                                 $item["owner-name"] = $item["author-name"];
2359                                 $item["owner-link"] = $item["author-link"];
2360                                 $item["owner-avatar"] = $item["author-avatar"];
2361                                 $item["owner-id"] = $item["author-id"];
2362                         } else {
2363                                 $is_like = false;
2364                         }
2365
2366                         if (($item["verb"] == ACTIVITY_TAG) && ($item["object-type"] == ACTIVITY_OBJ_TAGTERM)) {
2367                                 $xo = XML::parseString($item["object"], false);
2368                                 $xt = XML::parseString($item["target"], false);
2369
2370                                 if ($xt->type == ACTIVITY_OBJ_NOTE) {
2371                                         $item_tag = Item::selectFirst(['id', 'tag'], ['uri' => $xt->id, 'uid' => $importer["importer_uid"]]);
2372
2373                                         if (!DBA::isResult($item_tag)) {
2374                                                 Logger::log("Query failed to execute, no result returned in " . __FUNCTION__);
2375                                                 return false;
2376                                         }
2377
2378                                         // extract tag, if not duplicate, add to parent item
2379                                         if ($xo->content) {
2380                                                 if (!stristr($item_tag["tag"], trim($xo->content))) {
2381                                                         $tag = $item_tag["tag"] . (strlen($item_tag["tag"]) ? ',' : '') . '#[url=' . $xo->id . ']'. $xo->content . '[/url]';
2382                                                         Item::update(['tag' => $tag], ['id' => $item_tag["id"]]);
2383                                                 }
2384                                         }
2385                                 }
2386                         }
2387                 }
2388                 return true;
2389         }
2390
2391         /**
2392          * @brief Processes the link elements
2393          *
2394          * @param object $links link elements
2395          * @param array  $item  the item record
2396          * @return void
2397          * @todo set proper type-hints
2398          */
2399         private static function parseLinks($links, &$item)
2400         {
2401                 $rel = "";
2402                 $href = "";
2403                 $type = "";
2404                 $length = "0";
2405                 $title = "";
2406                 foreach ($links as $link) {
2407                         foreach ($link->attributes as $attributes) {
2408                                 switch ($attributes->name) {
2409                                         case "href"  : $href   = $attributes->textContent; break;
2410                                         case "rel"   : $rel    = $attributes->textContent; break;
2411                                         case "type"  : $type   = $attributes->textContent; break;
2412                                         case "length": $length = $attributes->textContent; break;
2413                                         case "title" : $title  = $attributes->textContent; break;
2414                                 }
2415                         }
2416                         if (($rel != "") && ($href != "")) {
2417                                 switch ($rel) {
2418                                         case "alternate":
2419                                                 $item["plink"] = $href;
2420                                                 break;
2421                                         case "enclosure":
2422                                                 $enclosure = $href;
2423
2424                                                 if (!empty($item["attach"])) {
2425                                                         $item["attach"] .= ",";
2426                                                 } else {
2427                                                         $item["attach"] = "";
2428                                                 }
2429
2430                                                 $item["attach"] .= '[attach]href="' . $href . '" length="' . $length . '" type="' . $type . '" title="' . $title . '"[/attach]';
2431                                                 break;
2432                                 }
2433                         }
2434                 }
2435         }
2436
2437         /**
2438          * @brief Processes the entry elements which contain the items and comments
2439          *
2440          * @param array  $header   Array of the header elements that always stay the same
2441          * @param object $xpath    XPath object
2442          * @param object $entry    entry elements
2443          * @param array  $importer Record of the importer user mixed with contact of the content
2444          * @param object $xml      xml
2445          * @return void
2446          * @todo Add type-hints
2447          */
2448         private static function processEntry($header, $xpath, $entry, $importer, $xml)
2449         {
2450                 Logger::log("Processing entries");
2451
2452                 $item = $header;
2453
2454                 $item["protocol"] = Conversation::PARCEL_DFRN;
2455
2456                 $item["source"] = $xml;
2457
2458                 // Get the uri
2459                 $item["uri"] = XML::getFirstNodeValue($xpath, "atom:id/text()", $entry);
2460
2461                 $item["edited"] = XML::getFirstNodeValue($xpath, "atom:updated/text()", $entry);
2462
2463                 $current = Item::selectFirst(['id', 'uid', 'edited', 'body'],
2464                         ['uri' => $item["uri"], 'uid' => $importer["importer_uid"]]
2465                 );
2466                 // Is there an existing item?
2467                 if (DBA::isResult($current) && !self::isEditedTimestampNewer($current, $item)) {
2468                         Logger::log("Item ".$item["uri"]." (".$item['edited'].") already existed.", Logger::DEBUG);
2469                         return;
2470                 }
2471
2472                 // Fetch the owner
2473                 $owner = self::fetchauthor($xpath, $entry, $importer, "dfrn:owner", true, $xml);
2474
2475                 $owner_unknown = (isset($owner["contact-unknown"]) && $owner["contact-unknown"]);
2476
2477                 $item["owner-name"] = $owner["name"];
2478                 $item["owner-link"] = $owner["link"];
2479                 $item["owner-avatar"] = $owner["avatar"];
2480                 $item["owner-id"] = Contact::getIdForURL($owner["link"], 0);
2481
2482                 // fetch the author
2483                 $author = self::fetchauthor($xpath, $entry, $importer, "atom:author", true, $xml);
2484
2485                 $item["author-name"] = $author["name"];
2486                 $item["author-link"] = $author["link"];
2487                 $item["author-avatar"] = $author["avatar"];
2488                 $item["author-id"] = Contact::getIdForURL($author["link"], 0);
2489
2490                 $item["title"] = XML::getFirstNodeValue($xpath, "atom:title/text()", $entry);
2491
2492                 $item["created"] = XML::getFirstNodeValue($xpath, "atom:published/text()", $entry);
2493
2494                 $item["body"] = XML::getFirstNodeValue($xpath, "dfrn:env/text()", $entry);
2495                 $item["body"] = str_replace([' ',"\t","\r","\n"], ['','','',''], $item["body"]);
2496                 // make sure nobody is trying to sneak some html tags by us
2497                 $item["body"] = notags(base64url_decode($item["body"]));
2498
2499                 $item["body"] = BBCode::limitBodySize($item["body"]);
2500
2501                 /// @todo Do we really need this check for HTML elements? (It was copied from the old function)
2502                 if ((strpos($item['body'], '<') !== false) && (strpos($item['body'], '>') !== false)) {
2503                         $base_url = get_app()->getBaseURL();
2504                         $item['body'] = HTML::relToAbs($item['body'], $base_url);
2505
2506                         $item['body'] = HTML::toBBCodeVideo($item['body']);
2507
2508                         $item['body'] = OEmbed::HTML2BBCode($item['body']);
2509
2510                         $config = HTMLPurifier_Config::createDefault();
2511                         $config->set('Cache.DefinitionImpl', null);
2512
2513                         // we shouldn't need a whitelist, because the bbcode converter
2514                         // will strip out any unsupported tags.
2515
2516                         $purifier = new HTMLPurifier($config);
2517                         $item['body'] = $purifier->purify($item['body']);
2518
2519                         $item['body'] = @HTML::toBBCode($item['body']);
2520                 }
2521
2522                 /// @todo We should check for a repeated post and if we know the repeated author.
2523
2524                 // We don't need the content element since "dfrn:env" is always present
2525                 //$item["body"] = $xpath->query("atom:content/text()", $entry)->item(0)->nodeValue;
2526
2527                 $item["location"] = XML::getFirstNodeValue($xpath, "dfrn:location/text()", $entry);
2528
2529                 $item["coord"] = XML::getFirstNodeValue($xpath, "georss:point", $entry);
2530
2531                 $item["private"] = XML::getFirstNodeValue($xpath, "dfrn:private/text()", $entry);
2532
2533                 $item["extid"] = XML::getFirstNodeValue($xpath, "dfrn:extid/text()", $entry);
2534
2535                 if (XML::getFirstNodeValue($xpath, "dfrn:bookmark/text()", $entry) == "true") {
2536                         $item["post-type"] = Item::PT_PAGE;
2537                 }
2538
2539                 $notice_info = $xpath->query("statusnet:notice_info", $entry);
2540                 if ($notice_info && ($notice_info->length > 0)) {
2541                         foreach ($notice_info->item(0)->attributes as $attributes) {
2542                                 if ($attributes->name == "source") {
2543                                         $item["app"] = strip_tags($attributes->textContent);
2544                                 }
2545                         }
2546                 }
2547
2548                 $item["guid"] = XML::getFirstNodeValue($xpath, "dfrn:diaspora_guid/text()", $entry);
2549
2550                 // We store the data from "dfrn:diaspora_signature" in a different table, this is done in "Item::insert"
2551                 $dsprsig = XML::unescape(XML::getFirstNodeValue($xpath, "dfrn:diaspora_signature/text()", $entry));
2552                 if ($dsprsig != "") {
2553                         $item["dsprsig"] = $dsprsig;
2554                 }
2555
2556                 $item["verb"] = XML::getFirstNodeValue($xpath, "activity:verb/text()", $entry);
2557
2558                 if (XML::getFirstNodeValue($xpath, "activity:object-type/text()", $entry) != "") {
2559                         $item["object-type"] = XML::getFirstNodeValue($xpath, "activity:object-type/text()", $entry);
2560                 }
2561
2562                 $object = $xpath->query("activity:object", $entry)->item(0);
2563                 $item["object"] = self::transformActivity($xpath, $object, "object");
2564
2565                 if (trim($item["object"]) != "") {
2566                         $r = XML::parseString($item["object"], false);
2567                         if (isset($r->type)) {
2568                                 $item["object-type"] = $r->type;
2569                         }
2570                 }
2571
2572                 $target = $xpath->query("activity:target", $entry)->item(0);
2573                 $item["target"] = self::transformActivity($xpath, $target, "target");
2574
2575                 $categories = $xpath->query("atom:category", $entry);
2576                 if ($categories) {
2577                         foreach ($categories as $category) {
2578                                 $term = "";
2579                                 $scheme = "";
2580                                 foreach ($category->attributes as $attributes) {
2581                                         if ($attributes->name == "term") {
2582                                                 $term = $attributes->textContent;
2583                                         }
2584
2585                                         if ($attributes->name == "scheme") {
2586                                                 $scheme = $attributes->textContent;
2587                                         }
2588                                 }
2589
2590                                 if (($term != "") && ($scheme != "")) {
2591                                         $parts = explode(":", $scheme);
2592                                         if ((count($parts) >= 4) && (array_shift($parts) == "X-DFRN")) {
2593                                                 $termhash = array_shift($parts);
2594                                                 $termurl = implode(":", $parts);
2595
2596                                                 if (!empty($item["tag"])) {
2597                                                         $item["tag"] .= ",";
2598                                                 } else {
2599                                                         $item["tag"] = "";
2600                                                 }
2601
2602                                                 $item["tag"] .= $termhash . "[url=" . $termurl . "]" . $term . "[/url]";
2603                                         }
2604                                 }
2605                         }
2606                 }
2607
2608                 $enclosure = "";
2609
2610                 $links = $xpath->query("atom:link", $entry);
2611                 if ($links) {
2612                         self::parseLinks($links, $item);
2613                 }
2614
2615                 $item['conversation-uri'] = XML::getFirstNodeValue($xpath, 'ostatus:conversation/text()', $entry);
2616
2617                 $conv = $xpath->query('ostatus:conversation', $entry);
2618                 if (is_object($conv->item(0))) {
2619                         foreach ($conv->item(0)->attributes as $attributes) {
2620                                 if ($attributes->name == "ref") {
2621                                         $item['conversation-uri'] = $attributes->textContent;
2622                                 }
2623                                 if ($attributes->name == "href") {
2624                                         $item['conversation-href'] = $attributes->textContent;
2625                                 }
2626                         }
2627                 }
2628
2629                 // Is it a reply or a top level posting?
2630                 $item["parent-uri"] = $item["uri"];
2631
2632                 $inreplyto = $xpath->query("thr:in-reply-to", $entry);
2633                 if (is_object($inreplyto->item(0))) {
2634                         foreach ($inreplyto->item(0)->attributes as $attributes) {
2635                                 if ($attributes->name == "ref") {
2636                                         $item["parent-uri"] = $attributes->textContent;
2637                                 }
2638                         }
2639                 }
2640
2641                 // Get the type of the item (Top level post, reply or remote reply)
2642                 $entrytype = self::getEntryType($importer, $item);
2643
2644                 // Now assign the rest of the values that depend on the type of the message
2645                 if (in_array($entrytype, [DFRN::REPLY, DFRN::REPLY_RC])) {
2646                         if (!isset($item["object-type"])) {
2647                                 $item["object-type"] = ACTIVITY_OBJ_COMMENT;
2648                         }
2649
2650                         if ($item["contact-id"] != $owner["contact-id"]) {
2651                                 $item["contact-id"] = $owner["contact-id"];
2652                         }
2653
2654                         if (($item["network"] != $owner["network"]) && ($owner["network"] != "")) {
2655                                 $item["network"] = $owner["network"];
2656                         }
2657
2658                         if ($item["contact-id"] != $author["contact-id"]) {
2659                                 $item["contact-id"] = $author["contact-id"];
2660                         }
2661
2662                         if (($item["network"] != $author["network"]) && ($author["network"] != "")) {
2663                                 $item["network"] = $author["network"];
2664                         }
2665                 }
2666
2667                 if ($entrytype == DFRN::REPLY_RC) {
2668                         $item["wall"] = 1;
2669                 } elseif ($entrytype == DFRN::TOP_LEVEL) {
2670                         if (!isset($item["object-type"])) {
2671                                 $item["object-type"] = ACTIVITY_OBJ_NOTE;
2672                         }
2673
2674                         // Is it an event?
2675                         if (($item["object-type"] == ACTIVITY_OBJ_EVENT) && !$owner_unknown) {
2676                                 Logger::log("Item ".$item["uri"]." seems to contain an event.", Logger::DEBUG);
2677                                 $ev = Event::fromBBCode($item["body"]);
2678                                 if ((x($ev, "desc") || x($ev, "summary")) && x($ev, "start")) {
2679                                         Logger::log("Event in item ".$item["uri"]." was found.", Logger::DEBUG);
2680                                         $ev["cid"]     = $importer["id"];
2681                                         $ev["uid"]     = $importer["importer_uid"];
2682                                         $ev["uri"]     = $item["uri"];
2683                                         $ev["edited"]  = $item["edited"];
2684                                         $ev["private"] = $item["private"];
2685                                         $ev["guid"]    = $item["guid"];
2686                                         $ev["plink"]   = $item["plink"];
2687
2688                                         $condition = ['uri' => $item["uri"], 'uid' => $importer["importer_uid"]];
2689                                         $event = DBA::selectFirst('event', ['id'], $condition);
2690                                         if (DBA::isResult($event)) {
2691                                                 $ev["id"] = $event["id"];
2692                                         }
2693
2694                                         $event_id = Event::store($ev);
2695                                         Logger::log("Event ".$event_id." was stored", Logger::DEBUG);
2696                                         return;
2697                                 }
2698                         }
2699                 }
2700
2701                 if (!self::processVerbs($entrytype, $importer, $item, $is_like)) {
2702                         Logger::log("Exiting because 'processVerbs' told us so", Logger::DEBUG);
2703                         return;
2704                 }
2705
2706                 // This check is done here to be able to receive connection requests in "processVerbs"
2707                 if (($entrytype == DFRN::TOP_LEVEL) && $owner_unknown) {
2708                         Logger::log("Item won't be stored because user " . $importer["importer_uid"] . " doesn't follow " . $item["owner-link"] . ".", Logger::DEBUG);
2709                         return;
2710                 }
2711
2712
2713                 // Update content if 'updated' changes
2714                 if (DBA::isResult($current)) {
2715                         if (self::updateContent($current, $item, $importer, $entrytype)) {
2716                                 Logger::log("Item ".$item["uri"]." was updated.", Logger::DEBUG);
2717                         } else {
2718                                 Logger::log("Item " . $item["uri"] . " already existed.", Logger::DEBUG);
2719                         }
2720                         return;
2721                 }
2722
2723                 if (in_array($entrytype, [DFRN::REPLY, DFRN::REPLY_RC])) {
2724                         $posted_id = Item::insert($item);
2725                         $parent = 0;
2726
2727                         if ($posted_id) {
2728                                 Logger::log("Reply from contact ".$item["contact-id"]." was stored with id ".$posted_id, Logger::DEBUG);
2729
2730                                 if ($item['uid'] == 0) {
2731                                         Item::distribute($posted_id);
2732                                 }
2733
2734                                 return true;
2735                         }
2736                 } else { // $entrytype == DFRN::TOP_LEVEL
2737                         if (($importer["uid"] == 0) && ($importer["importer_uid"] != 0)) {
2738                                 Logger::log("Contact ".$importer["id"]." isn't known to user ".$importer["importer_uid"].". The post will be ignored.", Logger::DEBUG);
2739                                 return;
2740                         }
2741                         if (!link_compare($item["owner-link"], $importer["url"])) {
2742                                 /*
2743                                  * The item owner info is not our contact. It's OK and is to be expected if this is a tgroup delivery,
2744                                  * but otherwise there's a possible data mixup on the sender's system.
2745                                  * the tgroup delivery code called from Item::insert will correct it if it's a forum,
2746                                  * but we're going to unconditionally correct it here so that the post will always be owned by our contact.
2747                                  */
2748                                 Logger::log('Correcting item owner.', Logger::DEBUG);
2749                                 $item["owner-link"] = $importer["url"];
2750                                 $item["owner-id"] = Contact::getIdForURL($importer["url"], 0);
2751                         }
2752
2753                         if (($importer["rel"] == Contact::FOLLOWER) && (!self::tgroupCheck($importer["importer_uid"], $item))) {
2754                                 Logger::log("Contact ".$importer["id"]." is only follower and tgroup check was negative.", Logger::DEBUG);
2755                                 return;
2756                         }
2757
2758                         // This is my contact on another system, but it's really me.
2759                         // Turn this into a wall post.
2760                         $notify = Item::isRemoteSelf($importer, $item);
2761
2762                         $posted_id = Item::insert($item, false, $notify);
2763
2764                         if ($notify) {
2765                                 $posted_id = $notify;
2766                         }
2767
2768                         Logger::log("Item was stored with id ".$posted_id, Logger::DEBUG);
2769
2770                         if ($item['uid'] == 0) {
2771                                 Item::distribute($posted_id);
2772                         }
2773
2774                         if (stristr($item["verb"], ACTIVITY_POKE)) {
2775                                 self::doPoke($item, $importer, $posted_id);
2776                         }
2777                 }
2778         }
2779
2780         /**
2781          * @brief Deletes items
2782          *
2783          * @param object $xpath    XPath object
2784          * @param object $deletion deletion elements
2785          * @param array  $importer Record of the importer user mixed with contact of the content
2786          * @return void
2787          * @todo set proper type-hints
2788          */
2789         private static function processDeletion($xpath, $deletion, $importer)
2790         {
2791                 Logger::log("Processing deletions");
2792                 $uri = null;
2793
2794                 foreach ($deletion->attributes as $attributes) {
2795                         if ($attributes->name == "ref") {
2796                                 $uri = $attributes->textContent;
2797                         }
2798                 }
2799
2800                 if (!$uri || !$importer["id"]) {
2801                         return false;
2802                 }
2803
2804                 $condition = ['uri' => $uri, 'uid' => $importer["importer_uid"]];
2805                 $item = Item::selectFirst(['id', 'parent', 'contact-id', 'file', 'deleted'], $condition);
2806                 if (!DBA::isResult($item)) {
2807                         Logger::log("Item with uri " . $uri . " for user " . $importer["importer_uid"] . " wasn't found.", Logger::DEBUG);
2808                         return;
2809                 }
2810
2811                 if (strstr($item['file'], '[')) {
2812                         Logger::log("Item with uri " . $uri . " for user " . $importer["importer_uid"] . " is filed. So it won't be deleted.", Logger::DEBUG);
2813                         return;
2814                 }
2815
2816                 // When it is a starting post it has to belong to the person that wants to delete it
2817                 if (($item['id'] == $item['parent']) && ($item['contact-id'] != $importer["id"])) {
2818                         Logger::log("Item with uri " . $uri . " don't belong to contact " . $importer["id"] . " - ignoring deletion.", Logger::DEBUG);
2819                         return;
2820                 }
2821
2822                 // Comments can be deleted by the thread owner or comment owner
2823                 if (($item['id'] != $item['parent']) && ($item['contact-id'] != $importer["id"])) {
2824                         $condition = ['id' => $item['parent'], 'contact-id' => $importer["id"]];
2825                         if (!Item::exists($condition)) {
2826                                 Logger::log("Item with uri " . $uri . " wasn't found or mustn't be deleted by contact " . $importer["id"] . " - ignoring deletion.", Logger::DEBUG);
2827                                 return;
2828                         }
2829                 }
2830
2831                 if ($item["deleted"]) {
2832                         return;
2833                 }
2834
2835                 Logger::log('deleting item '.$item['id'].' uri='.$uri, Logger::DEBUG);
2836
2837                 Item::delete(['id' => $item['id']]);
2838         }
2839
2840         /**
2841          * @brief Imports a DFRN message
2842          *
2843          * @param string $xml          The DFRN message
2844          * @param array  $importer     Record of the importer user mixed with contact of the content
2845          * @param bool   $sort_by_date Is used when feeds are polled
2846          * @return integer Import status
2847          * @todo set proper type-hints
2848          */
2849         public static function import($xml, $importer, $sort_by_date = false)
2850         {
2851                 if ($xml == "") {
2852                         return 400;
2853                 }
2854
2855                 $doc = new DOMDocument();
2856                 @$doc->loadXML($xml);
2857
2858                 $xpath = new DOMXPath($doc);
2859                 $xpath->registerNamespace("atom", NAMESPACE_ATOM1);
2860                 $xpath->registerNamespace("thr", NAMESPACE_THREAD);
2861                 $xpath->registerNamespace("at", NAMESPACE_TOMB);
2862                 $xpath->registerNamespace("media", NAMESPACE_MEDIA);
2863                 $xpath->registerNamespace("dfrn", NAMESPACE_DFRN);
2864                 $xpath->registerNamespace("activity", NAMESPACE_ACTIVITY);
2865                 $xpath->registerNamespace("georss", NAMESPACE_GEORSS);
2866                 $xpath->registerNamespace("poco", NAMESPACE_POCO);
2867                 $xpath->registerNamespace("ostatus", NAMESPACE_OSTATUS);
2868                 $xpath->registerNamespace("statusnet", NAMESPACE_STATUSNET);
2869
2870                 $header = [];
2871                 $header["uid"] = $importer["importer_uid"];
2872                 $header["network"] = Protocol::DFRN;
2873                 $header["wall"] = 0;
2874                 $header["origin"] = 0;
2875                 $header["contact-id"] = $importer["id"];
2876
2877                 // Update the contact table if the data has changed
2878
2879                 // The "atom:author" is only present in feeds
2880                 if ($xpath->query("/atom:feed/atom:author")->length > 0) {
2881                         self::fetchauthor($xpath, $doc->firstChild, $importer, "atom:author", false, $xml);
2882                 }
2883
2884                 // Only the "dfrn:owner" in the head section contains all data
2885                 if ($xpath->query("/atom:feed/dfrn:owner")->length > 0) {
2886                         self::fetchauthor($xpath, $doc->firstChild, $importer, "dfrn:owner", false, $xml);
2887                 }
2888
2889                 Logger::log("Import DFRN message for user " . $importer["importer_uid"] . " from contact " . $importer["id"], Logger::DEBUG);
2890
2891                 // is it a public forum? Private forums aren't exposed with this method
2892                 $forum = intval(XML::getFirstNodeValue($xpath, "/atom:feed/dfrn:community/text()"));
2893
2894                 // The account type is new since 3.5.1
2895                 if ($xpath->query("/atom:feed/dfrn:account_type")->length > 0) {
2896                         $accounttype = intval(XML::getFirstNodeValue($xpath, "/atom:feed/dfrn:account_type/text()"));
2897
2898                         if ($accounttype != $importer["contact-type"]) {
2899                                 DBA::update('contact', ['contact-type' => $accounttype], ['id' => $importer["id"]]);
2900                         }
2901                         // A forum contact can either have set "forum" or "prv" - but not both
2902                         if (($accounttype == Contact::ACCOUNT_TYPE_COMMUNITY) && (($forum != $importer["forum"]) || ($forum == $importer["prv"]))) {
2903                                 $condition = ['(`forum` != ? OR `prv` != ?) AND `id` = ?', $forum, !$forum, $importer["id"]];
2904                                 DBA::update('contact', ['forum' => $forum, 'prv' => !$forum], $condition);
2905                         }
2906                 } elseif ($forum != $importer["forum"]) { // Deprecated since 3.5.1
2907                         $condition = ['`forum` != ? AND `id` = ?', $forum, $importer["id"]];
2908                         DBA::update('contact', ['forum' => $forum], $condition);
2909                 }
2910
2911
2912                 // We are processing relocations even if we are ignoring a contact
2913                 $relocations = $xpath->query("/atom:feed/dfrn:relocate");
2914                 foreach ($relocations as $relocation) {
2915                         self::processRelocation($xpath, $relocation, $importer);
2916                 }
2917
2918                 if (($importer["uid"] != 0) && !$importer["readonly"]) {
2919                         $mails = $xpath->query("/atom:feed/dfrn:mail");
2920                         foreach ($mails as $mail) {
2921                                 self::processMail($xpath, $mail, $importer);
2922                         }
2923
2924                         $suggestions = $xpath->query("/atom:feed/dfrn:suggest");
2925                         foreach ($suggestions as $suggestion) {
2926                                 self::processSuggestion($xpath, $suggestion, $importer);
2927                         }
2928                 }
2929
2930                 $deletions = $xpath->query("/atom:feed/at:deleted-entry");
2931                 foreach ($deletions as $deletion) {
2932                         self::processDeletion($xpath, $deletion, $importer);
2933                 }
2934
2935                 if (!$sort_by_date) {
2936                         $entries = $xpath->query("/atom:feed/atom:entry");
2937                         foreach ($entries as $entry) {
2938                                 self::processEntry($header, $xpath, $entry, $importer, $xml);
2939                         }
2940                 } else {
2941                         $newentries = [];
2942                         $entries = $xpath->query("/atom:feed/atom:entry");
2943                         foreach ($entries as $entry) {
2944                                 $created = XML::getFirstNodeValue($xpath, "atom:published/text()", $entry);
2945                                 $newentries[strtotime($created)] = $entry;
2946                         }
2947
2948                         // Now sort after the publishing date
2949                         ksort($newentries);
2950
2951                         foreach ($newentries as $entry) {
2952                                 self::processEntry($header, $xpath, $entry, $importer, $xml);
2953                         }
2954                 }
2955                 Logger::log("Import done for user " . $importer["importer_uid"] . " from contact " . $importer["id"], Logger::DEBUG);
2956                 return 200;
2957         }
2958
2959         /**
2960          * @param App    $a            App
2961          * @param string $contact_nick contact nickname
2962          */
2963         public static function autoRedir(App $a, $contact_nick)
2964         {
2965                 // prevent looping
2966                 if (x($_REQUEST, 'redir') && intval($_REQUEST['redir'])) {
2967                         return;
2968                 }
2969
2970                 if ((! $contact_nick) || ($contact_nick === $a->user['nickname'])) {
2971                         return;
2972                 }
2973
2974                 if (local_user()) {
2975                         // We need to find out if $contact_nick is a user on this hub, and if so, if I
2976                         // am a contact of that user. However, that user may have other contacts with the
2977                         // same nickname as me on other hubs or other networks. Exclude these by requiring
2978                         // that the contact have a local URL. I will be the only person with my nickname at
2979                         // this URL, so if a result is found, then I am a contact of the $contact_nick user.
2980                         //
2981                         // We also have to make sure that I'm a legitimate contact--I'm not blocked or pending.
2982
2983                         $baseurl = System::baseUrl();
2984                         $domain_st = strpos($baseurl, "://");
2985                         if ($domain_st === false) {
2986                                 return;
2987                         }
2988                         $baseurl = substr($baseurl, $domain_st + 3);
2989                         $nurl = normalise_link($baseurl);
2990
2991                         /// @todo Why is there a query for "url" *and* "nurl"? Especially this normalising is strange.
2992                         $r = q("SELECT `id` FROM `contact` WHERE `uid` = (SELECT `uid` FROM `user` WHERE `nickname` = '%s' LIMIT 1)
2993                                         AND `nick` = '%s' AND NOT `self` AND (`url` LIKE '%%%s%%' OR `nurl` LIKE '%%%s%%') AND NOT `blocked` AND NOT `pending` LIMIT 1",
2994                                 DBA::escape($contact_nick),
2995                                 DBA::escape($a->user['nickname']),
2996                                 DBA::escape($baseurl),
2997                                 DBA::escape($nurl)
2998                         );
2999                         if ((! DBA::isResult($r)) || $r[0]['id'] == remote_user()) {
3000                                 return;
3001                         }
3002
3003                         $r = q("SELECT * FROM contact WHERE nick = '%s'
3004                                         AND network = '%s' AND uid = %d  AND url LIKE '%%%s%%' LIMIT 1",
3005                                 DBA::escape($contact_nick),
3006                                 DBA::escape(Protocol::DFRN),
3007                                 intval(local_user()),
3008                                 DBA::escape($baseurl)
3009                         );
3010                         if (! DBA::isResult($r)) {
3011                                 return;
3012                         }
3013
3014                         $cid = $r[0]['id'];
3015
3016                         $dfrn_id = (($r[0]['issued-id']) ? $r[0]['issued-id'] : $r[0]['dfrn-id']);
3017
3018                         if ($r[0]['duplex'] && $r[0]['issued-id']) {
3019                                 $orig_id = $r[0]['issued-id'];
3020                                 $dfrn_id = '1:' . $orig_id;
3021                         }
3022                         if ($r[0]['duplex'] && $r[0]['dfrn-id']) {
3023                                 $orig_id = $r[0]['dfrn-id'];
3024                                 $dfrn_id = '0:' . $orig_id;
3025                         }
3026
3027                         // ensure that we've got a valid ID. There may be some edge cases with forums and non-duplex mode
3028                         // that may have triggered some of the "went to {profile/intro} and got an RSS feed" issues
3029
3030                         if (strlen($dfrn_id) < 3) {
3031                                 return;
3032                         }
3033
3034                         $sec = Strings::getRandomHex();
3035
3036                         DBA::insert('profile_check', ['uid' => local_user(), 'cid' => $cid, 'dfrn_id' => $dfrn_id, 'sec' => $sec, 'expire' => time() + 45]);
3037
3038                         $url = curPageURL();
3039
3040                         Logger::log('auto_redir: ' . $r[0]['name'] . ' ' . $sec, Logger::DEBUG);
3041                         $dest = (($url) ? '&destination_url=' . $url : '');
3042                         System::externalRedirect($r[0]['poll'] . '?dfrn_id=' . $dfrn_id
3043                                 . '&dfrn_version=' . DFRN_PROTOCOL_VERSION . '&type=profile&sec=' . $sec . $dest);
3044                 }
3045
3046                 return;
3047         }
3048
3049         /**
3050          * @brief Returns the activity verb
3051          *
3052          * @param array $item Item array
3053          *
3054          * @return string activity verb
3055          */
3056         private static function constructVerb(array $item)
3057         {
3058                 if ($item['verb']) {
3059                         return $item['verb'];
3060                 }
3061                 return ACTIVITY_POST;
3062         }
3063
3064         private static function tgroupCheck($uid, $item)
3065         {
3066                 $mention = false;
3067
3068                 // check that the message originated elsewhere and is a top-level post
3069
3070                 if ($item['wall'] || $item['origin'] || ($item['uri'] != $item['parent-uri'])) {
3071                         return false;
3072                 }
3073
3074                 $user = DBA::selectFirst('user', ['page-flags', 'nickname'], ['uid' => $uid]);
3075                 if (!DBA::isResult($user)) {
3076                         return false;
3077                 }
3078
3079                 $community_page = ($user['page-flags'] == Contact::PAGE_COMMUNITY);
3080                 $prvgroup = ($user['page-flags'] == Contact::PAGE_PRVGROUP);
3081
3082                 $link = normalise_link(System::baseUrl() . '/profile/' . $user['nickname']);
3083
3084                 /*
3085                  * Diaspora uses their own hardwired link URL in @-tags
3086                  * instead of the one we supply with webfinger
3087                  */
3088                 $dlink = normalise_link(System::baseUrl() . '/u/' . $user['nickname']);
3089
3090                 $cnt = preg_match_all('/[\@\!]\[url\=(.*?)\](.*?)\[\/url\]/ism', $item['body'], $matches, PREG_SET_ORDER);
3091                 if ($cnt) {
3092                         foreach ($matches as $mtch) {
3093                                 if (link_compare($link, $mtch[1]) || link_compare($dlink, $mtch[1])) {
3094                                         $mention = true;
3095                                         Logger::log('mention found: ' . $mtch[2]);
3096                                 }
3097                         }
3098                 }
3099
3100                 if (!$mention) {
3101                         return false;
3102                 }
3103
3104                 return $community_page || $prvgroup;
3105         }
3106
3107         /**
3108          * This function returns true if $update has an edited timestamp newer
3109          * than $existing, i.e. $update contains new data which should override
3110          * what's already there.  If there is no timestamp yet, the update is
3111          * assumed to be newer.  If the update has no timestamp, the existing
3112          * item is assumed to be up-to-date.  If the timestamps are equal it
3113          * assumes the update has been seen before and should be ignored.
3114          *
3115          */
3116         private static function isEditedTimestampNewer($existing, $update)
3117         {
3118                 if (!x($existing, 'edited') || !$existing['edited']) {
3119                         return true;
3120                 }
3121                 if (!x($update, 'edited') || !$update['edited']) {
3122                         return false;
3123                 }
3124
3125                 $existing_edited = DateTimeFormat::utc($existing['edited']);
3126                 $update_edited = DateTimeFormat::utc($update['edited']);
3127
3128                 return (strcmp($existing_edited, $update_edited) < 0);
3129         }
3130 }