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