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