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