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