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