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