]> git.mxchange.org Git - friendica.git/blob - src/Protocol/DFRN.php
Rename dbesc to DBA::escape
[friendica.git] / src / Protocol / DFRN.php
1 <?php
2 /**
3  * @file include/dfrn.php
4  * @brief The implementation of the dfrn protocol
5  *
6  * @see https://github.com/friendica/friendica/wiki/Protocol and
7  * https://github.com/friendica/friendica/blob/master/spec/dfrn2.pdf
8  */
9 namespace Friendica\Protocol;
10
11 use DOMDocument;
12 use DOMXPath;
13 use Friendica\App;
14 use Friendica\Content\OEmbed;
15 use Friendica\Content\Text\BBCode;
16 use Friendica\Content\Text\HTML;
17 use Friendica\Core\Addon;
18 use Friendica\Core\Config;
19 use Friendica\Core\L10n;
20 use Friendica\Core\System;
21 use Friendica\Database\DBA;
22 use Friendica\Model\Contact;
23 use Friendica\Model\Event;
24 use Friendica\Model\GContact;
25 use Friendica\Model\Group;
26 use Friendica\Model\Item;
27 use Friendica\Model\Profile;
28 use Friendica\Model\User;
29 use Friendica\Object\Image;
30 use Friendica\Util\Crypto;
31 use Friendica\Util\DateTimeFormat;
32 use Friendica\Util\Network;
33 use Friendica\Util\XML;
34 use HTMLPurifier;
35 use HTMLPurifier_Config;
36
37 require_once 'boot.php';
38 require_once 'include/dba.php';
39 require_once "include/enotify.php";
40 require_once "include/items.php";
41 require_once "include/text.php";
42
43 /**
44  * @brief This class contain functions to create and send DFRN XML files
45  */
46 class DFRN
47 {
48
49         const TOP_LEVEL = 0;    // Top level posting
50         const REPLY = 1;                // Regular reply that is stored locally
51         const REPLY_RC = 2;     // Reply that will be relayed
52
53         /**
54          * @brief Generates the atom entries for delivery.php
55          *
56          * This function is used whenever content is transmitted via DFRN.
57          *
58          * @param array $items Item elements
59          * @param array $owner Owner record
60          *
61          * @return string DFRN entries
62          * @todo Find proper type-hints
63          */
64         public static function entries($items, $owner)
65         {
66                 $doc = new DOMDocument('1.0', 'utf-8');
67                 $doc->formatOutput = true;
68
69                 $root = self::addHeader($doc, $owner, "dfrn:owner", "", false);
70
71                 if (! count($items)) {
72                         return trim($doc->saveXML());
73                 }
74
75                 foreach ($items as $item) {
76                         // These values aren't sent when sending from the queue.
77                         /// @todo Check if we can set these values from the queue or if they are needed at all.
78                         $item["entry:comment-allow"] = defaults($item, "entry:comment-allow", true);
79                         $item["entry:cid"] = defaults($item, "entry:cid", 0);
80
81                         $entry = self::entry($doc, "text", $item, $owner, $item["entry:comment-allow"], $item["entry:cid"]);
82                         $root->appendChild($entry);
83                 }
84
85                 return trim($doc->saveXML());
86         }
87
88         /**
89          * @brief Generate an atom feed for the given user
90          *
91          * This function is called when another server is pulling data from the user feed.
92          *
93          * @param string  $dfrn_id     DFRN ID from the requesting party
94          * @param string  $owner_nick  Owner nick name
95          * @param string  $last_update Date of the last update
96          * @param int     $direction   Can be -1, 0 or 1.
97          * @param boolean $onlyheader  Output only the header without content? (Default is "no")
98          *
99          * @return string DFRN feed entries
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                         DBA::escape($owner_nick)
133                 );
134
135                 if (! DBA::isResult($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' ", DBA::escape($dfrn_id));
151                                         $my_id = $dfrn_id;
152                                         break;
153                                 case 0:
154                                         $sql_extra = sprintf(" AND `issued-id` = '%s' AND `duplex` = 1 ", DBA::escape($dfrn_id));
155                                         $my_id = '1:' . $dfrn_id;
156                                         break;
157                                 case 1:
158                                         $sql_extra = sprintf(" AND `dfrn-id` = '%s' AND `duplex` = 1 ", DBA::escape($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 (! DBA::isResult($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                                 DBA::escape($gs),
200                                 DBA::escape($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                                 DBA::escape(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                         DBA::escape($check_date),
240                         DBA::escape($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 = Item::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 (!DBA::isResult($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 = Item::inArray($ret);
335                 if (!DBA::isResult($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 (DBA::isResult($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 (DBA::isResult($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 = Item::selectFirst(['guid', 'plink'], ['uri' => $parent_item, 'uid' => $item['uid']]);
943                         $attributes = ["ref" => $parent_item, "type" => "text/html",
944                                                 "href" => $parent['plink'],
945                                                 "dfrn:diaspora_guid" => $parent['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 (DBA::isResult($conversation)) {
956                                 if ($conversation['conversation-uri'] != '') {
957                                         $conversation_uri = $conversation['conversation-uri'];
958                                 }
959                                 if ($conversation['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['post-type'] == Item::PT_PAGE) {
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                                 DBA::escape(normalise_link($mention))
1077                         );
1078
1079                         if (DBA::isResult($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 (!empty($ret["errno"]) && ($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 (!is_object($res) || (intval($res->status) != 0) || !strlen($res->challenge) || !strlen($res->dfrn_id)) {
1221                         Contact::markForArchival($contact);
1222
1223                         if (empty($res->status)) {
1224                                 $status = 3;
1225                         } else {
1226                                 $status = $res->status;
1227                         }
1228
1229                         return $status;
1230                 }
1231
1232                 $postvars     = [];
1233                 $sent_dfrn_id = hex2bin((string) $res->dfrn_id);
1234                 $challenge    = hex2bin((string) $res->challenge);
1235                 $perm         = (($res->perm) ? $res->perm : null);
1236                 $dfrn_version = (float) (($res->dfrn_version) ? $res->dfrn_version : 2.0);
1237                 $rino_remote_version = intval($res->rino);
1238                 $page         = (($owner['page-flags'] == PAGE_COMMUNITY) ? 1 : 0);
1239
1240                 logger("Remote rino version: ".$rino_remote_version." for ".$contact["url"], LOGGER_DEBUG);
1241
1242                 if ($owner['page-flags'] == PAGE_PRVGROUP) {
1243                         $page = 2;
1244                 }
1245
1246                 $final_dfrn_id = '';
1247
1248                 if ($perm) {
1249                         if ((($perm == 'rw') && (! intval($contact['writable'])))
1250                                 || (($perm == 'r') && (intval($contact['writable'])))
1251                         ) {
1252                                 q(
1253                                         "update contact set writable = %d where id = %d",
1254                                         intval(($perm == 'rw') ? 1 : 0),
1255                                         intval($contact['id'])
1256                                 );
1257                                 $contact['writable'] = (string) 1 - intval($contact['writable']);
1258                         }
1259                 }
1260
1261                 if (($contact['duplex'] && strlen($contact['pubkey']))
1262                         || ($owner['page-flags'] == PAGE_COMMUNITY && strlen($contact['pubkey']))
1263                         || ($contact['rel'] == CONTACT_IS_SHARING && strlen($contact['pubkey']))
1264                 ) {
1265                         openssl_public_decrypt($sent_dfrn_id, $final_dfrn_id, $contact['pubkey']);
1266                         openssl_public_decrypt($challenge, $postvars['challenge'], $contact['pubkey']);
1267                 } else {
1268                         openssl_private_decrypt($sent_dfrn_id, $final_dfrn_id, $contact['prvkey']);
1269                         openssl_private_decrypt($challenge, $postvars['challenge'], $contact['prvkey']);
1270                 }
1271
1272                 $final_dfrn_id = substr($final_dfrn_id, 0, strpos($final_dfrn_id, '.'));
1273
1274                 if (strpos($final_dfrn_id, ':') == 1) {
1275                         $final_dfrn_id = substr($final_dfrn_id, 2);
1276                 }
1277
1278                 if ($final_dfrn_id != $orig_id) {
1279                         logger('dfrn_deliver: wrong dfrn_id.');
1280                         // did not decode properly - cannot trust this site
1281                         Contact::markForArchival($contact);
1282                         return 3;
1283                 }
1284
1285                 $postvars['dfrn_id']      = $idtosend;
1286                 $postvars['dfrn_version'] = DFRN_PROTOCOL_VERSION;
1287                 if ($dissolve) {
1288                         $postvars['dissolve'] = '1';
1289                 }
1290
1291                 if ((($contact['rel']) && ($contact['rel'] != CONTACT_IS_SHARING) && (! $contact['blocked'])) || ($owner['page-flags'] == PAGE_COMMUNITY)) {
1292                         $postvars['data'] = $atom;
1293                         $postvars['perm'] = 'rw';
1294                 } else {
1295                         $postvars['data'] = str_replace('<dfrn:comment-allow>1', '<dfrn:comment-allow>0', $atom);
1296                         $postvars['perm'] = 'r';
1297                 }
1298
1299                 $postvars['ssl_policy'] = $ssl_policy;
1300
1301                 if ($page) {
1302                         $postvars['page'] = $page;
1303                 }
1304
1305
1306                 if ($rino > 0 && $rino_remote_version > 0 && (! $dissolve)) {
1307                         logger('rino version: '. $rino_remote_version);
1308
1309                         switch ($rino_remote_version) {
1310                                 case 1:
1311                                         $key = openssl_random_pseudo_bytes(16);
1312                                         $data = self::aesEncrypt($postvars['data'], $key);
1313                                         break;
1314                                 default:
1315                                         logger("rino: invalid requested version '$rino_remote_version'");
1316                                         Contact::markForArchival($contact);
1317                                         return -8;
1318                         }
1319
1320                         $postvars['rino'] = $rino_remote_version;
1321                         $postvars['data'] = bin2hex($data);
1322
1323                         if ($dfrn_version >= 2.1) {
1324                                 if (($contact['duplex'] && strlen($contact['pubkey']))
1325                                         || ($owner['page-flags'] == PAGE_COMMUNITY && strlen($contact['pubkey']))
1326                                         || ($contact['rel'] == CONTACT_IS_SHARING && strlen($contact['pubkey']))
1327                                 ) {
1328                                         openssl_public_encrypt($key, $postvars['key'], $contact['pubkey']);
1329                                 } else {
1330                                         openssl_private_encrypt($key, $postvars['key'], $contact['prvkey']);
1331                                 }
1332                         } else {
1333                                 if (($contact['duplex'] && strlen($contact['prvkey'])) || ($owner['page-flags'] == PAGE_COMMUNITY)) {
1334                                         openssl_private_encrypt($key, $postvars['key'], $contact['prvkey']);
1335                                 } else {
1336                                         openssl_public_encrypt($key, $postvars['key'], $contact['pubkey']);
1337                                 }
1338                         }
1339
1340                         logger('md5 rawkey ' . md5($postvars['key']));
1341
1342                         $postvars['key'] = bin2hex($postvars['key']);
1343                 }
1344
1345
1346                 logger('dfrn_deliver: ' . "SENDING: " . print_r($postvars, true), LOGGER_DATA);
1347
1348                 $xml = Network::post($contact['notify'], $postvars);
1349
1350                 logger('dfrn_deliver: ' . "RECEIVED: " . $xml, LOGGER_DATA);
1351
1352                 $curl_stat = $a->get_curl_code();
1353                 if (empty($curl_stat) || empty($xml)) {
1354                         Contact::markForArchival($contact);
1355                         return -9; // timed out
1356                 }
1357
1358                 if (($curl_stat == 503) && stristr($a->get_curl_headers(), 'retry-after')) {
1359                         Contact::markForArchival($contact);
1360                         return -10;
1361                 }
1362
1363                 if (strpos($xml, '<?xml') === false) {
1364                         logger('dfrn_deliver: phase 2: no valid XML returned');
1365                         logger('dfrn_deliver: phase 2: returned XML: ' . $xml, LOGGER_DATA);
1366                         Contact::markForArchival($contact);
1367                         return 3;
1368                 }
1369
1370                 $res = XML::parseString($xml);
1371
1372                 if (!isset($res->status)) {
1373                         Contact::markForArchival($contact);
1374                         return -11;
1375                 }
1376
1377                 // Possibly old servers had returned an empty value when everything was okay
1378                 if (empty($res->status)) {
1379                         $res->status = 200;
1380                 }
1381
1382                 if (!empty($res->message)) {
1383                         logger('Delivery returned status '.$res->status.' - '.$res->message, LOGGER_DEBUG);
1384                 }
1385
1386                 if (($res->status >= 200) && ($res->status <= 299)) {
1387                         Contact::unmarkForArchival($contact);
1388                 }
1389
1390                 return intval($res->status);
1391         }
1392
1393         /**
1394          * @brief Transmits atom content to the contacts via the Diaspora transport layer
1395          *
1396          * @param array  $owner    Owner record
1397          * @param array  $contact  Contact record of the receiver
1398          * @param string $atom     Content that will be transmitted
1399          *
1400          * @return int Deliver status. Negative values mean an error.
1401          */
1402         public static function transmit($owner, $contact, $atom, $public_batch = false)
1403         {
1404                 $a = get_app();
1405
1406                 if (!$public_batch) {
1407                         if (empty($contact['addr'])) {
1408                                 logger('Empty contact handle for ' . $contact['id'] . ' - ' . $contact['url'] . ' - trying to update it.');
1409                                 if (Contact::updateFromProbe($contact['id'])) {
1410                                         $new_contact = DBA::selectFirst('contact', ['addr'], ['id' => $contact['id']]);
1411                                         $contact['addr'] = $new_contact['addr'];
1412                                 }
1413
1414                                 if (empty($contact['addr'])) {
1415                                         logger('Unable to find contact handle for ' . $contact['id'] . ' - ' . $contact['url']);
1416                                         Contact::markForArchival($contact);
1417                                         return -21;
1418                                 }
1419                         }
1420
1421                         $fcontact = Diaspora::personByHandle($contact['addr']);
1422                         if (empty($fcontact)) {
1423                                 logger('Unable to find contact details for ' . $contact['id'] . ' - ' . $contact['addr']);
1424                                 Contact::markForArchival($contact);
1425                                 return -22;
1426                         }
1427                         $pubkey = $fcontact['pubkey'];
1428                 } else {
1429                         $pubkey = '';
1430                 }
1431
1432                 $envelope = Diaspora::buildMessage($atom, $owner, $contact, $owner['uprvkey'], $pubkey, $public_batch);
1433
1434                 // Create the endpoint for public posts. This is some WIP and should later be added to the probing
1435                 if ($public_batch && empty($contact["batch"])) {
1436                         $parts = parse_url($contact["notify"]);
1437                         $path_parts = explode('/', $parts['path']);
1438                         array_pop($path_parts);
1439                         $parts['path'] =  implode('/', $path_parts);
1440                         $contact["batch"] = Network::unparseURL($parts);
1441                 }
1442
1443                 $dest_url = ($public_batch ? $contact["batch"] : $contact["notify"]);
1444
1445                 $content_type = ($public_batch ? "application/magic-envelope+xml" : "application/json");
1446
1447                 $xml = Network::post($dest_url, $envelope, ["Content-Type: ".$content_type]);
1448
1449                 $curl_stat = $a->get_curl_code();
1450                 if (empty($curl_stat) || empty($xml)) {
1451                         logger('Empty answer from ' . $contact['id'] . ' - ' . $dest_url);
1452                         Contact::markForArchival($contact);
1453                         return -9; // timed out
1454                 }
1455
1456                 if (($curl_stat == 503) && (stristr($a->get_curl_headers(), 'retry-after'))) {
1457                         Contact::markForArchival($contact);
1458                         return -10;
1459                 }
1460
1461                 if (strpos($xml, '<?xml') === false) {
1462                         logger('No valid XML returned from ' . $contact['id'] . ' - ' . $dest_url);
1463                         logger('Returned XML: ' . $xml, LOGGER_DATA);
1464                         Contact::markForArchival($contact);
1465                         return 3;
1466                 }
1467
1468                 $res = XML::parseString($xml);
1469
1470                 if (empty($res->status)) {
1471                         Contact::markForArchival($contact);
1472                         return -23;
1473                 }
1474
1475                 if (!empty($res->message)) {
1476                         logger('Transmit to ' . $dest_url . ' returned status '.$res->status.' - '.$res->message, LOGGER_DEBUG);
1477                 }
1478
1479                 if (($res->status >= 200) && ($res->status <= 299)) {
1480                         Contact::unmarkForArchival($contact);
1481                 }
1482
1483                 return intval($res->status);
1484         }
1485
1486         /**
1487          * @brief Add new birthday event for this person
1488          *
1489          * @param array  $contact  Contact record
1490          * @param string $birthday Birthday of the contact
1491          * @return void
1492          * @todo Add array type-hint for $contact
1493          */
1494         private static function birthdayEvent($contact, $birthday)
1495         {
1496                 // Check for duplicates
1497                 $r = q(
1498                         "SELECT `id` FROM `event` WHERE `uid` = %d AND `cid` = %d AND `start` = '%s' AND `type` = '%s' LIMIT 1",
1499                         intval($contact['uid']),
1500                         intval($contact['id']),
1501                         DBA::escape(DateTimeFormat::utc($birthday)),
1502                         DBA::escape('birthday')
1503                 );
1504
1505                 if (DBA::isResult($r)) {
1506                         return;
1507                 }
1508
1509                 logger('updating birthday: ' . $birthday . ' for contact ' . $contact['id']);
1510
1511                 $bdtext = L10n::t('%s\'s birthday', $contact['name']);
1512                 $bdtext2 = L10n::t('Happy Birthday %s', ' [url=' . $contact['url'] . ']' . $contact['name'] . '[/url]');
1513
1514                 $r = q(
1515                         "INSERT INTO `event` (`uid`,`cid`,`created`,`edited`,`start`,`finish`,`summary`,`desc`,`type`)
1516                         VALUES ( %d, %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s') ",
1517                         intval($contact['uid']),
1518                         intval($contact['id']),
1519                         DBA::escape(DateTimeFormat::utcNow()),
1520                         DBA::escape(DateTimeFormat::utcNow()),
1521                         DBA::escape(DateTimeFormat::utc($birthday)),
1522                         DBA::escape(DateTimeFormat::utc($birthday . ' + 1 day ')),
1523                         DBA::escape($bdtext),
1524                         DBA::escape($bdtext2),
1525                         DBA::escape('birthday')
1526                 );
1527         }
1528
1529         /**
1530          * @brief Fetch the author data from head or entry items
1531          *
1532          * @param object $xpath     XPath object
1533          * @param object $context   In which context should the data be searched
1534          * @param array  $importer  Record of the importer user mixed with contact of the content
1535          * @param string $element   Element name from which the data is fetched
1536          * @param bool   $onlyfetch Should the data only be fetched or should it update the contact record as well
1537          * @param string $xml       optional, default empty
1538          *
1539          * @return array Relevant data of the author
1540          * @todo Find good type-hints for all parameter
1541          */
1542         private static function fetchauthor($xpath, $context, $importer, $element, $onlyfetch, $xml = "")
1543         {
1544                 $author = [];
1545                 $author["name"] = XML::getFirstNodeValue($xpath, $element."/atom:name/text()", $context);
1546                 $author["link"] = XML::getFirstNodeValue($xpath, $element."/atom:uri/text()", $context);
1547
1548                 $fields = ['id', 'uid', 'url', 'network', 'avatar-date', 'avatar', 'name-date', 'uri-date', 'addr',
1549                         'name', 'nick', 'about', 'location', 'keywords', 'xmpp', 'bdyear', 'bd', 'hidden', 'contact-type'];
1550                 $condition = ["`uid` = ? AND `nurl` = ? AND `network` != ?",
1551                         $importer["importer_uid"], normalise_link($author["link"]), NETWORK_STATUSNET];
1552                 $contact_old = DBA::selectFirst('contact', $fields, $condition);
1553
1554                 if (DBA::isResult($contact_old)) {
1555                         $author["contact-id"] = $contact_old["id"];
1556                         $author["network"] = $contact_old["network"];
1557                 } else {
1558                         if (!$onlyfetch) {
1559                                 logger("Contact ".$author["link"]." wasn't found for user ".$importer["importer_uid"]." XML: ".$xml, LOGGER_DEBUG);
1560                         }
1561
1562                         $author["contact-unknown"] = true;
1563                         $author["contact-id"] = $importer["id"];
1564                         $author["network"] = $importer["network"];
1565                         $onlyfetch = true;
1566                 }
1567
1568                 // Until now we aren't serving different sizes - but maybe later
1569                 $avatarlist = [];
1570                 /// @todo check if "avatar" or "photo" would be the best field in the specification
1571                 $avatars = $xpath->query($element . "/atom:link[@rel='avatar']", $context);
1572                 foreach ($avatars as $avatar) {
1573                         $href = "";
1574                         $width = 0;
1575                         foreach ($avatar->attributes as $attributes) {
1576                                 /// @TODO Rewrite these similar if() to one switch
1577                                 if ($attributes->name == "href") {
1578                                         $href = $attributes->textContent;
1579                                 }
1580                                 if ($attributes->name == "width") {
1581                                         $width = $attributes->textContent;
1582                                 }
1583                                 if ($attributes->name == "updated") {
1584                                         $author["avatar-date"] = $attributes->textContent;
1585                                 }
1586                         }
1587                         if (($width > 0) && ($href != "")) {
1588                                 $avatarlist[$width] = $href;
1589                         }
1590                 }
1591
1592                 if (count($avatarlist) > 0) {
1593                         krsort($avatarlist);
1594                         $author["avatar"] = current($avatarlist);
1595                 }
1596
1597                 if (DBA::isResult($contact_old) && !$onlyfetch) {
1598                         logger("Check if contact details for contact " . $contact_old["id"] . " (" . $contact_old["nick"] . ") have to be updated.", LOGGER_DEBUG);
1599
1600                         $poco = ["url" => $contact_old["url"]];
1601
1602                         // When was the last change to name or uri?
1603                         $name_element = $xpath->query($element . "/atom:name", $context)->item(0);
1604                         foreach ($name_element->attributes as $attributes) {
1605                                 if ($attributes->name == "updated") {
1606                                         $poco["name-date"] = $attributes->textContent;
1607                                 }
1608                         }
1609
1610                         $link_element = $xpath->query($element . "/atom:link", $context)->item(0);
1611                         foreach ($link_element->attributes as $attributes) {
1612                                 if ($attributes->name == "updated") {
1613                                         $poco["uri-date"] = $attributes->textContent;
1614                                 }
1615                         }
1616
1617                         // Update contact data
1618                         $value = XML::getFirstNodeValue($xpath, $element . "/dfrn:handle/text()", $context);
1619                         if ($value != "") {
1620                                 $poco["addr"] = $value;
1621                         }
1622
1623                         $value = XML::getFirstNodeValue($xpath, $element . "/poco:displayName/text()", $context);
1624                         if ($value != "") {
1625                                 $poco["name"] = $value;
1626                         }
1627
1628                         $value = XML::getFirstNodeValue($xpath, $element . "/poco:preferredUsername/text()", $context);
1629                         if ($value != "") {
1630                                 $poco["nick"] = $value;
1631                         }
1632
1633                         $value = XML::getFirstNodeValue($xpath, $element . "/poco:note/text()", $context);
1634                         if ($value != "") {
1635                                 $poco["about"] = $value;
1636                         }
1637
1638                         $value = XML::getFirstNodeValue($xpath, $element . "/poco:address/poco:formatted/text()", $context);
1639                         if ($value != "") {
1640                                 $poco["location"] = $value;
1641                         }
1642
1643                         /// @todo Only search for elements with "poco:type" = "xmpp"
1644                         $value = XML::getFirstNodeValue($xpath, $element . "/poco:ims/poco:value/text()", $context);
1645                         if ($value != "") {
1646                                 $poco["xmpp"] = $value;
1647                         }
1648
1649                         /// @todo Add support for the following fields that we don't support by now in the contact table:
1650                         /// - poco:utcOffset
1651                         /// - poco:urls
1652                         /// - poco:locality
1653                         /// - poco:region
1654                         /// - poco:country
1655
1656                         // If the "hide" element is present then the profile isn't searchable.
1657                         $hide = intval(XML::getFirstNodeValue($xpath, $element . "/dfrn:hide/text()", $context) == "true");
1658
1659                         logger("Hidden status for contact " . $contact_old["url"] . ": " . $hide, LOGGER_DEBUG);
1660
1661                         // If the contact isn't searchable then set the contact to "hidden".
1662                         // Problem: This can be manually overridden by the user.
1663                         if ($hide) {
1664                                 $contact_old["hidden"] = true;
1665                         }
1666
1667                         // Save the keywords into the contact table
1668                         $tags = [];
1669                         $tagelements = $xpath->evaluate($element . "/poco:tags/text()", $context);
1670                         foreach ($tagelements as $tag) {
1671                                 $tags[$tag->nodeValue] = $tag->nodeValue;
1672                         }
1673
1674                         if (count($tags)) {
1675                                 $poco["keywords"] = implode(", ", $tags);
1676                         }
1677
1678                         // "dfrn:birthday" contains the birthday converted to UTC
1679                         $birthday = XML::getFirstNodeValue($xpath, $element . "/poco:birthday/text()", $context);
1680
1681                         if (strtotime($birthday) > time()) {
1682                                 $bd_timestamp = strtotime($birthday);
1683
1684                                 $poco["bdyear"] = date("Y", $bd_timestamp);
1685                         }
1686
1687                         // "poco:birthday" is the birthday in the format "yyyy-mm-dd"
1688                         $value = XML::getFirstNodeValue($xpath, $element . "/poco:birthday/text()", $context);
1689
1690                         if (!in_array($value, ["", "0000-00-00", "0001-01-01"])) {
1691                                 $bdyear = date("Y");
1692                                 $value = str_replace("0000", $bdyear, $value);
1693
1694                                 if (strtotime($value) < time()) {
1695                                         $value = str_replace($bdyear, $bdyear + 1, $value);
1696                                         $bdyear = $bdyear + 1;
1697                                 }
1698
1699                                 $poco["bd"] = $value;
1700                         }
1701
1702                         $contact = array_merge($contact_old, $poco);
1703
1704                         if ($contact_old["bdyear"] != $contact["bdyear"]) {
1705                                 self::birthdayEvent($contact, $birthday);
1706                         }
1707
1708                         // Get all field names
1709                         $fields = [];
1710                         foreach ($contact_old as $field => $data) {
1711                                 $fields[$field] = $data;
1712                         }
1713
1714                         unset($fields["id"]);
1715                         unset($fields["uid"]);
1716                         unset($fields["url"]);
1717                         unset($fields["avatar-date"]);
1718                         unset($fields["avatar"]);
1719                         unset($fields["name-date"]);
1720                         unset($fields["uri-date"]);
1721
1722                         $update = false;
1723                         // Update check for this field has to be done differently
1724                         $datefields = ["name-date", "uri-date"];
1725                         foreach ($datefields as $field) {
1726                                 if (strtotime($contact[$field]) > strtotime($contact_old[$field])) {
1727                                         logger("Difference for contact " . $contact["id"] . " in field '" . $field . "'. New value: '" . $contact[$field] . "', old value '" . $contact_old[$field] . "'", LOGGER_DEBUG);
1728                                         $update = true;
1729                                 }
1730                         }
1731
1732                         foreach ($fields as $field => $data) {
1733                                 if ($contact[$field] != $contact_old[$field]) {
1734                                         logger("Difference for contact " . $contact["id"] . " in field '" . $field . "'. New value: '" . $contact[$field] . "', old value '" . $contact_old[$field] . "'", LOGGER_DEBUG);
1735                                         $update = true;
1736                                 }
1737                         }
1738
1739                         if ($update) {
1740                                 logger("Update contact data for contact " . $contact["id"] . " (" . $contact["nick"] . ")", LOGGER_DEBUG);
1741
1742                                 q(
1743                                         "UPDATE `contact` SET `name` = '%s', `nick` = '%s', `about` = '%s', `location` = '%s',
1744                                         `addr` = '%s', `keywords` = '%s', `bdyear` = '%s', `bd` = '%s', `hidden` = %d,
1745                                         `xmpp` = '%s', `name-date`  = '%s', `uri-date` = '%s'
1746                                         WHERE `id` = %d AND `network` = '%s'",
1747                                         DBA::escape($contact["name"]), DBA::escape($contact["nick"]), DBA::escape($contact["about"]),   DBA::escape($contact["location"]),
1748                                         DBA::escape($contact["addr"]), DBA::escape($contact["keywords"]), DBA::escape($contact["bdyear"]),
1749                                         DBA::escape($contact["bd"]), intval($contact["hidden"]), DBA::escape($contact["xmpp"]),
1750                                         DBA::escape(DateTimeFormat::utc($contact["name-date"])), DBA::escape(DateTimeFormat::utc($contact["uri-date"])),
1751                                         intval($contact["id"]), DBA::escape($contact["network"])
1752                                 );
1753                         }
1754
1755                         Contact::updateAvatar(
1756                                 $author['avatar'],
1757                                 $importer['importer_uid'],
1758                                 $contact['id'],
1759                                 (strtotime($contact['avatar-date']) > strtotime($contact_old['avatar-date']) || ($author['avatar'] != $contact_old['avatar']))
1760                         );
1761
1762                         /*
1763                          * The generation is a sign for the reliability of the provided data.
1764                          * It is used in the socgraph.php to prevent that old contact data
1765                          * that was relayed over several servers can overwrite contact
1766                          * data that we received directly.
1767                          */
1768
1769                         $poco["generation"] = 2;
1770                         $poco["photo"] = $author["avatar"];
1771                         $poco["hide"] = $hide;
1772                         $poco["contact-type"] = $contact["contact-type"];
1773                         $gcid = GContact::update($poco);
1774
1775                         GContact::link($gcid, $importer["importer_uid"], $contact["id"]);
1776                 }
1777
1778                 return $author;
1779         }
1780
1781         /**
1782          * @brief Transforms activity objects into an XML string
1783          *
1784          * @param object $xpath    XPath object
1785          * @param object $activity Activity object
1786          * @param string $element  element name
1787          *
1788          * @return string XML string
1789          * @todo Find good type-hints for all parameter
1790          */
1791         private static function transformActivity($xpath, $activity, $element)
1792         {
1793                 if (!is_object($activity)) {
1794                         return "";
1795                 }
1796
1797                 $obj_doc = new DOMDocument("1.0", "utf-8");
1798                 $obj_doc->formatOutput = true;
1799
1800                 $obj_element = $obj_doc->createElementNS(NAMESPACE_ATOM1, $element);
1801
1802                 $activity_type = $xpath->query("activity:object-type/text()", $activity)->item(0)->nodeValue;
1803                 XML::addElement($obj_doc, $obj_element, "type", $activity_type);
1804
1805                 $id = $xpath->query("atom:id", $activity)->item(0);
1806                 if (is_object($id)) {
1807                         $obj_element->appendChild($obj_doc->importNode($id, true));
1808                 }
1809
1810                 $title = $xpath->query("atom:title", $activity)->item(0);
1811                 if (is_object($title)) {
1812                         $obj_element->appendChild($obj_doc->importNode($title, true));
1813                 }
1814
1815                 $links = $xpath->query("atom:link", $activity);
1816                 if (is_object($links)) {
1817                         foreach ($links as $link) {
1818                                 $obj_element->appendChild($obj_doc->importNode($link, true));
1819                         }
1820                 }
1821
1822                 $content = $xpath->query("atom:content", $activity)->item(0);
1823                 if (is_object($content)) {
1824                         $obj_element->appendChild($obj_doc->importNode($content, true));
1825                 }
1826
1827                 $obj_doc->appendChild($obj_element);
1828
1829                 $objxml = $obj_doc->saveXML($obj_element);
1830
1831                 /// @todo This isn't totally clean. We should find a way to transform the namespaces
1832                 $objxml = str_replace("<".$element.' xmlns="http://www.w3.org/2005/Atom">', "<".$element.">", $objxml);
1833                 return($objxml);
1834         }
1835
1836         /**
1837          * @brief Processes the mail elements
1838          *
1839          * @param object $xpath    XPath object
1840          * @param object $mail     mail elements
1841          * @param array  $importer Record of the importer user mixed with contact of the content
1842          * @return void
1843          * @todo Find good type-hints for all parameter
1844          */
1845         private static function processMail($xpath, $mail, $importer)
1846         {
1847                 logger("Processing mails");
1848
1849                 /// @TODO Rewrite this to one statement
1850                 $msg = [];
1851                 $msg["uid"] = $importer["importer_uid"];
1852                 $msg["from-name"] = $xpath->query("dfrn:sender/dfrn:name/text()", $mail)->item(0)->nodeValue;
1853                 $msg["from-url"] = $xpath->query("dfrn:sender/dfrn:uri/text()", $mail)->item(0)->nodeValue;
1854                 $msg["from-photo"] = $xpath->query("dfrn:sender/dfrn:avatar/text()", $mail)->item(0)->nodeValue;
1855                 $msg["contact-id"] = $importer["id"];
1856                 $msg["uri"] = $xpath->query("dfrn:id/text()", $mail)->item(0)->nodeValue;
1857                 $msg["parent-uri"] = $xpath->query("dfrn:in-reply-to/text()", $mail)->item(0)->nodeValue;
1858                 $msg["created"] = DateTimeFormat::utc($xpath->query("dfrn:sentdate/text()", $mail)->item(0)->nodeValue);
1859                 $msg["title"] = $xpath->query("dfrn:subject/text()", $mail)->item(0)->nodeValue;
1860                 $msg["body"] = $xpath->query("dfrn:content/text()", $mail)->item(0)->nodeValue;
1861                 $msg["seen"] = 0;
1862                 $msg["replied"] = 0;
1863
1864                 DBA::insert('mail', $msg);
1865
1866                 // send notifications.
1867                 /// @TODO Arange this mess
1868                 $notif_params = [
1869                         "type" => NOTIFY_MAIL,
1870                         "notify_flags" => $importer["notify-flags"],
1871                         "language" => $importer["language"],
1872                         "to_name" => $importer["username"],
1873                         "to_email" => $importer["email"],
1874                         "uid" => $importer["importer_uid"],
1875                         "item" => $msg,
1876                         "source_name" => $msg["from-name"],
1877                         "source_link" => $importer["url"],
1878                         "source_photo" => $importer["thumb"],
1879                         "verb" => ACTIVITY_POST,
1880                         "otype" => "mail"
1881                 ];
1882
1883                 notification($notif_params);
1884
1885                 logger("Mail is processed, notification was sent.");
1886         }
1887
1888         /**
1889          * @brief Processes the suggestion elements
1890          *
1891          * @param object $xpath      XPath object
1892          * @param object $suggestion suggestion elements
1893          * @param array  $importer   Record of the importer user mixed with contact of the content
1894          * @return boolean
1895          * @todo Find good type-hints for all parameter
1896          */
1897         private static function processSuggestion($xpath, $suggestion, $importer)
1898         {
1899                 $a = get_app();
1900
1901                 logger("Processing suggestions");
1902
1903                 /// @TODO Rewrite this to one statement
1904                 $suggest = [];
1905                 $suggest["uid"] = $importer["importer_uid"];
1906                 $suggest["cid"] = $importer["id"];
1907                 $suggest["url"] = $xpath->query("dfrn:url/text()", $suggestion)->item(0)->nodeValue;
1908                 $suggest["name"] = $xpath->query("dfrn:name/text()", $suggestion)->item(0)->nodeValue;
1909                 $suggest["photo"] = $xpath->query("dfrn:photo/text()", $suggestion)->item(0)->nodeValue;
1910                 $suggest["request"] = $xpath->query("dfrn:request/text()", $suggestion)->item(0)->nodeValue;
1911                 $suggest["body"] = $xpath->query("dfrn:note/text()", $suggestion)->item(0)->nodeValue;
1912
1913                 // Does our member already have a friend matching this description?
1914
1915                 $r = q(
1916                         "SELECT `id` FROM `contact` WHERE `name` = '%s' AND `nurl` = '%s' AND `uid` = %d LIMIT 1",
1917                         DBA::escape($suggest["name"]),
1918                         DBA::escape(normalise_link($suggest["url"])),
1919                         intval($suggest["uid"])
1920                 );
1921
1922                 /*
1923                  * The valid result means the friend we're about to send a friend
1924                  * suggestion already has them in their contact, which means no further
1925                  * action is required.
1926                  *
1927                  * @see https://github.com/friendica/friendica/pull/3254#discussion_r107315246
1928                  */
1929                 if (DBA::isResult($r)) {
1930                         return false;
1931                 }
1932
1933                 // Do we already have an fcontact record for this person?
1934
1935                 $fid = 0;
1936                 $r = q(
1937                         "SELECT `id` FROM `fcontact` WHERE `url` = '%s' AND `name` = '%s' AND `request` = '%s' LIMIT 1",
1938                         DBA::escape($suggest["url"]),
1939                         DBA::escape($suggest["name"]),
1940                         DBA::escape($suggest["request"])
1941                 );
1942                 if (DBA::isResult($r)) {
1943                         $fid = $r[0]["id"];
1944
1945                         // OK, we do. Do we already have an introduction for this person ?
1946                         $r = q(
1947                                 "SELECT `id` FROM `intro` WHERE `uid` = %d AND `fid` = %d LIMIT 1",
1948                                 intval($suggest["uid"]),
1949                                 intval($fid)
1950                         );
1951
1952                         /*
1953                          * The valid result means the friend we're about to send a friend
1954                          * suggestion already has them in their contact, which means no further
1955                          * action is required.
1956                          *
1957                          * @see https://github.com/friendica/friendica/pull/3254#discussion_r107315246
1958                          */
1959                         if (DBA::isResult($r)) {
1960                                 return false;
1961                         }
1962                 }
1963                 if (!$fid) {
1964                         $r = q(
1965                                 "INSERT INTO `fcontact` (`name`,`url`,`photo`,`request`) VALUES ('%s', '%s', '%s', '%s')",
1966                                 DBA::escape($suggest["name"]),
1967                                 DBA::escape($suggest["url"]),
1968                                 DBA::escape($suggest["photo"]),
1969                                 DBA::escape($suggest["request"])
1970                         );
1971                 }
1972                 $r = q(
1973                         "SELECT `id` FROM `fcontact` WHERE `url` = '%s' AND `name` = '%s' AND `request` = '%s' LIMIT 1",
1974                         DBA::escape($suggest["url"]),
1975                         DBA::escape($suggest["name"]),
1976                         DBA::escape($suggest["request"])
1977                 );
1978
1979                 /*
1980                  * If no record in fcontact is found, below INSERT statement will not
1981                  * link an introduction to it.
1982                  */
1983                 if (!DBA::isResult($r)) {
1984                         // Database record did not get created. Quietly give up.
1985                         killme();
1986                 }
1987
1988                 $fid = $r[0]["id"];
1989
1990                 $hash = random_string();
1991
1992                 $r = q(
1993                         "INSERT INTO `intro` (`uid`, `fid`, `contact-id`, `note`, `hash`, `datetime`, `blocked`)
1994                         VALUES(%d, %d, %d, '%s', '%s', '%s', %d)",
1995                         intval($suggest["uid"]),
1996                         intval($fid),
1997                         intval($suggest["cid"]),
1998                         DBA::escape($suggest["body"]),
1999                         DBA::escape($hash),
2000                         DBA::escape(DateTimeFormat::utcNow()),
2001                         intval(0)
2002                 );
2003
2004                 notification(
2005                         [
2006                                 "type"         => NOTIFY_SUGGEST,
2007                                 "notify_flags" => $importer["notify-flags"],
2008                                 "language"     => $importer["language"],
2009                                 "to_name"      => $importer["username"],
2010                                 "to_email"     => $importer["email"],
2011                                 "uid"          => $importer["importer_uid"],
2012                                 "item"         => $suggest,
2013                                 "link"         => System::baseUrl()."/notifications/intros",
2014                                 "source_name"  => $importer["name"],
2015                                 "source_link"  => $importer["url"],
2016                                 "source_photo" => $importer["photo"],
2017                                 "verb"         => ACTIVITY_REQ_FRIEND,
2018                                 "otype"        => "intro"]
2019                 );
2020
2021                 return true;
2022         }
2023
2024         /**
2025          * @brief Processes the relocation elements
2026          *
2027          * @param object $xpath      XPath object
2028          * @param object $relocation relocation elements
2029          * @param array  $importer   Record of the importer user mixed with contact of the content
2030          * @return boolean
2031          * @todo Find good type-hints for all parameter
2032          */
2033         private static function processRelocation($xpath, $relocation, $importer)
2034         {
2035                 logger("Processing relocations");
2036
2037                 /// @TODO Rewrite this to one statement
2038                 $relocate = [];
2039                 $relocate["uid"] = $importer["importer_uid"];
2040                 $relocate["cid"] = $importer["id"];
2041                 $relocate["url"] = $xpath->query("dfrn:url/text()", $relocation)->item(0)->nodeValue;
2042                 $relocate["addr"] = $xpath->query("dfrn:addr/text()", $relocation)->item(0)->nodeValue;
2043                 $relocate["name"] = $xpath->query("dfrn:name/text()", $relocation)->item(0)->nodeValue;
2044                 $relocate["avatar"] = $xpath->query("dfrn:avatar/text()", $relocation)->item(0)->nodeValue;
2045                 $relocate["photo"] = $xpath->query("dfrn:photo/text()", $relocation)->item(0)->nodeValue;
2046                 $relocate["thumb"] = $xpath->query("dfrn:thumb/text()", $relocation)->item(0)->nodeValue;
2047                 $relocate["micro"] = $xpath->query("dfrn:micro/text()", $relocation)->item(0)->nodeValue;
2048                 $relocate["request"] = $xpath->query("dfrn:request/text()", $relocation)->item(0)->nodeValue;
2049                 $relocate["confirm"] = $xpath->query("dfrn:confirm/text()", $relocation)->item(0)->nodeValue;
2050                 $relocate["notify"] = $xpath->query("dfrn:notify/text()", $relocation)->item(0)->nodeValue;
2051                 $relocate["poll"] = $xpath->query("dfrn:poll/text()", $relocation)->item(0)->nodeValue;
2052                 $relocate["sitepubkey"] = $xpath->query("dfrn:sitepubkey/text()", $relocation)->item(0)->nodeValue;
2053
2054                 if (($relocate["avatar"] == "") && ($relocate["photo"] != "")) {
2055                         $relocate["avatar"] = $relocate["photo"];
2056                 }
2057
2058                 if ($relocate["addr"] == "") {
2059                         $relocate["addr"] = preg_replace("=(https?://)(.*)/profile/(.*)=ism", "$3@$2", $relocate["url"]);
2060                 }
2061
2062                 // update contact
2063                 $r = q(
2064                         "SELECT `photo`, `url` FROM `contact` WHERE `id` = %d AND `uid` = %d",
2065                         intval($importer["id"]),
2066                         intval($importer["importer_uid"])
2067                 );
2068
2069                 if (!DBA::isResult($r)) {
2070                         logger("Query failed to execute, no result returned in " . __FUNCTION__);
2071                         return false;
2072                 }
2073
2074                 $old = $r[0];
2075
2076                 // Update the gcontact entry
2077                 $relocate["server_url"] = preg_replace("=(https?://)(.*)/profile/(.*)=ism", "$1$2", $relocate["url"]);
2078
2079                 $fields = ['name' => $relocate["name"], 'photo' => $relocate["avatar"],
2080                         'url' => $relocate["url"], 'nurl' => normalise_link($relocate["url"]),
2081                         'addr' => $relocate["addr"], 'connect' => $relocate["addr"],
2082                         'notify' => $relocate["notify"], 'server_url' => $relocate["server_url"]];
2083                 DBA::update('gcontact', $fields, ['nurl' => normalise_link($old["url"])]);
2084
2085                 // Update the contact table. We try to find every entry.
2086                 $fields = ['name' => $relocate["name"], 'avatar' => $relocate["avatar"],
2087                         'url' => $relocate["url"], 'nurl' => normalise_link($relocate["url"]),
2088                         'addr' => $relocate["addr"], 'request' => $relocate["request"],
2089                         'confirm' => $relocate["confirm"], 'notify' => $relocate["notify"],
2090                         'poll' => $relocate["poll"], 'site-pubkey' => $relocate["sitepubkey"]];
2091                 $condition = ["(`id` = ?) OR (`nurl` = ?)", $importer["id"], normalise_link($old["url"])];
2092
2093                 DBA::update('contact', $fields, $condition);
2094
2095                 Contact::updateAvatar($relocate["avatar"], $importer["importer_uid"], $importer["id"], true);
2096
2097                 logger('Contacts are updated.');
2098
2099                 /// @TODO
2100                 /// merge with current record, current contents have priority
2101                 /// update record, set url-updated
2102                 /// update profile photos
2103                 /// schedule a scan?
2104                 return true;
2105         }
2106
2107         /**
2108          * @brief Updates an item
2109          *
2110          * @param array $current   the current item record
2111          * @param array $item      the new item record
2112          * @param array $importer  Record of the importer user mixed with contact of the content
2113          * @param int   $entrytype Is it a toplevel entry, a comment or a relayed comment?
2114          * @return mixed
2115          * @todo set proper type-hints (array?)
2116          */
2117         private static function updateContent($current, $item, $importer, $entrytype)
2118         {
2119                 $changed = false;
2120
2121                 if (self::isEditedTimestampNewer($current, $item)) {
2122                         // do not accept (ignore) an earlier edit than one we currently have.
2123                         if (DateTimeFormat::utc($item["edited"]) < $current["edited"]) {
2124                                 return false;
2125                         }
2126
2127                         $fields = ['title' => defaults($item, 'title', ''), 'body' => defaults($item, 'body', ''),
2128                                         'tag' => defaults($item, 'tag', ''), 'changed' => DateTimeFormat::utcNow(),
2129                                         'edited' => DateTimeFormat::utc($item["edited"])];
2130
2131                         $condition = ["`uri` = ? AND `uid` IN (0, ?)", $item["uri"], $importer["importer_uid"]];
2132                         Item::update($fields, $condition);
2133
2134                         $changed = true;
2135                 }
2136                 return $changed;
2137         }
2138
2139         /**
2140          * @brief Detects the entry type of the item
2141          *
2142          * @param array $importer Record of the importer user mixed with contact of the content
2143          * @param array $item     the new item record
2144          *
2145          * @return int Is it a toplevel entry, a comment or a relayed comment?
2146          * @todo set proper type-hints (array?)
2147          */
2148         private static function getEntryType($importer, $item)
2149         {
2150                 if ($item["parent-uri"] != $item["uri"]) {
2151                         $community = false;
2152
2153                         if ($importer["page-flags"] == PAGE_COMMUNITY || $importer["page-flags"] == PAGE_PRVGROUP) {
2154                                 $sql_extra = "";
2155                                 $community = true;
2156                                 logger("possible community action");
2157                         } else {
2158                                 $sql_extra = " AND `contact`.`self` AND `item`.`wall` ";
2159                         }
2160
2161                         // was the top-level post for this action written by somebody on this site?
2162                         // Specifically, the recipient?
2163
2164                         $is_a_remote_action = false;
2165
2166                         $parent = Item::selectFirst(['parent-uri'], ['uri' => $item["parent-uri"]]);
2167                         if (DBA::isResult($parent)) {
2168                                 $r = q(
2169                                         "SELECT `item`.`forum_mode`, `item`.`wall` FROM `item`
2170                                         INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
2171                                         WHERE `item`.`uri` = '%s' AND (`item`.`parent-uri` = '%s' OR `item`.`thr-parent` = '%s')
2172                                         AND `item`.`uid` = %d
2173                                         $sql_extra
2174                                         LIMIT 1",
2175                                         DBA::escape($parent["parent-uri"]),
2176                                         DBA::escape($parent["parent-uri"]),
2177                                         DBA::escape($parent["parent-uri"]),
2178                                         intval($importer["importer_uid"])
2179                                 );
2180                                 if (DBA::isResult($r)) {
2181                                         $is_a_remote_action = true;
2182                                 }
2183                         }
2184
2185                         /*
2186                          * Does this have the characteristics of a community or private group action?
2187                          * If it's an action to a wall post on a community/prvgroup page it's a
2188                          * valid community action. Also forum_mode makes it valid for sure.
2189                          * If neither, it's not.
2190                          */
2191                         if ($is_a_remote_action && $community && (!$r[0]["forum_mode"]) && (!$r[0]["wall"])) {
2192                                 $is_a_remote_action = false;
2193                                 logger("not a community action");
2194                         }
2195
2196                         if ($is_a_remote_action) {
2197                                 return DFRN::REPLY_RC;
2198                         } else {
2199                                 return DFRN::REPLY;
2200                         }
2201                 } else {
2202                         return DFRN::TOP_LEVEL;
2203                 }
2204         }
2205
2206         /**
2207          * @brief Send a "poke"
2208          *
2209          * @param array $item      the new item record
2210          * @param array $importer  Record of the importer user mixed with contact of the content
2211          * @param int   $posted_id The record number of item record that was just posted
2212          * @return void
2213          * @todo set proper type-hints (array?)
2214          */
2215         private static function doPoke($item, $importer, $posted_id)
2216         {
2217                 $verb = urldecode(substr($item["verb"], strpos($item["verb"], "#")+1));
2218                 if (!$verb) {
2219                         return;
2220                 }
2221                 $xo = XML::parseString($item["object"], false);
2222
2223                 if (($xo->type == ACTIVITY_OBJ_PERSON) && ($xo->id)) {
2224                         // somebody was poked/prodded. Was it me?
2225                         foreach ($xo->link as $l) {
2226                                 $atts = $l->attributes();
2227                                 switch ($atts["rel"]) {
2228                                         case "alternate":
2229                                                 $Blink = $atts["href"];
2230                                                 break;
2231                                         default:
2232                                                 break;
2233                                 }
2234                         }
2235
2236                         if ($Blink && link_compare($Blink, System::baseUrl() . "/profile/" . $importer["nickname"])) {
2237                                 $author = DBA::selectFirst('contact', ['name', 'thumb', 'url'], ['id' => $item['author-id']]);
2238
2239                                 // send a notification
2240                                 notification(
2241                                         [
2242                                         "type"         => NOTIFY_POKE,
2243                                         "notify_flags" => $importer["notify-flags"],
2244                                         "language"     => $importer["language"],
2245                                         "to_name"      => $importer["username"],
2246                                         "to_email"     => $importer["email"],
2247                                         "uid"          => $importer["importer_uid"],
2248                                         "item"         => $item,
2249                                         "link"         => System::baseUrl()."/display/".urlencode(Item::getGuidById($posted_id)),
2250                                         "source_name"  => $author["name"],
2251                                         "source_link"  => $author["url"],
2252                                         "source_photo" => $author["thumb"],
2253                                         "verb"         => $item["verb"],
2254                                         "otype"        => "person",
2255                                         "activity"     => $verb,
2256                                         "parent"       => $item["parent"]]
2257                                 );
2258                         }
2259                 }
2260         }
2261
2262         /**
2263          * @brief Processes several actions, depending on the verb
2264          *
2265          * @param int   $entrytype Is it a toplevel entry, a comment or a relayed comment?
2266          * @param array $importer  Record of the importer user mixed with contact of the content
2267          * @param array $item      the new item record
2268          * @param bool  $is_like   Is the verb a "like"?
2269          *
2270          * @return bool Should the processing of the entries be continued?
2271          * @todo set proper type-hints (array?)
2272          */
2273         private static function processVerbs($entrytype, $importer, &$item, &$is_like)
2274         {
2275                 logger("Process verb ".$item["verb"]." and object-type ".$item["object-type"]." for entrytype ".$entrytype, LOGGER_DEBUG);
2276
2277                 if (($entrytype == DFRN::TOP_LEVEL)) {
2278                         // The filling of the the "contact" variable is done for legcy reasons
2279                         // The functions below are partly used by ostatus.php as well - where we have this variable
2280                         $r = q("SELECT * FROM `contact` WHERE `id` = %d", intval($importer["id"]));
2281                         $contact = $r[0];
2282                         $nickname = $contact["nick"];
2283
2284                         // Big question: Do we need these functions? They were part of the "consume_feed" function.
2285                         // This function once was responsible for DFRN and OStatus.
2286                         if (activity_match($item["verb"], ACTIVITY_FOLLOW)) {
2287                                 logger("New follower");
2288                                 Contact::addRelationship($importer, $contact, $item, $nickname);
2289                                 return false;
2290                         }
2291                         if (activity_match($item["verb"], ACTIVITY_UNFOLLOW)) {
2292                                 logger("Lost follower");
2293                                 Contact::removeFollower($importer, $contact, $item);
2294                                 return false;
2295                         }
2296                         if (activity_match($item["verb"], ACTIVITY_REQ_FRIEND)) {
2297                                 logger("New friend request");
2298                                 Contact::addRelationship($importer, $contact, $item, $nickname, true);
2299                                 return false;
2300                         }
2301                         if (activity_match($item["verb"], ACTIVITY_UNFRIEND)) {
2302                                 logger("Lost sharer");
2303                                 Contact::removeSharer($importer, $contact, $item);
2304                                 return false;
2305                         }
2306                 } else {
2307                         if (($item["verb"] == ACTIVITY_LIKE)
2308                                 || ($item["verb"] == ACTIVITY_DISLIKE)
2309                                 || ($item["verb"] == ACTIVITY_ATTEND)
2310                                 || ($item["verb"] == ACTIVITY_ATTENDNO)
2311                                 || ($item["verb"] == ACTIVITY_ATTENDMAYBE)
2312                         ) {
2313                                 $is_like = true;
2314                                 $item["gravity"] = GRAVITY_ACTIVITY;
2315                                 // only one like or dislike per person
2316                                 // splitted into two queries for performance issues
2317                                 $condition = ['uid' => $item["uid"], 'author-id' => $item["author-id"], 'gravity' => GRAVITY_ACTIVITY,
2318                                         'verb' => $item["verb"], 'parent-uri' => $item["parent-uri"]];
2319                                 if (Item::exists($condition)) {
2320                                         return false;
2321                                 }
2322
2323                                 $condition = ['uid' => $item["uid"], 'author-id' => $item["author-id"], 'gravity' => GRAVITY_ACTIVITY,
2324                                         'verb' => $item["verb"], 'thr-parent' => $item["parent-uri"]];
2325                                 if (Item::exists($condition)) {
2326                                         return false;
2327                                 }
2328                         } else {
2329                                 $is_like = false;
2330                         }
2331
2332                         if (($item["verb"] == ACTIVITY_TAG) && ($item["object-type"] == ACTIVITY_OBJ_TAGTERM)) {
2333                                 $xo = XML::parseString($item["object"], false);
2334                                 $xt = XML::parseString($item["target"], false);
2335
2336                                 if ($xt->type == ACTIVITY_OBJ_NOTE) {
2337                                         $item_tag = Item::selectFirst(['id', 'tag'], ['uri' => $xt->id, 'uid' => $importer["importer_uid"]]);
2338
2339                                         if (!DBA::isResult($item_tag)) {
2340                                                 logger("Query failed to execute, no result returned in " . __FUNCTION__);
2341                                                 return false;
2342                                         }
2343
2344                                         // extract tag, if not duplicate, add to parent item
2345                                         if ($xo->content) {
2346                                                 if (!stristr($item_tag["tag"], trim($xo->content))) {
2347                                                         $tag = $item_tag["tag"] . (strlen($item_tag["tag"]) ? ',' : '') . '#[url=' . $xo->id . ']'. $xo->content . '[/url]';
2348                                                         Item::update(['tag' => $tag], ['id' => $item_tag["id"]]);
2349                                                 }
2350                                         }
2351                                 }
2352                         }
2353                 }
2354                 return true;
2355         }
2356
2357         /**
2358          * @brief Processes the link elements
2359          *
2360          * @param object $links link elements
2361          * @param array  $item  the item record
2362          * @return void
2363          * @todo set proper type-hints
2364          */
2365         private static function parseLinks($links, &$item)
2366         {
2367                 $rel = "";
2368                 $href = "";
2369                 $type = "";
2370                 $length = "0";
2371                 $title = "";
2372                 foreach ($links as $link) {
2373                         foreach ($link->attributes as $attributes) {
2374                                 switch ($attributes->name) {
2375                                         case "href"  : $href   = $attributes->textContent; break;
2376                                         case "rel"   : $rel    = $attributes->textContent; break;
2377                                         case "type"  : $type   = $attributes->textContent; break;
2378                                         case "length": $length = $attributes->textContent; break;
2379                                         case "title" : $title  = $attributes->textContent; break;
2380                                 }
2381                         }
2382                         if (($rel != "") && ($href != "")) {
2383                                 switch ($rel) {
2384                                         case "alternate":
2385                                                 $item["plink"] = $href;
2386                                                 break;
2387                                         case "enclosure":
2388                                                 $enclosure = $href;
2389                                                 if (strlen($item["attach"])) {
2390                                                         $item["attach"] .= ",";
2391                                                 }
2392
2393                                                 $item["attach"] .= '[attach]href="' . $href . '" length="' . $length . '" type="' . $type . '" title="' . $title . '"[/attach]';
2394                                                 break;
2395                                 }
2396                         }
2397                 }
2398         }
2399
2400         /**
2401          * @brief Processes the entry elements which contain the items and comments
2402          *
2403          * @param array  $header   Array of the header elements that always stay the same
2404          * @param object $xpath    XPath object
2405          * @param object $entry    entry elements
2406          * @param array  $importer Record of the importer user mixed with contact of the content
2407          * @param object $xml      xml
2408          * @return void
2409          * @todo Add type-hints
2410          */
2411         private static function processEntry($header, $xpath, $entry, $importer, $xml)
2412         {
2413                 logger("Processing entries");
2414
2415                 $item = $header;
2416
2417                 $item["protocol"] = PROTOCOL_DFRN;
2418
2419                 $item["source"] = $xml;
2420
2421                 // Get the uri
2422                 $item["uri"] = XML::getFirstNodeValue($xpath, "atom:id/text()", $entry);
2423
2424                 $item["edited"] = XML::getFirstNodeValue($xpath, "atom:updated/text()", $entry);
2425
2426                 $current = Item::selectFirst(['id', 'uid', 'edited', 'body'],
2427                         ['uri' => $item["uri"], 'uid' => $importer["importer_uid"]]
2428                 );
2429                 // Is there an existing item?
2430                 if (DBA::isResult($current) && !self::isEditedTimestampNewer($current, $item)) {
2431                         logger("Item ".$item["uri"]." (".$item['edited'].") already existed.", LOGGER_DEBUG);
2432                         return;
2433                 }
2434
2435                 // Fetch the owner
2436                 $owner = self::fetchauthor($xpath, $entry, $importer, "dfrn:owner", true);
2437
2438                 $owner_unknown = (isset($owner["contact-unknown"]) && $owner["contact-unknown"]);
2439
2440                 $item["owner-link"] = $owner["link"];
2441                 $item["owner-id"] = Contact::getIdForURL($owner["link"], 0);
2442
2443                 // fetch the author
2444                 $author = self::fetchauthor($xpath, $entry, $importer, "atom:author", true);
2445
2446                 $item["author-link"] = $author["link"];
2447                 $item["author-id"] = Contact::getIdForURL($author["link"], 0);
2448
2449                 $item["title"] = XML::getFirstNodeValue($xpath, "atom:title/text()", $entry);
2450
2451                 $item["created"] = XML::getFirstNodeValue($xpath, "atom:published/text()", $entry);
2452
2453                 $item["body"] = XML::getFirstNodeValue($xpath, "dfrn:env/text()", $entry);
2454                 $item["body"] = str_replace([' ',"\t","\r","\n"], ['','','',''], $item["body"]);
2455                 // make sure nobody is trying to sneak some html tags by us
2456                 $item["body"] = notags(base64url_decode($item["body"]));
2457
2458                 $item["body"] = BBCode::limitBodySize($item["body"]);
2459
2460                 /// @todo Do we really need this check for HTML elements? (It was copied from the old function)
2461                 if ((strpos($item['body'], '<') !== false) && (strpos($item['body'], '>') !== false)) {
2462                         $base_url = get_app()->get_baseurl();
2463                         $item['body'] = reltoabs($item['body'], $base_url);
2464
2465                         $item['body'] = html2bb_video($item['body']);
2466
2467                         $item['body'] = OEmbed::HTML2BBCode($item['body']);
2468
2469                         $config = HTMLPurifier_Config::createDefault();
2470                         $config->set('Cache.DefinitionImpl', null);
2471
2472                         // we shouldn't need a whitelist, because the bbcode converter
2473                         // will strip out any unsupported tags.
2474
2475                         $purifier = new HTMLPurifier($config);
2476                         $item['body'] = $purifier->purify($item['body']);
2477
2478                         $item['body'] = @HTML::toBBCode($item['body']);
2479                 }
2480
2481                 /// @todo We should check for a repeated post and if we know the repeated author.
2482
2483                 // We don't need the content element since "dfrn:env" is always present
2484                 //$item["body"] = $xpath->query("atom:content/text()", $entry)->item(0)->nodeValue;
2485
2486                 $item["location"] = XML::getFirstNodeValue($xpath, "dfrn:location/text()", $entry);
2487
2488                 $item["coord"] = XML::getFirstNodeValue($xpath, "georss:point", $entry);
2489
2490                 $item["private"] = XML::getFirstNodeValue($xpath, "dfrn:private/text()", $entry);
2491
2492                 $item["extid"] = XML::getFirstNodeValue($xpath, "dfrn:extid/text()", $entry);
2493
2494                 if (XML::getFirstNodeValue($xpath, "dfrn:bookmark/text()", $entry) == "true") {
2495                         $item["post-type"] = Item::PT_PAGE;
2496                 }
2497
2498                 $notice_info = $xpath->query("statusnet:notice_info", $entry);
2499                 if ($notice_info && ($notice_info->length > 0)) {
2500                         foreach ($notice_info->item(0)->attributes as $attributes) {
2501                                 if ($attributes->name == "source") {
2502                                         $item["app"] = strip_tags($attributes->textContent);
2503                                 }
2504                         }
2505                 }
2506
2507                 $item["guid"] = XML::getFirstNodeValue($xpath, "dfrn:diaspora_guid/text()", $entry);
2508
2509                 // We store the data from "dfrn:diaspora_signature" in a different table, this is done in "Item::insert"
2510                 $dsprsig = unxmlify(XML::getFirstNodeValue($xpath, "dfrn:diaspora_signature/text()", $entry));
2511                 if ($dsprsig != "") {
2512                         $item["dsprsig"] = $dsprsig;
2513                 }
2514
2515                 $item["verb"] = XML::getFirstNodeValue($xpath, "activity:verb/text()", $entry);
2516
2517                 if (XML::getFirstNodeValue($xpath, "activity:object-type/text()", $entry) != "") {
2518                         $item["object-type"] = XML::getFirstNodeValue($xpath, "activity:object-type/text()", $entry);
2519                 }
2520
2521                 $object = $xpath->query("activity:object", $entry)->item(0);
2522                 $item["object"] = self::transformActivity($xpath, $object, "object");
2523
2524                 if (trim($item["object"]) != "") {
2525                         $r = XML::parseString($item["object"], false);
2526                         if (isset($r->type)) {
2527                                 $item["object-type"] = $r->type;
2528                         }
2529                 }
2530
2531                 $target = $xpath->query("activity:target", $entry)->item(0);
2532                 $item["target"] = self::transformActivity($xpath, $target, "target");
2533
2534                 $categories = $xpath->query("atom:category", $entry);
2535                 if ($categories) {
2536                         foreach ($categories as $category) {
2537                                 $term = "";
2538                                 $scheme = "";
2539                                 foreach ($category->attributes as $attributes) {
2540                                         if ($attributes->name == "term") {
2541                                                 $term = $attributes->textContent;
2542                                         }
2543
2544                                         if ($attributes->name == "scheme") {
2545                                                 $scheme = $attributes->textContent;
2546                                         }
2547                                 }
2548
2549                                 if (($term != "") && ($scheme != "")) {
2550                                         $parts = explode(":", $scheme);
2551                                         if ((count($parts) >= 4) && (array_shift($parts) == "X-DFRN")) {
2552                                                 $termhash = array_shift($parts);
2553                                                 $termurl = implode(":", $parts);
2554
2555                                                 if (!empty($item["tag"])) {
2556                                                         $item["tag"] .= ",";
2557                                                 } else {
2558                                                         $item["tag"] = "";
2559                                                 }
2560
2561                                                 $item["tag"] .= $termhash . "[url=" . $termurl . "]" . $term . "[/url]";
2562                                         }
2563                                 }
2564                         }
2565                 }
2566
2567                 $enclosure = "";
2568
2569                 $links = $xpath->query("atom:link", $entry);
2570                 if ($links) {
2571                         self::parseLinks($links, $item);
2572                 }
2573
2574                 $item['conversation-uri'] = XML::getFirstNodeValue($xpath, 'ostatus:conversation/text()', $entry);
2575
2576                 $conv = $xpath->query('ostatus:conversation', $entry);
2577                 if (is_object($conv->item(0))) {
2578                         foreach ($conv->item(0)->attributes as $attributes) {
2579                                 if ($attributes->name == "ref") {
2580                                         $item['conversation-uri'] = $attributes->textContent;
2581                                 }
2582                                 if ($attributes->name == "href") {
2583                                         $item['conversation-href'] = $attributes->textContent;
2584                                 }
2585                         }
2586                 }
2587
2588                 // Is it a reply or a top level posting?
2589                 $item["parent-uri"] = $item["uri"];
2590
2591                 $inreplyto = $xpath->query("thr:in-reply-to", $entry);
2592                 if (is_object($inreplyto->item(0))) {
2593                         foreach ($inreplyto->item(0)->attributes as $attributes) {
2594                                 if ($attributes->name == "ref") {
2595                                         $item["parent-uri"] = $attributes->textContent;
2596                                 }
2597                         }
2598                 }
2599
2600                 // Get the type of the item (Top level post, reply or remote reply)
2601                 $entrytype = self::getEntryType($importer, $item);
2602
2603                 // Now assign the rest of the values that depend on the type of the message
2604                 if (in_array($entrytype, [DFRN::REPLY, DFRN::REPLY_RC])) {
2605                         if (!isset($item["object-type"])) {
2606                                 $item["object-type"] = ACTIVITY_OBJ_COMMENT;
2607                         }
2608
2609                         if ($item["contact-id"] != $owner["contact-id"]) {
2610                                 $item["contact-id"] = $owner["contact-id"];
2611                         }
2612
2613                         if (($item["network"] != $owner["network"]) && ($owner["network"] != "")) {
2614                                 $item["network"] = $owner["network"];
2615                         }
2616
2617                         if ($item["contact-id"] != $author["contact-id"]) {
2618                                 $item["contact-id"] = $author["contact-id"];
2619                         }
2620
2621                         if (($item["network"] != $author["network"]) && ($author["network"] != "")) {
2622                                 $item["network"] = $author["network"];
2623                         }
2624                 }
2625
2626                 if ($entrytype == DFRN::REPLY_RC) {
2627                         $item["wall"] = 1;
2628                 } elseif ($entrytype == DFRN::TOP_LEVEL) {
2629                         if (!isset($item["object-type"])) {
2630                                 $item["object-type"] = ACTIVITY_OBJ_NOTE;
2631                         }
2632
2633                         // Is it an event?
2634                         if (($item["object-type"] == ACTIVITY_OBJ_EVENT) && !$owner_unknown) {
2635                                 logger("Item ".$item["uri"]." seems to contain an event.", LOGGER_DEBUG);
2636                                 $ev = Event::fromBBCode($item["body"]);
2637                                 if ((x($ev, "desc") || x($ev, "summary")) && x($ev, "start")) {
2638                                         logger("Event in item ".$item["uri"]." was found.", LOGGER_DEBUG);
2639                                         $ev["cid"]     = $importer["id"];
2640                                         $ev["uid"]     = $importer["importer_uid"];
2641                                         $ev["uri"]     = $item["uri"];
2642                                         $ev["edited"]  = $item["edited"];
2643                                         $ev["private"] = $item["private"];
2644                                         $ev["guid"]    = $item["guid"];
2645
2646                                         $r = q(
2647                                                 "SELECT `id` FROM `event` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2648                                                 DBA::escape($item["uri"]),
2649                                                 intval($importer["importer_uid"])
2650                                         );
2651                                         if (DBA::isResult($r)) {
2652                                                 $ev["id"] = $r[0]["id"];
2653                                         }
2654
2655                                         $event_id = Event::store($ev);
2656                                         logger("Event ".$event_id." was stored", LOGGER_DEBUG);
2657                                         return;
2658                                 }
2659                         }
2660                 }
2661
2662                 if (!self::processVerbs($entrytype, $importer, $item, $is_like)) {
2663                         logger("Exiting because 'processVerbs' told us so", LOGGER_DEBUG);
2664                         return;
2665                 }
2666
2667                 // This check is done here to be able to receive connection requests in "processVerbs"
2668                 if (($entrytype == DFRN::TOP_LEVEL) && $owner_unknown) {
2669                         logger("Item won't be stored because user " . $importer["importer_uid"] . " doesn't follow " . $item["owner-link"] . ".", LOGGER_DEBUG);
2670                         return;
2671                 }
2672
2673
2674                 // Update content if 'updated' changes
2675                 if (DBA::isResult($current)) {
2676                         if (self::updateContent($current, $item, $importer, $entrytype)) {
2677                                 logger("Item ".$item["uri"]." was updated.", LOGGER_DEBUG);
2678                         } else {
2679                                 logger("Item " . $item["uri"] . " already existed.", LOGGER_DEBUG);
2680                         }
2681                         return;
2682                 }
2683
2684                 if (in_array($entrytype, [DFRN::REPLY, DFRN::REPLY_RC])) {
2685                         $posted_id = Item::insert($item);
2686                         $parent = 0;
2687
2688                         if ($posted_id) {
2689                                 logger("Reply from contact ".$item["contact-id"]." was stored with id ".$posted_id, LOGGER_DEBUG);
2690
2691                                 if ($item['uid'] == 0) {
2692                                         Item::distribute($posted_id);
2693                                 }
2694
2695                                 return true;
2696                         }
2697                 } else { // $entrytype == DFRN::TOP_LEVEL
2698                         if (($importer["uid"] == 0) && ($importer["importer_uid"] != 0)) {
2699                                 logger("Contact ".$importer["id"]." isn't known to user ".$importer["importer_uid"].". The post will be ignored.", LOGGER_DEBUG);
2700                                 return;
2701                         }
2702                         if (!link_compare($item["owner-link"], $importer["url"])) {
2703                                 /*
2704                                  * The item owner info is not our contact. It's OK and is to be expected if this is a tgroup delivery,
2705                                  * but otherwise there's a possible data mixup on the sender's system.
2706                                  * the tgroup delivery code called from Item::insert will correct it if it's a forum,
2707                                  * but we're going to unconditionally correct it here so that the post will always be owned by our contact.
2708                                  */
2709                                 logger('Correcting item owner.', LOGGER_DEBUG);
2710                                 $item["owner-link"] = $importer["url"];
2711                                 $item["owner-id"] = Contact::getIdForURL($importer["url"], 0);
2712                         }
2713
2714                         if (($importer["rel"] == CONTACT_IS_FOLLOWER) && (!self::tgroupCheck($importer["importer_uid"], $item))) {
2715                                 logger("Contact ".$importer["id"]." is only follower and tgroup check was negative.", LOGGER_DEBUG);
2716                                 return;
2717                         }
2718
2719                         // This is my contact on another system, but it's really me.
2720                         // Turn this into a wall post.
2721                         $notify = Item::isRemoteSelf($importer, $item);
2722
2723                         $posted_id = Item::insert($item, false, $notify);
2724
2725                         if ($notify) {
2726                                 $posted_id = $notify;
2727                         }
2728
2729                         logger("Item was stored with id ".$posted_id, LOGGER_DEBUG);
2730
2731                         if ($item['uid'] == 0) {
2732                                 Item::distribute($posted_id);
2733                         }
2734
2735                         if (stristr($item["verb"], ACTIVITY_POKE)) {
2736                                 self::doPoke($item, $importer, $posted_id);
2737                         }
2738                 }
2739         }
2740
2741         /**
2742          * @brief Deletes items
2743          *
2744          * @param object $xpath    XPath object
2745          * @param object $deletion deletion elements
2746          * @param array  $importer Record of the importer user mixed with contact of the content
2747          * @return void
2748          * @todo set proper type-hints
2749          */
2750         private static function processDeletion($xpath, $deletion, $importer)
2751         {
2752                 logger("Processing deletions");
2753                 $uri = null;
2754
2755                 foreach ($deletion->attributes as $attributes) {
2756                         if ($attributes->name == "ref") {
2757                                 $uri = $attributes->textContent;
2758                         }
2759                 }
2760
2761                 if (!$uri || !$importer["id"]) {
2762                         return false;
2763                 }
2764
2765                 $condition = ['uri' => $uri, 'uid' => $importer["importer_uid"]];
2766                 $item = Item::selectFirst(['id', 'parent', 'contact-id', 'file', 'deleted'], $condition);
2767                 if (!DBA::isResult($item)) {
2768                         logger("Item with uri " . $uri . " for user " . $importer["importer_uid"] . " wasn't found.", LOGGER_DEBUG);
2769                         return;
2770                 }
2771
2772                 if (strstr($item['file'], '[')) {
2773                         logger("Item with uri " . $uri . " for user " . $importer["importer_uid"] . " is filed. So it won't be deleted.", LOGGER_DEBUG);
2774                         return;
2775                 }
2776
2777                 // When it is a starting post it has to belong to the person that wants to delete it
2778                 if (($item['id'] == $item['parent']) && ($item['contact-id'] != $importer["id"])) {
2779                         logger("Item with uri " . $uri . " don't belong to contact " . $importer["id"] . " - ignoring deletion.", LOGGER_DEBUG);
2780                         return;
2781                 }
2782
2783                 // Comments can be deleted by the thread owner or comment owner
2784                 if (($item['id'] != $item['parent']) && ($item['contact-id'] != $importer["id"])) {
2785                         $condition = ['id' => $item['parent'], 'contact-id' => $importer["id"]];
2786                         if (!Item::exists($condition)) {
2787                                 logger("Item with uri " . $uri . " wasn't found or mustn't be deleted by contact " . $importer["id"] . " - ignoring deletion.", LOGGER_DEBUG);
2788                                 return;
2789                         }
2790                 }
2791
2792                 if ($item["deleted"]) {
2793                         return;
2794                 }
2795
2796                 logger('deleting item '.$item['id'].' uri='.$uri, LOGGER_DEBUG);
2797
2798                 Item::delete(['id' => $item['id']]);
2799         }
2800
2801         /**
2802          * @brief Imports a DFRN message
2803          *
2804          * @param string $xml          The DFRN message
2805          * @param array  $importer     Record of the importer user mixed with contact of the content
2806          * @param bool   $sort_by_date Is used when feeds are polled
2807          * @return integer Import status
2808          * @todo set proper type-hints
2809          */
2810         public static function import($xml, $importer, $sort_by_date = false)
2811         {
2812                 if ($xml == "") {
2813                         return 400;
2814                 }
2815
2816                 $doc = new DOMDocument();
2817                 @$doc->loadXML($xml);
2818
2819                 $xpath = new DOMXPath($doc);
2820                 $xpath->registerNamespace("atom", NAMESPACE_ATOM1);
2821                 $xpath->registerNamespace("thr", NAMESPACE_THREAD);
2822                 $xpath->registerNamespace("at", NAMESPACE_TOMB);
2823                 $xpath->registerNamespace("media", NAMESPACE_MEDIA);
2824                 $xpath->registerNamespace("dfrn", NAMESPACE_DFRN);
2825                 $xpath->registerNamespace("activity", NAMESPACE_ACTIVITY);
2826                 $xpath->registerNamespace("georss", NAMESPACE_GEORSS);
2827                 $xpath->registerNamespace("poco", NAMESPACE_POCO);
2828                 $xpath->registerNamespace("ostatus", NAMESPACE_OSTATUS);
2829                 $xpath->registerNamespace("statusnet", NAMESPACE_STATUSNET);
2830
2831                 $header = [];
2832                 $header["uid"] = $importer["importer_uid"];
2833                 $header["network"] = NETWORK_DFRN;
2834                 $header["wall"] = 0;
2835                 $header["origin"] = 0;
2836                 $header["contact-id"] = $importer["id"];
2837
2838                 // Update the contact table if the data has changed
2839
2840                 // The "atom:author" is only present in feeds
2841                 if ($xpath->query("/atom:feed/atom:author")->length > 0) {
2842                         self::fetchauthor($xpath, $doc->firstChild, $importer, "atom:author", false, $xml);
2843                 }
2844
2845                 // Only the "dfrn:owner" in the head section contains all data
2846                 if ($xpath->query("/atom:feed/dfrn:owner")->length > 0) {
2847                         self::fetchauthor($xpath, $doc->firstChild, $importer, "dfrn:owner", false, $xml);
2848                 }
2849
2850                 logger("Import DFRN message for user " . $importer["importer_uid"] . " from contact " . $importer["id"], LOGGER_DEBUG);
2851
2852                 // is it a public forum? Private forums aren't exposed with this method
2853                 $forum = intval(XML::getFirstNodeValue($xpath, "/atom:feed/dfrn:community/text()"));
2854
2855                 // The account type is new since 3.5.1
2856                 if ($xpath->query("/atom:feed/dfrn:account_type")->length > 0) {
2857                         $accounttype = intval(XML::getFirstNodeValue($xpath, "/atom:feed/dfrn:account_type/text()"));
2858
2859                         if ($accounttype != $importer["contact-type"]) {
2860                                 DBA::update('contact', ['contact-type' => $accounttype], ['id' => $importer["id"]]);
2861                         }
2862                         // A forum contact can either have set "forum" or "prv" - but not both
2863                         if (($accounttype == ACCOUNT_TYPE_COMMUNITY) && (($forum != $importer["forum"]) || ($forum == $importer["prv"]))) {
2864                                 $condition = ['(`forum` != ? OR `prv` != ?) AND `id` = ?', $forum, !$forum, $importer["id"]];
2865                                 DBA::update('contact', ['forum' => $forum, 'prv' => !$forum], $condition);
2866                         }
2867                 } elseif ($forum != $importer["forum"]) { // Deprecated since 3.5.1
2868                         $condition = ['`forum` != ? AND `id` = ?', $forum, $importer["id"]];
2869                         DBA::update('contact', ['forum' => $forum], $condition);
2870                 }
2871
2872
2873                 // We are processing relocations even if we are ignoring a contact
2874                 $relocations = $xpath->query("/atom:feed/dfrn:relocate");
2875                 foreach ($relocations as $relocation) {
2876                         self::processRelocation($xpath, $relocation, $importer);
2877                 }
2878
2879                 if (($importer["uid"] != 0) && !$importer["readonly"]) {
2880                         $mails = $xpath->query("/atom:feed/dfrn:mail");
2881                         foreach ($mails as $mail) {
2882                                 self::processMail($xpath, $mail, $importer);
2883                         }
2884
2885                         $suggestions = $xpath->query("/atom:feed/dfrn:suggest");
2886                         foreach ($suggestions as $suggestion) {
2887                                 self::processSuggestion($xpath, $suggestion, $importer);
2888                         }
2889                 }
2890
2891                 $deletions = $xpath->query("/atom:feed/at:deleted-entry");
2892                 foreach ($deletions as $deletion) {
2893                         self::processDeletion($xpath, $deletion, $importer);
2894                 }
2895
2896                 if (!$sort_by_date) {
2897                         $entries = $xpath->query("/atom:feed/atom:entry");
2898                         foreach ($entries as $entry) {
2899                                 self::processEntry($header, $xpath, $entry, $importer, $xml);
2900                         }
2901                 } else {
2902                         $newentries = [];
2903                         $entries = $xpath->query("/atom:feed/atom:entry");
2904                         foreach ($entries as $entry) {
2905                                 $created = XML::getFirstNodeValue($xpath, "atom:published/text()", $entry);
2906                                 $newentries[strtotime($created)] = $entry;
2907                         }
2908
2909                         // Now sort after the publishing date
2910                         ksort($newentries);
2911
2912                         foreach ($newentries as $entry) {
2913                                 self::processEntry($header, $xpath, $entry, $importer, $xml);
2914                         }
2915                 }
2916                 logger("Import done for user " . $importer["importer_uid"] . " from contact " . $importer["id"], LOGGER_DEBUG);
2917                 return 200;
2918         }
2919
2920         /**
2921          * @param App    $a            App
2922          * @param string $contact_nick contact nickname
2923          */
2924         public static function autoRedir(App $a, $contact_nick)
2925         {
2926                 // prevent looping
2927                 if (x($_REQUEST, 'redir') && intval($_REQUEST['redir'])) {
2928                         return;
2929                 }
2930
2931                 if ((! $contact_nick) || ($contact_nick === $a->user['nickname'])) {
2932                         return;
2933                 }
2934
2935                 if (local_user()) {
2936                         // We need to find out if $contact_nick is a user on this hub, and if so, if I
2937                         // am a contact of that user. However, that user may have other contacts with the
2938                         // same nickname as me on other hubs or other networks. Exclude these by requiring
2939                         // that the contact have a local URL. I will be the only person with my nickname at
2940                         // this URL, so if a result is found, then I am a contact of the $contact_nick user.
2941                         //
2942                         // We also have to make sure that I'm a legitimate contact--I'm not blocked or pending.
2943
2944                         $baseurl = System::baseUrl();
2945                         $domain_st = strpos($baseurl, "://");
2946                         if ($domain_st === false) {
2947                                 return;
2948                         }
2949                         $baseurl = substr($baseurl, $domain_st + 3);
2950                         $nurl = normalise_link($baseurl);
2951
2952                         /// @todo Why is there a query for "url" *and* "nurl"? Especially this normalising is strange.
2953                         $r = q("SELECT `id` FROM `contact` WHERE `uid` = (SELECT `uid` FROM `user` WHERE `nickname` = '%s' LIMIT 1)
2954                                         AND `nick` = '%s' AND NOT `self` AND (`url` LIKE '%%%s%%' OR `nurl` LIKE '%%%s%%') AND NOT `blocked` AND NOT `pending` LIMIT 1",
2955                                 DBA::escape($contact_nick),
2956                                 DBA::escape($a->user['nickname']),
2957                                 DBA::escape($baseurl),
2958                                 DBA::escape($nurl)
2959                         );
2960                         if ((! DBA::isResult($r)) || $r[0]['id'] == remote_user()) {
2961                                 return;
2962                         }
2963
2964                         $r = q("SELECT * FROM contact WHERE nick = '%s'
2965                                         AND network = '%s' AND uid = %d  AND url LIKE '%%%s%%' LIMIT 1",
2966                                 DBA::escape($contact_nick),
2967                                 DBA::escape(NETWORK_DFRN),
2968                                 intval(local_user()),
2969                                 DBA::escape($baseurl)
2970                         );
2971                         if (! DBA::isResult($r)) {
2972                                 return;
2973                         }
2974
2975                         $cid = $r[0]['id'];
2976
2977                         $dfrn_id = (($r[0]['issued-id']) ? $r[0]['issued-id'] : $r[0]['dfrn-id']);
2978
2979                         if ($r[0]['duplex'] && $r[0]['issued-id']) {
2980                                 $orig_id = $r[0]['issued-id'];
2981                                 $dfrn_id = '1:' . $orig_id;
2982                         }
2983                         if ($r[0]['duplex'] && $r[0]['dfrn-id']) {
2984                                 $orig_id = $r[0]['dfrn-id'];
2985                                 $dfrn_id = '0:' . $orig_id;
2986                         }
2987
2988                         // ensure that we've got a valid ID. There may be some edge cases with forums and non-duplex mode
2989                         // that may have triggered some of the "went to {profile/intro} and got an RSS feed" issues
2990
2991                         if (strlen($dfrn_id) < 3) {
2992                                 return;
2993                         }
2994
2995                         $sec = random_string();
2996
2997                         DBA::insert('profile_check', ['uid' => local_user(), 'cid' => $cid, 'dfrn_id' => $dfrn_id, 'sec' => $sec, 'expire' => time() + 45]);
2998
2999                         $url = curPageURL();
3000
3001                         logger('auto_redir: ' . $r[0]['name'] . ' ' . $sec, LOGGER_DEBUG);
3002                         $dest = (($url) ? '&destination_url=' . $url : '');
3003                         goaway($r[0]['poll'] . '?dfrn_id=' . $dfrn_id
3004                                 . '&dfrn_version=' . DFRN_PROTOCOL_VERSION . '&type=profile&sec=' . $sec . $dest);
3005                 }
3006
3007                 return;
3008         }
3009
3010         /**
3011          * @brief Returns the activity verb
3012          *
3013          * @param array $item Item array
3014          *
3015          * @return string activity verb
3016          */
3017         private static function constructVerb(array $item)
3018         {
3019                 if ($item['verb']) {
3020                         return $item['verb'];
3021                 }
3022                 return ACTIVITY_POST;
3023         }
3024
3025         private static function tgroupCheck($uid, $item)
3026         {
3027                 $mention = false;
3028
3029                 // check that the message originated elsewhere and is a top-level post
3030
3031                 if ($item['wall'] || $item['origin'] || ($item['uri'] != $item['parent-uri'])) {
3032                         return false;
3033                 }
3034
3035                 $u = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1",
3036                         intval($uid)
3037                 );
3038                 if (!DBA::isResult($u)) {
3039                         return false;
3040                 }
3041
3042                 $community_page = ($u[0]['page-flags'] == PAGE_COMMUNITY);
3043                 $prvgroup = ($u[0]['page-flags'] == PAGE_PRVGROUP);
3044
3045                 $link = normalise_link(System::baseUrl() . '/profile/' . $u[0]['nickname']);
3046
3047                 /*
3048                  * Diaspora uses their own hardwired link URL in @-tags
3049                  * instead of the one we supply with webfinger
3050                  */
3051                 $dlink = normalise_link(System::baseUrl() . '/u/' . $u[0]['nickname']);
3052
3053                 $cnt = preg_match_all('/[\@\!]\[url\=(.*?)\](.*?)\[\/url\]/ism', $item['body'], $matches, PREG_SET_ORDER);
3054                 if ($cnt) {
3055                         foreach ($matches as $mtch) {
3056                                 if (link_compare($link, $mtch[1]) || link_compare($dlink, $mtch[1])) {
3057                                         $mention = true;
3058                                         logger('mention found: ' . $mtch[2]);
3059                                 }
3060                         }
3061                 }
3062
3063                 if (!$mention) {
3064                         return false;
3065                 }
3066
3067                 return $community_page || $prvgroup;
3068         }
3069
3070         /**
3071          * This function returns true if $update has an edited timestamp newer
3072          * than $existing, i.e. $update contains new data which should override
3073          * what's already there.  If there is no timestamp yet, the update is
3074          * assumed to be newer.  If the update has no timestamp, the existing
3075          * item is assumed to be up-to-date.  If the timestamps are equal it
3076          * assumes the update has been seen before and should be ignored.
3077          *
3078          */
3079         private static function isEditedTimestampNewer($existing, $update)
3080         {
3081                 if (!x($existing, 'edited') || !$existing['edited']) {
3082                         return true;
3083                 }
3084                 if (!x($update, 'edited') || !$update['edited']) {
3085                         return false;
3086                 }
3087
3088                 $existing_edited = DateTimeFormat::utc($existing['edited']);
3089                 $update_edited = DateTimeFormat::utc($update['edited']);
3090
3091                 return (strcmp($existing_edited, $update_edited) < 0);
3092         }
3093 }