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