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