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