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