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