]> git.mxchange.org Git - friendica.git/blob - include/dfrn.php
Forum posts with "!" are now created directly as forum post
[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 Updates an item
1992          *
1993          * @param array $current the current item record
1994          * @param array $item the new item record
1995          * @param array $importer Record of the importer user mixed with contact of the content
1996          * @param int $entrytype Is it a toplevel entry, a comment or a relayed comment?
1997          * @todo set proper type-hints (array?)
1998          */
1999         private static function update_content($current, $item, $importer, $entrytype) {
2000                 $changed = false;
2001
2002                 if (edited_timestamp_is_newer($current, $item)) {
2003
2004                         // do not accept (ignore) an earlier edit than one we currently have.
2005                         if (datetime_convert("UTC","UTC",$item["edited"]) < $current["edited"]) {
2006                                 return false;
2007                         }
2008
2009                         $fields = array('title' => $item["title"], 'body' => $item["body"],
2010                                         'tag' => $item["tag"], 'changed' => datetime_convert(),
2011                                         'edited' => datetime_convert("UTC", "UTC", $item["edited"]));
2012
2013                         $condition = array("`uri` = ? AND `uid` IN (0, ?)", $item["uri"], $importer["importer_uid"]);
2014                         dba::update('item', $fields, $condition);
2015
2016                         create_tags_from_itemuri($item["uri"], $importer["importer_uid"]);
2017                         update_thread_uri($item["uri"], $importer["importer_uid"]);
2018
2019                         $changed = true;
2020
2021                         if ($entrytype == DFRN_REPLY_RC) {
2022                                 proc_run(PRIORITY_HIGH, "include/notifier.php","comment-import", $current["id"]);
2023                         }
2024                 }
2025
2026                 // update last-child if it changes
2027                 if ($item["last-child"] && ($item["last-child"] != $current["last-child"])) {
2028                         $r = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` IN (0, %d)",
2029                                 dbesc(datetime_convert()),
2030                                 dbesc($item["parent-uri"]),
2031                                 intval($importer["importer_uid"])
2032                         );
2033                         $r = q("UPDATE `item` SET `last-child` = %d , `changed` = '%s' WHERE `uri` = '%s' AND `uid` IN (0, %d)",
2034                                 intval($item["last-child"]),
2035                                 dbesc(datetime_convert()),
2036                                 dbesc($item["uri"]),
2037                                 intval($importer["importer_uid"])
2038                         );
2039                 }
2040                 return $changed;
2041         }
2042
2043         /**
2044          * @brief Detects the entry type of the item
2045          *
2046          * @param array $importer Record of the importer user mixed with contact of the content
2047          * @param array $item the new item record
2048          *
2049          * @return int Is it a toplevel entry, a comment or a relayed comment?
2050          * @todo set proper type-hints (array?)
2051          */
2052         private static function get_entry_type($importer, $item) {
2053                 if ($item["parent-uri"] != $item["uri"]) {
2054                         $community = false;
2055
2056                         if ($importer["page-flags"] == PAGE_COMMUNITY || $importer["page-flags"] == PAGE_PRVGROUP) {
2057                                 $sql_extra = "";
2058                                 $community = true;
2059                                 logger("possible community action");
2060                         } else {
2061                                 $sql_extra = " AND `contact`.`self` AND `item`.`wall` ";
2062                         }
2063
2064                         // was the top-level post for this action written by somebody on this site?
2065                         // Specifically, the recipient?
2066
2067                         $is_a_remote_action = false;
2068
2069                         $r = q("SELECT `item`.`parent-uri` FROM `item`
2070                                 WHERE `item`.`uri` = '%s'
2071                                 LIMIT 1",
2072                                 dbesc($item["parent-uri"])
2073                         );
2074                         if (dbm::is_result($r)) {
2075                                 $r = q("SELECT `item`.`forum_mode`, `item`.`wall` FROM `item`
2076                                         INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
2077                                         WHERE `item`.`uri` = '%s' AND (`item`.`parent-uri` = '%s' OR `item`.`thr-parent` = '%s')
2078                                         AND `item`.`uid` = %d
2079                                         $sql_extra
2080                                         LIMIT 1",
2081                                         dbesc($r[0]["parent-uri"]),
2082                                         dbesc($r[0]["parent-uri"]),
2083                                         dbesc($r[0]["parent-uri"]),
2084                                         intval($importer["importer_uid"])
2085                                 );
2086                                 if (dbm::is_result($r)) {
2087                                         $is_a_remote_action = true;
2088                                 }
2089                         }
2090
2091                         /*
2092                          * Does this have the characteristics of a community or private group action?
2093                          * If it's an action to a wall post on a community/prvgroup page it's a
2094                          * valid community action. Also forum_mode makes it valid for sure.
2095                          * If neither, it's not.
2096                          */
2097
2098                         /// @TODO Maybe merge these if() blocks into one?
2099                         if ($is_a_remote_action && $community && (!$r[0]["forum_mode"]) && (!$r[0]["wall"])) {
2100                                 $is_a_remote_action = false;
2101                                 logger("not a community action");
2102                         }
2103
2104                         if ($is_a_remote_action) {
2105                                 return DFRN_REPLY_RC;
2106                         } else {
2107                                 return DFRN_REPLY;
2108                         }
2109                 } else {
2110                         return DFRN_TOP_LEVEL;
2111                 }
2112
2113         }
2114
2115         /**
2116          * @brief Send a "poke"
2117          *
2118          * @param array $item the new item record
2119          * @param array $importer Record of the importer user mixed with contact of the content
2120          * @param int $posted_id The record number of item record that was just posted
2121          * @todo set proper type-hints (array?)
2122          */
2123         private static function do_poke($item, $importer, $posted_id) {
2124                 $verb = urldecode(substr($item["verb"],strpos($item["verb"], "#")+1));
2125                 if (!$verb) {
2126                         return;
2127                 }
2128                 $xo = parse_xml_string($item["object"],false);
2129
2130                 if (($xo->type == ACTIVITY_OBJ_PERSON) && ($xo->id)) {
2131
2132                         // somebody was poked/prodded. Was it me?
2133                         foreach ($xo->link as $l) {
2134                                 $atts = $l->attributes();
2135                                 switch ($atts["rel"]) {
2136                                         case "alternate":
2137                                                 $Blink = $atts["href"];
2138                                                 break;
2139                                         default:
2140                                                 break;
2141                                 }
2142                         }
2143
2144                         if ($Blink && link_compare($Blink, System::baseUrl() . "/profile/" . $importer["nickname"])) {
2145
2146                                 // send a notification
2147                                 notification(array(
2148                                         "type"         => NOTIFY_POKE,
2149                                         "notify_flags" => $importer["notify-flags"],
2150                                         "language"     => $importer["language"],
2151                                         "to_name"      => $importer["username"],
2152                                         "to_email"     => $importer["email"],
2153                                         "uid"          => $importer["importer_uid"],
2154                                         "item"         => $item,
2155                                         "link"         => System::baseUrl()."/display/".urlencode(get_item_guid($posted_id)),
2156                                         "source_name"  => stripslashes($item["author-name"]),
2157                                         "source_link"  => $item["author-link"],
2158                                         "source_photo" => ((link_compare($item["author-link"],$importer["url"]))
2159                                                 ? $importer["thumb"] : $item["author-avatar"]),
2160                                         "verb"         => $item["verb"],
2161                                         "otype"        => "person",
2162                                         "activity"     => $verb,
2163                                         "parent"       => $item["parent"]
2164                                 ));
2165                         }
2166                 }
2167         }
2168
2169         /**
2170          * @brief Processes several actions, depending on the verb
2171          *
2172          * @param int $entrytype Is it a toplevel entry, a comment or a relayed comment?
2173          * @param array $importer Record of the importer user mixed with contact of the content
2174          * @param array $item the new item record
2175          * @param bool $is_like Is the verb a "like"?
2176          *
2177          * @return bool Should the processing of the entries be continued?
2178          * @todo set proper type-hints (array?)
2179          */
2180         private static function process_verbs($entrytype, $importer, &$item, &$is_like) {
2181
2182                 logger("Process verb ".$item["verb"]." and object-type ".$item["object-type"]." for entrytype ".$entrytype, LOGGER_DEBUG);
2183
2184                 if (($entrytype == DFRN_TOP_LEVEL)) {
2185                         // The filling of the the "contact" variable is done for legcy reasons
2186                         // The functions below are partly used by ostatus.php as well - where we have this variable
2187                         $r = q("SELECT * FROM `contact` WHERE `id` = %d", intval($importer["id"]));
2188                         $contact = $r[0];
2189                         $nickname = $contact["nick"];
2190
2191                         // Big question: Do we need these functions? They were part of the "consume_feed" function.
2192                         // This function once was responsible for DFRN and OStatus.
2193                         if (activity_match($item["verb"], ACTIVITY_FOLLOW)) {
2194                                 logger("New follower");
2195                                 new_follower($importer, $contact, $item, $nickname);
2196                                 return false;
2197                         }
2198                         if (activity_match($item["verb"], ACTIVITY_UNFOLLOW))  {
2199                                 logger("Lost follower");
2200                                 lose_follower($importer, $contact, $item);
2201                                 return false;
2202                         }
2203                         if (activity_match($item["verb"], ACTIVITY_REQ_FRIEND)) {
2204                                 logger("New friend request");
2205                                 new_follower($importer, $contact, $item, $nickname, true);
2206                                 return false;
2207                         }
2208                         if (activity_match($item["verb"], ACTIVITY_UNFRIEND))  {
2209                                 logger("Lost sharer");
2210                                 lose_sharer($importer, $contact, $item);
2211                                 return false;
2212                         }
2213                 } else {
2214                         if (($item["verb"] == ACTIVITY_LIKE)
2215                                 || ($item["verb"] == ACTIVITY_DISLIKE)
2216                                 || ($item["verb"] == ACTIVITY_ATTEND)
2217                                 || ($item["verb"] == ACTIVITY_ATTENDNO)
2218                                 || ($item["verb"] == ACTIVITY_ATTENDMAYBE)) {
2219                                 $is_like = true;
2220                                 $item["type"] = "activity";
2221                                 $item["gravity"] = GRAVITY_LIKE;
2222                                 // only one like or dislike per person
2223                                 // splitted into two queries for performance issues
2224                                 $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",
2225                                         intval($item["uid"]),
2226                                         dbesc($item["author-link"]),
2227                                         dbesc($item["verb"]),
2228                                         dbesc($item["parent-uri"])
2229                                 );
2230                                 if (dbm::is_result($r)) {
2231                                         return false;
2232                                 }
2233
2234                                 $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",
2235                                         intval($item["uid"]),
2236                                         dbesc($item["author-link"]),
2237                                         dbesc($item["verb"]),
2238                                         dbesc($item["parent-uri"])
2239                                 );
2240                                 if (dbm::is_result($r)) {
2241                                         return false;
2242                                 }
2243                         } else {
2244                                 $is_like = false;
2245                         }
2246
2247                         if (($item["verb"] == ACTIVITY_TAG) && ($item["object-type"] == ACTIVITY_OBJ_TAGTERM)) {
2248
2249                                 $xo = parse_xml_string($item["object"],false);
2250                                 $xt = parse_xml_string($item["target"],false);
2251
2252                                 if ($xt->type == ACTIVITY_OBJ_NOTE) {
2253                                         $r = q("SELECT `id`, `tag` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2254                                                 dbesc($xt->id),
2255                                                 intval($importer["importer_uid"])
2256                                         );
2257
2258                                         if (!dbm::is_result($r)) {
2259                                                 logger("Query failed to execute, no result returned in " . __FUNCTION__);
2260                                                 return false;
2261                                         }
2262
2263                                         // extract tag, if not duplicate, add to parent item
2264                                         if ($xo->content) {
2265                                                 if (!(stristr($r[0]["tag"],trim($xo->content)))) {
2266                                                         q("UPDATE `item` SET `tag` = '%s' WHERE `id` = %d",
2267                                                                 dbesc($r[0]["tag"] . (strlen($r[0]["tag"]) ? ',' : '') . '#[url=' . $xo->id . ']'. $xo->content . '[/url]'),
2268                                                                 intval($r[0]["id"])
2269                                                         );
2270                                                         create_tags_from_item($r[0]["id"]);
2271                                                 }
2272                                         }
2273                                 }
2274                         }
2275                 }
2276                 return true;
2277         }
2278
2279         /**
2280          * @brief Processes the link elements
2281          *
2282          * @param object $links link elements
2283          * @param array $item the item record
2284          * @todo set proper type-hints
2285          */
2286         private static function parse_links($links, &$item) {
2287                 $rel = "";
2288                 $href = "";
2289                 $type = "";
2290                 $length = "0";
2291                 $title = "";
2292                 foreach ($links AS $link) {
2293                         foreach ($link->attributes AS $attributes) {
2294                                 /// @TODO Rewrite these repeated (same) if () statements to a switch()
2295                                 if ($attributes->name == "href") {
2296                                         $href = $attributes->textContent;
2297                                 }
2298                                 if ($attributes->name == "rel") {
2299                                         $rel = $attributes->textContent;
2300                                 }
2301                                 if ($attributes->name == "type") {
2302                                         $type = $attributes->textContent;
2303                                 }
2304                                 if ($attributes->name == "length") {
2305                                         $length = $attributes->textContent;
2306                                 }
2307                                 if ($attributes->name == "title") {
2308                                         $title = $attributes->textContent;
2309                                 }
2310                         }
2311                         if (($rel != "") && ($href != "")) {
2312                                 switch ($rel) {
2313                                         case "alternate":
2314                                                 $item["plink"] = $href;
2315                                                 break;
2316                                         case "enclosure":
2317                                                 $enclosure = $href;
2318                                                 if (strlen($item["attach"])) {
2319                                                         $item["attach"] .= ",";
2320                                                 }
2321
2322                                                 $item["attach"] .= '[attach]href="' . $href . '" length="' . $length . '" type="' . $type . '" title="' . $title . '"[/attach]';
2323                                                 break;
2324                                 }
2325                         }
2326                 }
2327         }
2328
2329         /**
2330          * @brief Processes the entry elements which contain the items and comments
2331          *
2332          * @param array $header Array of the header elements that always stay the same
2333          * @param object $xpath XPath object
2334          * @param object $entry entry elements
2335          * @param array $importer Record of the importer user mixed with contact of the content
2336          * @todo Add type-hints
2337          */
2338         private static function process_entry($header, $xpath, $entry, $importer, $xml) {
2339
2340                 logger("Processing entries");
2341
2342                 $item = $header;
2343
2344                 $item["protocol"] = PROTOCOL_DFRN;
2345
2346                 $item["source"] = $xml;
2347
2348                 // Get the uri
2349                 $item["uri"] = $xpath->query("atom:id/text()", $entry)->item(0)->nodeValue;
2350
2351                 $item["edited"] = $xpath->query("atom:updated/text()", $entry)->item(0)->nodeValue;
2352
2353                 $current = q("SELECT `id`, `uid`, `last-child`, `edited`, `body` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2354                         dbesc($item["uri"]),
2355                         intval($importer["importer_uid"])
2356                 );
2357
2358                 // Is there an existing item?
2359                 if (dbm::is_result($current) && edited_timestamp_is_newer($current[0], $item) &&
2360                         (datetime_convert("UTC","UTC",$item["edited"]) < $current[0]["edited"])) {
2361                         logger("Item ".$item["uri"]." already existed.", LOGGER_DEBUG);
2362                         return;
2363                 }
2364
2365                 // Fetch the owner
2366                 $owner = self::fetchauthor($xpath, $entry, $importer, "dfrn:owner", true);
2367
2368                 $item["owner-name"] = $owner["name"];
2369                 $item["owner-link"] = $owner["link"];
2370                 $item["owner-avatar"] = $owner["avatar"];
2371
2372                 // fetch the author
2373                 $author = self::fetchauthor($xpath, $entry, $importer, "atom:author", true);
2374
2375                 $item["author-name"] = $author["name"];
2376                 $item["author-link"] = $author["link"];
2377                 $item["author-avatar"] = $author["avatar"];
2378
2379                 $item["title"] = $xpath->query("atom:title/text()", $entry)->item(0)->nodeValue;
2380
2381                 $item["created"] = $xpath->query("atom:published/text()", $entry)->item(0)->nodeValue;
2382
2383                 $item["body"] = $xpath->query("dfrn:env/text()", $entry)->item(0)->nodeValue;
2384                 $item["body"] = str_replace(array(' ',"\t","\r","\n"), array('','','',''),$item["body"]);
2385                 // make sure nobody is trying to sneak some html tags by us
2386                 $item["body"] = notags(base64url_decode($item["body"]));
2387
2388                 $item["body"] = limit_body_size($item["body"]);
2389
2390                 /// @todo Do we really need this check for HTML elements? (It was copied from the old function)
2391                 if ((strpos($item['body'],'<') !== false) && (strpos($item['body'],'>') !== false)) {
2392
2393                         $item['body'] = reltoabs($item['body'],$base_url);
2394
2395                         $item['body'] = html2bb_video($item['body']);
2396
2397                         $item['body'] = oembed_html2bbcode($item['body']);
2398
2399                         $config = HTMLPurifier_Config::createDefault();
2400                         $config->set('Cache.DefinitionImpl', null);
2401
2402                         // we shouldn't need a whitelist, because the bbcode converter
2403                         // will strip out any unsupported tags.
2404
2405                         $purifier = new HTMLPurifier($config);
2406                         $item['body'] = $purifier->purify($item['body']);
2407
2408                         $item['body'] = @html2bbcode($item['body']);
2409                 }
2410
2411                 /// @todo We should check for a repeated post and if we know the repeated author.
2412
2413                 // We don't need the content element since "dfrn:env" is always present
2414                 //$item["body"] = $xpath->query("atom:content/text()", $entry)->item(0)->nodeValue;
2415
2416                 $item["last-child"] = $xpath->query("dfrn:comment-allow/text()", $entry)->item(0)->nodeValue;
2417                 $item["location"] = $xpath->query("dfrn:location/text()", $entry)->item(0)->nodeValue;
2418
2419                 $georsspoint = $xpath->query("georss:point", $entry);
2420                 if ($georsspoint) {
2421                         $item["coord"] = $georsspoint->item(0)->nodeValue;
2422                 }
2423
2424                 $item["private"] = $xpath->query("dfrn:private/text()", $entry)->item(0)->nodeValue;
2425
2426                 $item["extid"] = $xpath->query("dfrn:extid/text()", $entry)->item(0)->nodeValue;
2427
2428                 if ($xpath->query("dfrn:bookmark/text()", $entry)->item(0)->nodeValue == "true") {
2429                         $item["bookmark"] = true;
2430                 }
2431
2432                 $notice_info = $xpath->query("statusnet:notice_info", $entry);
2433                 if ($notice_info && ($notice_info->length > 0)) {
2434                         foreach ($notice_info->item(0)->attributes AS $attributes) {
2435                                 if ($attributes->name == "source") {
2436                                         $item["app"] = strip_tags($attributes->textContent);
2437                                 }
2438                         }
2439                 }
2440
2441                 $item["guid"] = $xpath->query("dfrn:diaspora_guid/text()", $entry)->item(0)->nodeValue;
2442
2443                 // We store the data from "dfrn:diaspora_signature" in a different table, this is done in "item_store"
2444                 $dsprsig = unxmlify($xpath->query("dfrn:diaspora_signature/text()", $entry)->item(0)->nodeValue);
2445                 if ($dsprsig != "") {
2446                         $item["dsprsig"] = $dsprsig;
2447                 }
2448
2449                 $item["verb"] = $xpath->query("activity:verb/text()", $entry)->item(0)->nodeValue;
2450
2451                 if ($xpath->query("activity:object-type/text()", $entry)->item(0)->nodeValue != "") {
2452                         $item["object-type"] = $xpath->query("activity:object-type/text()", $entry)->item(0)->nodeValue;
2453                 }
2454
2455                 $object = $xpath->query("activity:object", $entry)->item(0);
2456                 $item["object"] = self::transform_activity($xpath, $object, "object");
2457
2458                 if (trim($item["object"]) != "") {
2459                         $r = parse_xml_string($item["object"], false);
2460                         if (isset($r->type)) {
2461                                 $item["object-type"] = $r->type;
2462                         }
2463                 }
2464
2465                 $target = $xpath->query("activity:target", $entry)->item(0);
2466                 $item["target"] = self::transform_activity($xpath, $target, "target");
2467
2468                 $categories = $xpath->query("atom:category", $entry);
2469                 if ($categories) {
2470                         foreach ($categories AS $category) {
2471                                 $term = "";
2472                                 $scheme = "";
2473                                 foreach ($category->attributes AS $attributes) {
2474                                         if ($attributes->name == "term") {
2475                                                 $term = $attributes->textContent;
2476                                         }
2477
2478                                         if ($attributes->name == "scheme") {
2479                                                 $scheme = $attributes->textContent;
2480                                         }
2481                                 }
2482
2483                                 if (($term != "") && ($scheme != "")) {
2484                                         $parts = explode(":", $scheme);
2485                                         if ((count($parts) >= 4) && (array_shift($parts) == "X-DFRN")) {
2486                                                 $termhash = array_shift($parts);
2487                                                 $termurl = implode(":", $parts);
2488
2489                                                 if (strlen($item["tag"])) {
2490                                                         $item["tag"] .= ",";
2491                                                 }
2492
2493                                                 $item["tag"] .= $termhash . "[url=" . $termurl . "]" . $term . "[/url]";
2494                                         }
2495                                 }
2496                         }
2497                 }
2498
2499                 $enclosure = "";
2500
2501                 $links = $xpath->query("atom:link", $entry);
2502                 if ($links) {
2503                         self::parse_links($links, $item);
2504                 }
2505
2506                 $item['conversation-uri'] = $xpath->query('ostatus:conversation/text()', $entry)->item(0)->nodeValue;
2507
2508                 $conv = $xpath->query('ostatus:conversation', $entry);
2509                 if (is_object($conv->item(0))) {
2510                         foreach ($conv->item(0)->attributes AS $attributes) {
2511                                 if ($attributes->name == "ref") {
2512                                         $item['conversation-uri'] = $attributes->textContent;
2513                                 }
2514                                 if ($attributes->name == "href") {
2515                                         $item['conversation-href'] = $attributes->textContent;
2516                                 }
2517                         }
2518                 }
2519
2520                 // Is it a reply or a top level posting?
2521                 $item["parent-uri"] = $item["uri"];
2522
2523                 $inreplyto = $xpath->query("thr:in-reply-to", $entry);
2524                 if (is_object($inreplyto->item(0))) {
2525                         foreach ($inreplyto->item(0)->attributes AS $attributes) {
2526                                 if ($attributes->name == "ref") {
2527                                         $item["parent-uri"] = $attributes->textContent;
2528                                 }
2529                         }
2530                 }
2531
2532                 // Get the type of the item (Top level post, reply or remote reply)
2533                 $entrytype = self::get_entry_type($importer, $item);
2534
2535                 // Now assign the rest of the values that depend on the type of the message
2536                 if (in_array($entrytype, array(DFRN_REPLY, DFRN_REPLY_RC))) {
2537                         if (!isset($item["object-type"])) {
2538                                 $item["object-type"] = ACTIVITY_OBJ_COMMENT;
2539                         }
2540
2541                         if ($item["contact-id"] != $owner["contact-id"]) {
2542                                 $item["contact-id"] = $owner["contact-id"];
2543                         }
2544
2545                         if (($item["network"] != $owner["network"]) && ($owner["network"] != "")) {
2546                                 $item["network"] = $owner["network"];
2547                         }
2548
2549                         if ($item["contact-id"] != $author["contact-id"]) {
2550                                 $item["contact-id"] = $author["contact-id"];
2551                         }
2552
2553                         if (($item["network"] != $author["network"]) && ($author["network"] != "")) {
2554                                 $item["network"] = $author["network"];
2555                         }
2556
2557                         /// @TODO maybe remove this old-lost code then?
2558                         // This code was taken from the old DFRN code
2559                         // When activated, forums don't work.
2560                         // And: Why should we disallow commenting by followers?
2561                         // the behaviour is now similar to the Diaspora part.
2562                         //if ($importer["rel"] == CONTACT_IS_FOLLOWER) {
2563                         //      logger("Contact ".$importer["id"]." is only follower. Quitting", LOGGER_DEBUG);
2564                         //      return;
2565                         //}
2566                 }
2567
2568                 if ($entrytype == DFRN_REPLY_RC) {
2569                         $item["type"] = "remote-comment";
2570                         $item["wall"] = 1;
2571                 } elseif ($entrytype == DFRN_TOP_LEVEL) {
2572                         if (!isset($item["object-type"])) {
2573                                 $item["object-type"] = ACTIVITY_OBJ_NOTE;
2574                         }
2575
2576                         // Is it an event?
2577                         if ($item["object-type"] == ACTIVITY_OBJ_EVENT) {
2578                                 logger("Item ".$item["uri"]." seems to contain an event.", LOGGER_DEBUG);
2579                                 $ev = bbtoevent($item["body"]);
2580                                 if ((x($ev, "desc") || x($ev, "summary")) && x($ev, "start")) {
2581                                         logger("Event in item ".$item["uri"]." was found.", LOGGER_DEBUG);
2582                                         /// @TODO Mixure of "/' ahead ...
2583                                         $ev["cid"] = $importer["id"];
2584                                         $ev["uid"] = $importer["uid"];
2585                                         $ev["uri"] = $item["uri"];
2586                                         $ev["edited"] = $item["edited"];
2587                                         $ev['private'] = $item['private'];
2588                                         $ev["guid"] = $item["guid"];
2589
2590                                         $r = q("SELECT `id` FROM `event` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2591                                                 dbesc($item["uri"]),
2592                                                 intval($importer["uid"])
2593                                         );
2594                                         if (dbm::is_result($r)) {
2595                                                 $ev["id"] = $r[0]["id"];
2596                                         }
2597
2598                                         $event_id = event_store($ev);
2599                                         logger("Event ".$event_id." was stored", LOGGER_DEBUG);
2600                                         return;
2601                                 }
2602                         }
2603                 }
2604
2605                 if (!self::process_verbs($entrytype, $importer, $item, $is_like)) {
2606                         logger("Exiting because 'process_verbs' told us so", LOGGER_DEBUG);
2607                         return;
2608                 }
2609
2610                 // Update content if 'updated' changes
2611                 if (dbm::is_result($current)) {
2612                         if (self::update_content($r[0], $item, $importer, $entrytype)) {
2613                                 logger("Item ".$item["uri"]." was updated.", LOGGER_DEBUG);
2614                         } else {
2615                                 logger("Item ".$item["uri"]." already existed.", LOGGER_DEBUG);
2616                         }
2617                         return;
2618                 }
2619
2620                 if (in_array($entrytype, array(DFRN_REPLY, DFRN_REPLY_RC))) {
2621                         $posted_id = item_store($item);
2622                         $parent = 0;
2623
2624                         if ($posted_id) {
2625
2626                                 logger("Reply from contact ".$item["contact-id"]." was stored with id ".$posted_id, LOGGER_DEBUG);
2627
2628                                 $item["id"] = $posted_id;
2629
2630                                 $r = q("SELECT `parent`, `parent-uri` FROM `item` WHERE `id` = %d AND `uid` = %d LIMIT 1",
2631                                         intval($posted_id),
2632                                         intval($importer["importer_uid"])
2633                                 );
2634                                 if (dbm::is_result($r)) {
2635                                         $parent = $r[0]["parent"];
2636                                         $parent_uri = $r[0]["parent-uri"];
2637                                 }
2638
2639                                 if (!$is_like) {
2640                                         $r1 = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `uid` = %d AND `parent` = %d",
2641                                                 dbesc(datetime_convert()),
2642                                                 intval($importer["importer_uid"]),
2643                                                 intval($r[0]["parent"])
2644                                         );
2645
2646                                         $r2 = q("UPDATE `item` SET `last-child` = 1, `changed` = '%s' WHERE `uid` = %d AND `id` = %d",
2647                                                 dbesc(datetime_convert()),
2648                                                 intval($importer["importer_uid"]),
2649                                                 intval($posted_id)
2650                                         );
2651                                 }
2652
2653                                 if ($posted_id && $parent && ($entrytype == DFRN_REPLY_RC)) {
2654                                         logger("Notifying followers about comment ".$posted_id, LOGGER_DEBUG);
2655                                         proc_run(PRIORITY_HIGH, "include/notifier.php", "comment-import", $posted_id);
2656                                 }
2657
2658                                 return true;
2659                         }
2660                 } else { // $entrytype == DFRN_TOP_LEVEL
2661                         if (!link_compare($item["owner-link"],$importer["url"])) {
2662                                 /*
2663                                  * The item owner info is not our contact. It's OK and is to be expected if this is a tgroup delivery,
2664                                  * but otherwise there's a possible data mixup on the sender's system.
2665                                  * the tgroup delivery code called from item_store will correct it if it's a forum,
2666                                  * but we're going to unconditionally correct it here so that the post will always be owned by our contact.
2667                                  */
2668                                 logger('Correcting item owner.', LOGGER_DEBUG);
2669                                 $item["owner-name"]   = $importer["senderName"];
2670                                 $item["owner-link"]   = $importer["url"];
2671                                 $item["owner-avatar"] = $importer["thumb"];
2672                         }
2673
2674                         if (($importer["rel"] == CONTACT_IS_FOLLOWER) && (!tgroup_check($importer["importer_uid"], $item))) {
2675                                 logger("Contact ".$importer["id"]." is only follower and tgroup check was negative.", LOGGER_DEBUG);
2676                                 return;
2677                         }
2678
2679                         // This is my contact on another system, but it's really me.
2680                         // Turn this into a wall post.
2681                         $notify = item_is_remote_self($importer, $item);
2682
2683                         $posted_id = item_store($item, false, $notify);
2684
2685                         logger("Item was stored with id ".$posted_id, LOGGER_DEBUG);
2686
2687                         if (stristr($item["verb"],ACTIVITY_POKE))
2688                                 self::do_poke($item, $importer, $posted_id);
2689                 }
2690         }
2691
2692         /**
2693          * @brief Deletes items
2694          *
2695          * @param object $xpath XPath object
2696          * @param object $deletion deletion elements
2697          * @param array $importer Record of the importer user mixed with contact of the content
2698          * @todo set proper type-hints
2699          */
2700         private static function process_deletion($xpath, $deletion, $importer) {
2701
2702                 logger("Processing deletions");
2703
2704                 foreach ($deletion->attributes AS $attributes) {
2705                         if ($attributes->name == "ref") {
2706                                 $uri = $attributes->textContent;
2707                         }
2708                         if ($attributes->name == "when") {
2709                                 $when = $attributes->textContent;
2710                         }
2711                 }
2712                 if ($when) {
2713                         $when = datetime_convert("UTC", "UTC", $when, "Y-m-d H:i:s");
2714                 } else {
2715                         $when = datetime_convert("UTC", "UTC", "now", "Y-m-d H:i:s");
2716                 }
2717
2718                 if (!$uri || !$importer["id"]) {
2719                         return false;
2720                 }
2721
2722                 /// @todo Only select the used fields
2723                 $r = q("SELECT `item`.*, `contact`.`self` FROM `item` INNER JOIN `contact` on `item`.`contact-id` = `contact`.`id`
2724                                 WHERE `uri` = '%s' AND `item`.`uid` = %d AND `contact-id` = %d AND NOT `item`.`file` LIKE '%%[%%' LIMIT 1",
2725                                 dbesc($uri),
2726                                 intval($importer["uid"]),
2727                                 intval($importer["id"])
2728                         );
2729                 if (!dbm::is_result($r)) {
2730                         logger("Item with uri " . $uri . " from contact " . $importer["id"] . " for user " . $importer["uid"] . " wasn't found.", LOGGER_DEBUG);
2731                         return;
2732                 } else {
2733
2734                         $item = $r[0];
2735
2736                         $entrytype = self::get_entry_type($importer, $item);
2737
2738                         if (!$item["deleted"]) {
2739                                 logger('deleting item '.$item["id"].' uri='.$uri, LOGGER_DEBUG);
2740                         } else {
2741                                 return;
2742                         }
2743
2744                         if ($item["object-type"] == ACTIVITY_OBJ_EVENT) {
2745                                 logger("Deleting event ".$item["event-id"], LOGGER_DEBUG);
2746                                 event_delete($item["event-id"]);
2747                         }
2748
2749                         if (($item["verb"] == ACTIVITY_TAG) && ($item["object-type"] == ACTIVITY_OBJ_TAGTERM)) {
2750
2751                                 $xo = parse_xml_string($item["object"],false);
2752                                 $xt = parse_xml_string($item["target"],false);
2753
2754                                 if ($xt->type == ACTIVITY_OBJ_NOTE) {
2755                                         $i = q("SELECT `id`, `contact-id`, `tag` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2756                                                 dbesc($xt->id),
2757                                                 intval($importer["importer_uid"])
2758                                         );
2759                                         if (dbm::is_result($i)) {
2760
2761                                                 // For tags, the owner cannot remove the tag on the author's copy of the post.
2762
2763                                                 $owner_remove = (($item["contact-id"] == $i[0]["contact-id"]) ? true: false);
2764                                                 $author_remove = (($item["origin"] && $item["self"]) ? true : false);
2765                                                 $author_copy = (($item["origin"]) ? true : false);
2766
2767                                                 if ($owner_remove && $author_copy) {
2768                                                         return;
2769                                                 }
2770                                                 if ($author_remove || $owner_remove) {
2771                                                         $tags = explode(',',$i[0]["tag"]);
2772                                                         $newtags = array();
2773                                                         if (count($tags)) {
2774                                                                 foreach ($tags as $tag) {
2775                                                                         if (trim($tag) !== trim($xo->body)) {
2776                                                                                 $newtags[] = trim($tag);
2777                                                                         }
2778                                                                 }
2779                                                         }
2780                                                         q("UPDATE `item` SET `tag` = '%s' WHERE `id` = %d",
2781                                                                 dbesc(implode(',', $newtags)),
2782                                                                 intval($i[0]["id"])
2783                                                         );
2784                                                         create_tags_from_item($i[0]["id"]);
2785                                                 }
2786                                         }
2787                                 }
2788                         }
2789
2790                         if ($entrytype == DFRN_TOP_LEVEL) {
2791                                 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s',
2792                                                 `body` = '', `title` = ''
2793                                         WHERE `parent-uri` = '%s' AND `uid` IN (0, %d)",
2794                                                 dbesc($when),
2795                                                 dbesc(datetime_convert()),
2796                                                 dbesc($uri),
2797                                                 intval($importer["uid"])
2798                                         );
2799                                 create_tags_from_itemuri($uri, $importer["uid"]);
2800                                 create_files_from_itemuri($uri, $importer["uid"]);
2801                                 update_thread_uri($uri, $importer["uid"]);
2802                         } else {
2803                                 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s',
2804                                                 `body` = '', `title` = ''
2805                                         WHERE `uri` = '%s' AND `uid` IN (0, %d)",
2806                                                 dbesc($when),
2807                                                 dbesc(datetime_convert()),
2808                                                 dbesc($uri),
2809                                                 intval($importer["uid"])
2810                                         );
2811                                 create_tags_from_itemuri($uri, $importer["uid"]);
2812                                 create_files_from_itemuri($uri, $importer["uid"]);
2813                                 update_thread_uri($uri, $importer["importer_uid"]);
2814                                 if ($item["last-child"]) {
2815                                         // ensure that last-child is set in case the comment that had it just got wiped.
2816                                         q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` IN (0, %d)",
2817                                                 dbesc(datetime_convert()),
2818                                                 dbesc($item["parent-uri"]),
2819                                                 intval($item["uid"])
2820                                         );
2821                                         // who is the last child now?
2822                                         $r = q("SELECT `id` FROM `item` WHERE `parent-uri` = '%s' AND `type` != 'activity' AND `deleted` = 0 AND `moderated` = 0 AND `uid` = %d
2823                                                 ORDER BY `created` DESC LIMIT 1",
2824                                                         dbesc($item["parent-uri"]),
2825                                                         intval($importer["uid"])
2826                                         );
2827                                         if (dbm::is_result($r)) {
2828                                                 q("UPDATE `item` SET `last-child` = 1 WHERE `id` = %d",
2829                                                         intval($r[0]["id"])
2830                                                 );
2831                                         }
2832                                 }
2833                                 // if this is a relayed delete, propagate it to other recipients
2834
2835                                 if ($entrytype == DFRN_REPLY_RC) {
2836                                         logger("Notifying followers about deletion of post " . $item["id"], LOGGER_DEBUG);
2837                                         proc_run(PRIORITY_HIGH, "include/notifier.php","drop", $item["id"]);
2838                                 }
2839                         }
2840                 }
2841         }
2842
2843         /**
2844          * @brief Imports a DFRN message
2845          *
2846          * @param text $xml The DFRN message
2847          * @param array $importer Record of the importer user mixed with contact of the content
2848          * @param bool $sort_by_date Is used when feeds are polled
2849          * @return integer Import status
2850          * @todo set proper type-hints
2851          */
2852         public static function import($xml, $importer, $sort_by_date = false) {
2853
2854                 if ($xml == "") {
2855                         return 400;
2856                 }
2857
2858                 $doc = new DOMDocument();
2859                 @$doc->loadXML($xml);
2860
2861                 $xpath = new DomXPath($doc);
2862                 $xpath->registerNamespace("atom", NAMESPACE_ATOM1);
2863                 $xpath->registerNamespace("thr", NAMESPACE_THREAD);
2864                 $xpath->registerNamespace("at", NAMESPACE_TOMB);
2865                 $xpath->registerNamespace("media", NAMESPACE_MEDIA);
2866                 $xpath->registerNamespace("dfrn", NAMESPACE_DFRN);
2867                 $xpath->registerNamespace("activity", NAMESPACE_ACTIVITY);
2868                 $xpath->registerNamespace("georss", NAMESPACE_GEORSS);
2869                 $xpath->registerNamespace("poco", NAMESPACE_POCO);
2870                 $xpath->registerNamespace("ostatus", NAMESPACE_OSTATUS);
2871                 $xpath->registerNamespace("statusnet", NAMESPACE_STATUSNET);
2872
2873                 $header = array();
2874                 $header["uid"] = $importer["uid"];
2875                 $header["network"] = NETWORK_DFRN;
2876                 $header["type"] = "remote";
2877                 $header["wall"] = 0;
2878                 $header["origin"] = 0;
2879                 $header["contact-id"] = $importer["id"];
2880
2881                 // Update the contact table if the data has changed
2882
2883                 // The "atom:author" is only present in feeds
2884                 if ($xpath->query("/atom:feed/atom:author")->length > 0) {
2885                         self::fetchauthor($xpath, $doc->firstChild, $importer, "atom:author", false, $xml);
2886                 }
2887
2888                 // Only the "dfrn:owner" in the head section contains all data
2889                 if ($xpath->query("/atom:feed/dfrn:owner")->length > 0) {
2890                         self::fetchauthor($xpath, $doc->firstChild, $importer, "dfrn:owner", false, $xml);
2891                 }
2892
2893                 logger("Import DFRN message for user " . $importer["uid"] . " from contact " . $importer["id"], LOGGER_DEBUG);
2894
2895                 // The account type is new since 3.5.1
2896                 if ($xpath->query("/atom:feed/dfrn:account_type")->length > 0) {
2897                         $accounttype = intval($xpath->evaluate("/atom:feed/dfrn:account_type/text()", $context)->item(0)->nodeValue);
2898
2899                         if ($accounttype != $importer["contact-type"]) {
2900                                 dba::update('contact', array('contact-type' => $accounttype), array('id' => $importer["id"]));
2901                         }
2902                 }
2903
2904                 // is it a public forum? Private forums aren't supported with this method
2905                 // This is deprecated since 3.5.1
2906                 $forum = intval($xpath->evaluate("/atom:feed/dfrn:community/text()", $context)->item(0)->nodeValue);
2907
2908                 if ($forum != $importer["forum"]) {
2909                         $condition = array('`forum` != ? AND `id` = ?', $forum, $importer["id"]);
2910                         dba::update('contact', array('forum' => $forum), $condition);
2911                 }
2912
2913                 // We are processing relocations even if we are ignoring a contact
2914                 $relocations = $xpath->query("/atom:feed/dfrn:relocate");
2915                 foreach ($relocations AS $relocation) {
2916                         self::process_relocation($xpath, $relocation, $importer);
2917                 }
2918
2919                 if ($importer["readonly"]) {
2920                         // We aren't receiving stuff from this person. But we will quietly ignore them
2921                         // rather than a blatant "go away" message.
2922                         logger('ignoring contact '.$importer["id"]);
2923                         return 403;
2924                 }
2925
2926                 $mails = $xpath->query("/atom:feed/dfrn:mail");
2927                 foreach ($mails AS $mail) {
2928                         self::process_mail($xpath, $mail, $importer);
2929                 }
2930
2931                 $suggestions = $xpath->query("/atom:feed/dfrn:suggest");
2932                 foreach ($suggestions AS $suggestion) {
2933                         self::process_suggestion($xpath, $suggestion, $importer);
2934                 }
2935
2936                 $deletions = $xpath->query("/atom:feed/at:deleted-entry");
2937                 foreach ($deletions AS $deletion) {
2938                         self::process_deletion($xpath, $deletion, $importer);
2939                 }
2940
2941                 if (!$sort_by_date) {
2942                         $entries = $xpath->query("/atom:feed/atom:entry");
2943                         foreach ($entries AS $entry) {
2944                                 self::process_entry($header, $xpath, $entry, $importer, $xml);
2945                         }
2946                 } else {
2947                         $newentries = array();
2948                         $entries = $xpath->query("/atom:feed/atom:entry");
2949                         foreach ($entries AS $entry) {
2950                                 $created = $xpath->query("atom:published/text()", $entry)->item(0)->nodeValue;
2951                                 $newentries[strtotime($created)] = $entry;
2952                         }
2953
2954                         // Now sort after the publishing date
2955                         ksort($newentries);
2956
2957                         foreach ($newentries AS $entry) {
2958                                 self::process_entry($header, $xpath, $entry, $importer, $xml);
2959                         }
2960                 }
2961                 logger("Import done for user " . $importer["uid"] . " from contact " . $importer["id"], LOGGER_DEBUG);
2962                 return 200;
2963         }
2964 }