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