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