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