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