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