]> git.mxchange.org Git - friendica.git/blob - include/dfrn.php
Optimized timeouts during network operations
[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         /**
868          * @brief Delivers the atom content to the contacts
869          *
870          * @param array $owner Owner record
871          * @param array $contactr Contact record of the receiver
872          * @param string $atom Content that will be transmitted
873          * @param bool $dissolve (to be documented)
874          *
875          * @return int Deliver status. -1 means an error.
876          */
877         public static function deliver($owner,$contact,$atom, $dissolve = false) {
878
879                 $a = get_app();
880
881                 $idtosend = $orig_id = (($contact['dfrn-id']) ? $contact['dfrn-id'] : $contact['issued-id']);
882
883                 if($contact['duplex'] && $contact['dfrn-id'])
884                         $idtosend = '0:' . $orig_id;
885                 if($contact['duplex'] && $contact['issued-id'])
886                         $idtosend = '1:' . $orig_id;
887
888
889                 $rino = get_config('system','rino_encrypt');
890                 $rino = intval($rino);
891                 // use RINO1 if mcrypt isn't installed and RINO2 was selected
892                 if ($rino==2 and !function_exists('mcrypt_create_iv')) $rino=1;
893
894                 logger("Local rino version: ". $rino, LOGGER_DEBUG);
895
896                 $ssl_val = intval(get_config('system','ssl_policy'));
897                 $ssl_policy = '';
898
899                 switch($ssl_val){
900                         case SSL_POLICY_FULL:
901                                 $ssl_policy = 'full';
902                                 break;
903                         case SSL_POLICY_SELFSIGN:
904                                 $ssl_policy = 'self';
905                                 break;
906                         case SSL_POLICY_NONE:
907                         default:
908                                 $ssl_policy = 'none';
909                                 break;
910                 }
911
912                 $url = $contact['notify'] . '&dfrn_id=' . $idtosend . '&dfrn_version=' . DFRN_PROTOCOL_VERSION . (($rino) ? '&rino='.$rino : '');
913
914                 logger('dfrn_deliver: ' . $url);
915
916                 $ret = z_fetch_url($url);
917
918                 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
919                         return(-1); // timed out
920                 }
921
922                 $xml = $ret['body'];
923
924                 $curl_stat = $a->get_curl_code();
925                 if(! $curl_stat)
926                         return(-1); // timed out
927
928                 logger('dfrn_deliver: ' . $xml, LOGGER_DATA);
929
930                 if(! $xml)
931                         return 3;
932
933                 if(strpos($xml,'<?xml') === false) {
934                         logger('dfrn_deliver: no valid XML returned');
935                         logger('dfrn_deliver: returned XML: ' . $xml, LOGGER_DATA);
936                         return 3;
937                 }
938
939                 $res = parse_xml_string($xml);
940
941                 if((intval($res->status) != 0) || (! strlen($res->challenge)) || (! strlen($res->dfrn_id)))
942                         return (($res->status) ? $res->status : 3);
943
944                 $postvars     = array();
945                 $sent_dfrn_id = hex2bin((string) $res->dfrn_id);
946                 $challenge    = hex2bin((string) $res->challenge);
947                 $perm         = (($res->perm) ? $res->perm : null);
948                 $dfrn_version = (float) (($res->dfrn_version) ? $res->dfrn_version : 2.0);
949                 $rino_remote_version = intval($res->rino);
950                 $page         = (($owner['page-flags'] == PAGE_COMMUNITY) ? 1 : 0);
951
952                 logger("Remote rino version: ".$rino_remote_version." for ".$contact["url"], LOGGER_DEBUG);
953
954                 if($owner['page-flags'] == PAGE_PRVGROUP)
955                         $page = 2;
956
957                 $final_dfrn_id = '';
958
959                 if($perm) {
960                         if((($perm == 'rw') && (! intval($contact['writable'])))
961                                 || (($perm == 'r') && (intval($contact['writable'])))) {
962                                 q("update contact set writable = %d where id = %d",
963                                         intval(($perm == 'rw') ? 1 : 0),
964                                         intval($contact['id'])
965                                 );
966                                 $contact['writable'] = (string) 1 - intval($contact['writable']);
967                         }
968                 }
969
970                 if(($contact['duplex'] && strlen($contact['pubkey']))
971                         || ($owner['page-flags'] == PAGE_COMMUNITY && strlen($contact['pubkey']))
972                         || ($contact['rel'] == CONTACT_IS_SHARING && strlen($contact['pubkey']))) {
973                         openssl_public_decrypt($sent_dfrn_id,$final_dfrn_id,$contact['pubkey']);
974                         openssl_public_decrypt($challenge,$postvars['challenge'],$contact['pubkey']);
975                 } else {
976                         openssl_private_decrypt($sent_dfrn_id,$final_dfrn_id,$contact['prvkey']);
977                         openssl_private_decrypt($challenge,$postvars['challenge'],$contact['prvkey']);
978                 }
979
980                 $final_dfrn_id = substr($final_dfrn_id, 0, strpos($final_dfrn_id, '.'));
981
982                 if(strpos($final_dfrn_id,':') == 1)
983                         $final_dfrn_id = substr($final_dfrn_id,2);
984
985                 if($final_dfrn_id != $orig_id) {
986                         logger('dfrn_deliver: wrong dfrn_id.');
987                         // did not decode properly - cannot trust this site
988                         return 3;
989                 }
990
991                 $postvars['dfrn_id']      = $idtosend;
992                 $postvars['dfrn_version'] = DFRN_PROTOCOL_VERSION;
993                 if($dissolve)
994                         $postvars['dissolve'] = '1';
995
996
997                 if((($contact['rel']) && ($contact['rel'] != CONTACT_IS_SHARING) && (! $contact['blocked'])) || ($owner['page-flags'] == PAGE_COMMUNITY)) {
998                         $postvars['data'] = $atom;
999                         $postvars['perm'] = 'rw';
1000                 } else {
1001                         $postvars['data'] = str_replace('<dfrn:comment-allow>1','<dfrn:comment-allow>0',$atom);
1002                         $postvars['perm'] = 'r';
1003                 }
1004
1005                 $postvars['ssl_policy'] = $ssl_policy;
1006
1007                 if($page)
1008                         $postvars['page'] = $page;
1009
1010
1011                 if($rino>0 && $rino_remote_version>0 && (! $dissolve)) {
1012                         logger('rino version: '. $rino_remote_version);
1013
1014                         switch($rino_remote_version) {
1015                                 case 1:
1016                                         // Deprecated rino version!
1017                                         $key = substr(random_string(),0,16);
1018                                         $data = aes_encrypt($postvars['data'],$key);
1019                                         break;
1020                                 case 2:
1021                                         // RINO 2 based on php-encryption
1022                                         try {
1023                                                 $key = Crypto::createNewRandomKey();
1024                                         } catch (CryptoTestFailed $ex) {
1025                                                 logger('Cannot safely create a key');
1026                                                 return -1;
1027                                         } catch (CannotPerformOperation $ex) {
1028                                                 logger('Cannot safely create a key');
1029                                                 return -1;
1030                                         }
1031                                         try {
1032                                                 $data = Crypto::encrypt($postvars['data'], $key);
1033                                         } catch (CryptoTestFailed $ex) {
1034                                                 logger('Cannot safely perform encryption');
1035                                                 return -1;
1036                                         } catch (CannotPerformOperation $ex) {
1037                                                 logger('Cannot safely perform encryption');
1038                                                 return -1;
1039                                         }
1040                                         break;
1041                                 default:
1042                                         logger("rino: invalid requested verision '$rino_remote_version'");
1043                                         return -1;
1044                         }
1045
1046                         $postvars['rino'] = $rino_remote_version;
1047                         $postvars['data'] = bin2hex($data);
1048
1049                         #logger('rino: sent key = ' . $key, LOGGER_DEBUG);
1050
1051
1052                         if($dfrn_version >= 2.1) {
1053                                 if(($contact['duplex'] && strlen($contact['pubkey']))
1054                                         || ($owner['page-flags'] == PAGE_COMMUNITY && strlen($contact['pubkey']))
1055                                         || ($contact['rel'] == CONTACT_IS_SHARING && strlen($contact['pubkey'])))
1056
1057                                         openssl_public_encrypt($key,$postvars['key'],$contact['pubkey']);
1058                                 else
1059                                         openssl_private_encrypt($key,$postvars['key'],$contact['prvkey']);
1060
1061                         } else {
1062                                 if(($contact['duplex'] && strlen($contact['prvkey'])) || ($owner['page-flags'] == PAGE_COMMUNITY))
1063                                         openssl_private_encrypt($key,$postvars['key'],$contact['prvkey']);
1064                                 else
1065                                         openssl_public_encrypt($key,$postvars['key'],$contact['pubkey']);
1066
1067                         }
1068
1069                         logger('md5 rawkey ' . md5($postvars['key']));
1070
1071                         $postvars['key'] = bin2hex($postvars['key']);
1072                 }
1073
1074
1075                 logger('dfrn_deliver: ' . "SENDING: " . print_r($postvars,true), LOGGER_DATA);
1076
1077                 $xml = post_url($contact['notify'],$postvars);
1078
1079                 logger('dfrn_deliver: ' . "RECEIVED: " . $xml, LOGGER_DATA);
1080
1081                 $curl_stat = $a->get_curl_code();
1082                 if((! $curl_stat) || (! strlen($xml)))
1083                         return(-1); // timed out
1084
1085                 if(($curl_stat == 503) && (stristr($a->get_curl_headers(),'retry-after')))
1086                         return(-1);
1087
1088                 if(strpos($xml,'<?xml') === false) {
1089                         logger('dfrn_deliver: phase 2: no valid XML returned');
1090                         logger('dfrn_deliver: phase 2: returned XML: ' . $xml, LOGGER_DATA);
1091                         return 3;
1092                 }
1093
1094                 if($contact['term-date'] != '0000-00-00 00:00:00') {
1095                         logger("dfrn_deliver: $url back from the dead - removing mark for death");
1096                         require_once('include/Contact.php');
1097                         unmark_for_death($contact);
1098                 }
1099
1100                 $res = parse_xml_string($xml);
1101
1102                 return $res->status;
1103         }
1104
1105         /**
1106          * @brief Add new birthday event for this person
1107          *
1108          * @param array $contact Contact record
1109          * @param string $birthday Birthday of the contact
1110          *
1111          */
1112         private static function birthday_event($contact, $birthday) {
1113
1114                 // Check for duplicates
1115                 $r = q("SELECT `id` FROM `event` WHERE `uid` = %d AND `cid` = %d AND `start` = '%s' AND `type` = '%s' LIMIT 1",
1116                         intval($contact["uid"]),
1117                         intval($contact["id"]),
1118                         dbesc(datetime_convert("UTC","UTC", $birthday)),
1119                         dbesc("birthday"));
1120
1121                 if (dbm::is_result($r)) {
1122                         return;
1123                 }
1124
1125                 logger("updating birthday: ".$birthday." for contact ".$contact["id"]);
1126
1127                 $bdtext = sprintf(t("%s\'s birthday"), $contact["name"]);
1128                 $bdtext2 = sprintf(t("Happy Birthday %s"), " [url=".$contact["url"]."]".$contact["name"]."[/url]") ;
1129
1130                 $r = q("INSERT INTO `event` (`uid`,`cid`,`created`,`edited`,`start`,`finish`,`summary`,`desc`,`type`)
1131                         VALUES ( %d, %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s') ",
1132                         intval($contact["uid"]),
1133                         intval($contact["id"]),
1134                         dbesc(datetime_convert()),
1135                         dbesc(datetime_convert()),
1136                         dbesc(datetime_convert("UTC","UTC", $birthday)),
1137                         dbesc(datetime_convert("UTC","UTC", $birthday." + 1 day ")),
1138                         dbesc($bdtext),
1139                         dbesc($bdtext2),
1140                         dbesc("birthday")
1141                 );
1142         }
1143
1144         /**
1145          * @brief Fetch the author data from head or entry items
1146          *
1147          * @param object $xpath XPath object
1148          * @param object $context In which context should the data be searched
1149          * @param array $importer Record of the importer user mixed with contact of the content
1150          * @param string $element Element name from which the data is fetched
1151          * @param bool $onlyfetch Should the data only be fetched or should it update the contact record as well
1152          *
1153          * @return Returns an array with relevant data of the author
1154          */
1155         private static function fetchauthor($xpath, $context, $importer, $element, $onlyfetch, $xml = "") {
1156
1157                 $author = array();
1158                 $author["name"] = $xpath->evaluate($element."/atom:name/text()", $context)->item(0)->nodeValue;
1159                 $author["link"] = $xpath->evaluate($element."/atom:uri/text()", $context)->item(0)->nodeValue;
1160
1161                 $r = q("SELECT `id`, `uid`, `url`, `network`, `avatar-date`, `name-date`, `uri-date`, `addr`,
1162                                 `name`, `nick`, `about`, `location`, `keywords`, `xmpp`, `bdyear`, `bd`, `hidden`, `contact-type`
1163                                 FROM `contact` WHERE `uid` = %d AND `nurl` = '%s' AND `network` != '%s'",
1164                         intval($importer["uid"]), dbesc(normalise_link($author["link"])), dbesc(NETWORK_STATUSNET));
1165                 if ($r) {
1166                         $contact = $r[0];
1167                         $author["contact-id"] = $r[0]["id"];
1168                         $author["network"] = $r[0]["network"];
1169                 } else {
1170                         if (!$onlyfetch)
1171                                 logger("Contact ".$author["link"]." wasn't found for user ".$importer["uid"]." XML: ".$xml, LOGGER_DEBUG);
1172
1173                         $author["contact-id"] = $importer["id"];
1174                         $author["network"] = $importer["network"];
1175                         $onlyfetch = true;
1176                 }
1177
1178                 // Until now we aren't serving different sizes - but maybe later
1179                 $avatarlist = array();
1180                 /// @todo check if "avatar" or "photo" would be the best field in the specification
1181                 $avatars = $xpath->query($element."/atom:link[@rel='avatar']", $context);
1182                 foreach($avatars AS $avatar) {
1183                         $href = "";
1184                         $width = 0;
1185                         foreach($avatar->attributes AS $attributes) {
1186                                 if ($attributes->name == "href")
1187                                         $href = $attributes->textContent;
1188                                 if ($attributes->name == "width")
1189                                         $width = $attributes->textContent;
1190                                 if ($attributes->name == "updated")
1191                                         $contact["avatar-date"] = $attributes->textContent;
1192                         }
1193                         if (($width > 0) AND ($href != ""))
1194                                 $avatarlist[$width] = $href;
1195                 }
1196                 if (count($avatarlist) > 0) {
1197                         krsort($avatarlist);
1198                         $author["avatar"] = current($avatarlist);
1199                 }
1200
1201                 if ($r AND !$onlyfetch) {
1202                         logger("Check if contact details for contact ".$r[0]["id"]." (".$r[0]["nick"].") have to be updated.", LOGGER_DEBUG);
1203
1204                         $poco = array("url" => $contact["url"]);
1205
1206                         // When was the last change to name or uri?
1207                         $name_element = $xpath->query($element."/atom:name", $context)->item(0);
1208                         foreach($name_element->attributes AS $attributes)
1209                                 if ($attributes->name == "updated")
1210                                         $poco["name-date"] = $attributes->textContent;
1211
1212                         $link_element = $xpath->query($element."/atom:link", $context)->item(0);
1213                         foreach($link_element->attributes AS $attributes)
1214                                 if ($attributes->name == "updated")
1215                                         $poco["uri-date"] = $attributes->textContent;
1216
1217                         // Update contact data
1218                         $value = $xpath->evaluate($element."/dfrn:handle/text()", $context)->item(0)->nodeValue;
1219                         if ($value != "")
1220                                 $poco["addr"] = $value;
1221
1222                         $value = $xpath->evaluate($element."/poco:displayName/text()", $context)->item(0)->nodeValue;
1223                         if ($value != "")
1224                                 $poco["name"] = $value;
1225
1226                         $value = $xpath->evaluate($element."/poco:preferredUsername/text()", $context)->item(0)->nodeValue;
1227                         if ($value != "")
1228                                 $poco["nick"] = $value;
1229
1230                         $value = $xpath->evaluate($element."/poco:note/text()", $context)->item(0)->nodeValue;
1231                         if ($value != "")
1232                                 $poco["about"] = $value;
1233
1234                         $value = $xpath->evaluate($element."/poco:address/poco:formatted/text()", $context)->item(0)->nodeValue;
1235                         if ($value != "")
1236                                 $poco["location"] = $value;
1237
1238                         /// @todo Only search for elements with "poco:type" = "xmpp"
1239                         $value = $xpath->evaluate($element."/poco:ims/poco:value/text()", $context)->item(0)->nodeValue;
1240                         if ($value != "")
1241                                 $poco["xmpp"] = $value;
1242
1243                         /// @todo Add support for the following fields that we don't support by now in the contact table:
1244                         /// - poco:utcOffset
1245                         /// - poco:urls
1246                         /// - poco:locality
1247                         /// - poco:region
1248                         /// - poco:country
1249
1250                         // If the "hide" element is present then the profile isn't searchable.
1251                         $hide = intval($xpath->evaluate($element."/dfrn:hide/text()", $context)->item(0)->nodeValue == "true");
1252
1253                         logger("Hidden status for contact ".$contact["url"].": ".$hide, LOGGER_DEBUG);
1254
1255                         // If the contact isn't searchable then set the contact to "hidden".
1256                         // Problem: This can be manually overridden by the user.
1257                         if ($hide)
1258                                 $contact["hidden"] = true;
1259
1260                         // Save the keywords into the contact table
1261                         $tags = array();
1262                         $tagelements = $xpath->evaluate($element."/poco:tags/text()", $context);
1263                         foreach($tagelements AS $tag)
1264                                 $tags[$tag->nodeValue] = $tag->nodeValue;
1265
1266                         if (count($tags))
1267                                 $poco["keywords"] = implode(", ", $tags);
1268
1269                         // "dfrn:birthday" contains the birthday converted to UTC
1270                         $old_bdyear = $contact["bdyear"];
1271
1272                         $birthday = $xpath->evaluate($element."/dfrn:birthday/text()", $context)->item(0)->nodeValue;
1273
1274                         if (strtotime($birthday) > time()) {
1275                                 $bd_timestamp = strtotime($birthday);
1276
1277                                 $poco["bdyear"] = date("Y", $bd_timestamp);
1278                         }
1279
1280                         // "poco:birthday" is the birthday in the format "yyyy-mm-dd"
1281                         $value = $xpath->evaluate($element."/poco:birthday/text()", $context)->item(0)->nodeValue;
1282
1283                         if (!in_array($value, array("", "0000-00-00"))) {
1284                                 $bdyear = date("Y");
1285                                 $value = str_replace("0000", $bdyear, $value);
1286
1287                                 if (strtotime($value) < time()) {
1288                                         $value = str_replace($bdyear, $bdyear + 1, $value);
1289                                         $bdyear = $bdyear + 1;
1290                                 }
1291
1292                                 $poco["bd"] = $value;
1293                         }
1294
1295                         $contact = array_merge($contact, $poco);
1296
1297                         if ($old_bdyear != $contact["bdyear"])
1298                                 self::birthday_event($contact, $birthday);
1299
1300                         // Get all field names
1301                         $fields = array();
1302                         foreach ($r[0] AS $field => $data)
1303                                 $fields[$field] = $data;
1304
1305                         unset($fields["id"]);
1306                         unset($fields["uid"]);
1307                         unset($fields["url"]);
1308                         unset($fields["avatar-date"]);
1309                         unset($fields["name-date"]);
1310                         unset($fields["uri-date"]);
1311
1312                         // Update check for this field has to be done differently
1313                         $datefields = array("name-date", "uri-date");
1314                         foreach ($datefields AS $field)
1315                                 if (strtotime($contact[$field]) > strtotime($r[0][$field])) {
1316                                         logger("Difference for contact ".$contact["id"]." in field '".$field."'. New value: '".$contact[$field]."', old value '".$r[0][$field]."'", LOGGER_DEBUG);
1317                                         $update = true;
1318                                 }
1319
1320                         foreach ($fields AS $field => $data)
1321                                 if ($contact[$field] != $r[0][$field]) {
1322                                         logger("Difference for contact ".$contact["id"]." in field '".$field."'. New value: '".$contact[$field]."', old value '".$r[0][$field]."'", LOGGER_DEBUG);
1323                                         $update = true;
1324                                 }
1325
1326                         if ($update) {
1327                                 logger("Update contact data for contact ".$contact["id"]." (".$contact["nick"].")", LOGGER_DEBUG);
1328
1329                                 q("UPDATE `contact` SET `name` = '%s', `nick` = '%s', `about` = '%s', `location` = '%s',
1330                                         `addr` = '%s', `keywords` = '%s', `bdyear` = '%s', `bd` = '%s', `hidden` = %d,
1331                                         `xmpp` = '%s', `name-date`  = '%s', `uri-date` = '%s'
1332                                         WHERE `id` = %d AND `network` = '%s'",
1333                                         dbesc($contact["name"]), dbesc($contact["nick"]), dbesc($contact["about"]), dbesc($contact["location"]),
1334                                         dbesc($contact["addr"]), dbesc($contact["keywords"]), dbesc($contact["bdyear"]),
1335                                         dbesc($contact["bd"]), intval($contact["hidden"]), dbesc($contact["xmpp"]),
1336                                         dbesc($contact["name-date"]), dbesc($contact["uri-date"]),
1337                                         intval($contact["id"]), dbesc($contact["network"]));
1338                         }
1339
1340                         update_contact_avatar($author["avatar"], $importer["uid"], $contact["id"],
1341                                                 (strtotime($contact["avatar-date"]) > strtotime($r[0]["avatar-date"])));
1342
1343                         // The generation is a sign for the reliability of the provided data.
1344                         // It is used in the socgraph.php to prevent that old contact data
1345                         // that was relayed over several servers can overwrite contact
1346                         // data that we received directly.
1347
1348                         $poco["generation"] = 2;
1349                         $poco["photo"] = $author["avatar"];
1350                         $poco["hide"] = $hide;
1351                         $poco["contact-type"] = $contact["contact-type"];
1352                         update_gcontact($poco);
1353                 }
1354
1355                 return($author);
1356         }
1357
1358         /**
1359          * @brief Transforms activity objects into an XML string
1360          *
1361          * @param object $xpath XPath object
1362          * @param object $activity Activity object
1363          * @param text $element element name
1364          *
1365          * @return string XML string
1366          */
1367         private static function transform_activity($xpath, $activity, $element) {
1368                 if (!is_object($activity))
1369                         return "";
1370
1371                 $obj_doc = new DOMDocument("1.0", "utf-8");
1372                 $obj_doc->formatOutput = true;
1373
1374                 $obj_element = $obj_doc->createElementNS(NAMESPACE_ATOM1, $element);
1375
1376                 $activity_type = $xpath->query("activity:object-type/text()", $activity)->item(0)->nodeValue;
1377                 xml::add_element($obj_doc, $obj_element, "type", $activity_type);
1378
1379                 $id = $xpath->query("atom:id", $activity)->item(0);
1380                 if (is_object($id))
1381                         $obj_element->appendChild($obj_doc->importNode($id, true));
1382
1383                 $title = $xpath->query("atom:title", $activity)->item(0);
1384                 if (is_object($title))
1385                         $obj_element->appendChild($obj_doc->importNode($title, true));
1386
1387                 $links = $xpath->query("atom:link", $activity);
1388                 if (is_object($links))
1389                         foreach ($links AS $link)
1390                                 $obj_element->appendChild($obj_doc->importNode($link, true));
1391
1392                 $content = $xpath->query("atom:content", $activity)->item(0);
1393                 if (is_object($content))
1394                         $obj_element->appendChild($obj_doc->importNode($content, true));
1395
1396                 $obj_doc->appendChild($obj_element);
1397
1398                 $objxml = $obj_doc->saveXML($obj_element);
1399
1400                 /// @todo This isn't totally clean. We should find a way to transform the namespaces
1401                 $objxml = str_replace("<".$element.' xmlns="http://www.w3.org/2005/Atom">', "<".$element.">", $objxml);
1402                 return($objxml);
1403         }
1404
1405         /**
1406          * @brief Processes the mail elements
1407          *
1408          * @param object $xpath XPath object
1409          * @param object $mail mail elements
1410          * @param array $importer Record of the importer user mixed with contact of the content
1411          */
1412         private static function process_mail($xpath, $mail, $importer) {
1413
1414                 logger("Processing mails");
1415
1416                 $msg = array();
1417                 $msg["uid"] = $importer["importer_uid"];
1418                 $msg["from-name"] = $xpath->query("dfrn:sender/dfrn:name/text()", $mail)->item(0)->nodeValue;
1419                 $msg["from-url"] = $xpath->query("dfrn:sender/dfrn:uri/text()", $mail)->item(0)->nodeValue;
1420                 $msg["from-photo"] = $xpath->query("dfrn:sender/dfrn:avatar/text()", $mail)->item(0)->nodeValue;
1421                 $msg["contact-id"] = $importer["id"];
1422                 $msg["uri"] = $xpath->query("dfrn:id/text()", $mail)->item(0)->nodeValue;
1423                 $msg["parent-uri"] = $xpath->query("dfrn:in-reply-to/text()", $mail)->item(0)->nodeValue;
1424                 $msg["created"] = $xpath->query("dfrn:sentdate/text()", $mail)->item(0)->nodeValue;
1425                 $msg["title"] = $xpath->query("dfrn:subject/text()", $mail)->item(0)->nodeValue;
1426                 $msg["body"] = $xpath->query("dfrn:content/text()", $mail)->item(0)->nodeValue;
1427                 $msg["seen"] = 0;
1428                 $msg["replied"] = 0;
1429
1430                 dbm::esc_array($msg, true);
1431
1432                 $r = dbq("INSERT INTO `mail` (`".implode("`, `", array_keys($msg))."`) VALUES (".implode(", ", array_values($msg)).")");
1433
1434                 // send notifications.
1435
1436                 $notif_params = array(
1437                         "type" => NOTIFY_MAIL,
1438                         "notify_flags" => $importer["notify-flags"],
1439                         "language" => $importer["language"],
1440                         "to_name" => $importer["username"],
1441                         "to_email" => $importer["email"],
1442                         "uid" => $importer["importer_uid"],
1443                         "item" => $msg,
1444                         "source_name" => $msg["from-name"],
1445                         "source_link" => $importer["url"],
1446                         "source_photo" => $importer["thumb"],
1447                         "verb" => ACTIVITY_POST,
1448                         "otype" => "mail"
1449                 );
1450
1451                 notification($notif_params);
1452
1453                 logger("Mail is processed, notification was sent.");
1454         }
1455
1456         /**
1457          * @brief Processes the suggestion elements
1458          *
1459          * @param object $xpath XPath object
1460          * @param object $suggestion suggestion elements
1461          * @param array $importer Record of the importer user mixed with contact of the content
1462          */
1463         private static function process_suggestion($xpath, $suggestion, $importer) {
1464                 $a = get_app();
1465
1466                 logger("Processing suggestions");
1467
1468                 $suggest = array();
1469                 $suggest["uid"] = $importer["importer_uid"];
1470                 $suggest["cid"] = $importer["id"];
1471                 $suggest["url"] = $xpath->query("dfrn:url/text()", $suggestion)->item(0)->nodeValue;
1472                 $suggest["name"] = $xpath->query("dfrn:name/text()", $suggestion)->item(0)->nodeValue;
1473                 $suggest["photo"] = $xpath->query("dfrn:photo/text()", $suggestion)->item(0)->nodeValue;
1474                 $suggest["request"] = $xpath->query("dfrn:request/text()", $suggestion)->item(0)->nodeValue;
1475                 $suggest["body"] = $xpath->query("dfrn:note/text()", $suggestion)->item(0)->nodeValue;
1476
1477                 // Does our member already have a friend matching this description?
1478
1479                 $r = q("SELECT `id` FROM `contact` WHERE `name` = '%s' AND `nurl` = '%s' AND `uid` = %d LIMIT 1",
1480                         dbesc($suggest["name"]),
1481                         dbesc(normalise_link($suggest["url"])),
1482                         intval($suggest["uid"])
1483                 );
1484                 if (dbm::is_result($r))
1485                         return false;
1486
1487                 // Do we already have an fcontact record for this person?
1488
1489                 $fid = 0;
1490                 $r = q("SELECT `id` FROM `fcontact` WHERE `url` = '%s' AND `name` = '%s' AND `request` = '%s' LIMIT 1",
1491                         dbesc($suggest["url"]),
1492                         dbesc($suggest["name"]),
1493                         dbesc($suggest["request"])
1494                 );
1495                 if (dbm::is_result($r)) {
1496                         $fid = $r[0]["id"];
1497
1498                         // OK, we do. Do we already have an introduction for this person ?
1499                         $r = q("SELECT `id` FROM `intro` WHERE `uid` = %d AND `fid` = %d LIMIT 1",
1500                                 intval($suggest["uid"]),
1501                                 intval($fid)
1502                         );
1503                         if (dbm::is_result($r))
1504                                 return false;
1505                 }
1506                 if(!$fid)
1507                         $r = q("INSERT INTO `fcontact` (`name`,`url`,`photo`,`request`) VALUES ('%s', '%s', '%s', '%s')",
1508                         dbesc($suggest["name"]),
1509                         dbesc($suggest["url"]),
1510                         dbesc($suggest["photo"]),
1511                         dbesc($suggest["request"])
1512                 );
1513                 $r = q("SELECT `id` FROM `fcontact` WHERE `url` = '%s' AND `name` = '%s' AND `request` = '%s' LIMIT 1",
1514                         dbesc($suggest["url"]),
1515                         dbesc($suggest["name"]),
1516                         dbesc($suggest["request"])
1517                 );
1518                 if (dbm::is_result($r))
1519                         $fid = $r[0]["id"];
1520                 else
1521                         // database record did not get created. Quietly give up.
1522                         return false;
1523
1524
1525                 $hash = random_string();
1526
1527                 $r = q("INSERT INTO `intro` (`uid`, `fid`, `contact-id`, `note`, `hash`, `datetime`, `blocked`)
1528                         VALUES(%d, %d, %d, '%s', '%s', '%s', %d)",
1529                         intval($suggest["uid"]),
1530                         intval($fid),
1531                         intval($suggest["cid"]),
1532                         dbesc($suggest["body"]),
1533                         dbesc($hash),
1534                         dbesc(datetime_convert()),
1535                         intval(0)
1536                 );
1537
1538                 notification(array(
1539                         "type"         => NOTIFY_SUGGEST,
1540                         "notify_flags" => $importer["notify-flags"],
1541                         "language"     => $importer["language"],
1542                         "to_name"      => $importer["username"],
1543                         "to_email"     => $importer["email"],
1544                         "uid"          => $importer["importer_uid"],
1545                         "item"         => $suggest,
1546                         "link"         => App::get_baseurl()."/notifications/intros",
1547                         "source_name"  => $importer["name"],
1548                         "source_link"  => $importer["url"],
1549                         "source_photo" => $importer["photo"],
1550                         "verb"         => ACTIVITY_REQ_FRIEND,
1551                         "otype"        => "intro"
1552                 ));
1553
1554                 return true;
1555
1556         }
1557
1558         /**
1559          * @brief Processes the relocation elements
1560          *
1561          * @param object $xpath XPath object
1562          * @param object $relocation relocation elements
1563          * @param array $importer Record of the importer user mixed with contact of the content
1564          */
1565         private static function process_relocation($xpath, $relocation, $importer) {
1566
1567                 logger("Processing relocations");
1568
1569                 $relocate = array();
1570                 $relocate["uid"] = $importer["importer_uid"];
1571                 $relocate["cid"] = $importer["id"];
1572                 $relocate["url"] = $xpath->query("dfrn:url/text()", $relocation)->item(0)->nodeValue;
1573                 $relocate["addr"] = $xpath->query("dfrn:addr/text()", $relocation)->item(0)->nodeValue;
1574                 $relocate["name"] = $xpath->query("dfrn:name/text()", $relocation)->item(0)->nodeValue;
1575                 $relocate["avatar"] = $xpath->query("dfrn:avatar/text()", $relocation)->item(0)->nodeValue;
1576                 $relocate["photo"] = $xpath->query("dfrn:photo/text()", $relocation)->item(0)->nodeValue;
1577                 $relocate["thumb"] = $xpath->query("dfrn:thumb/text()", $relocation)->item(0)->nodeValue;
1578                 $relocate["micro"] = $xpath->query("dfrn:micro/text()", $relocation)->item(0)->nodeValue;
1579                 $relocate["request"] = $xpath->query("dfrn:request/text()", $relocation)->item(0)->nodeValue;
1580                 $relocate["confirm"] = $xpath->query("dfrn:confirm/text()", $relocation)->item(0)->nodeValue;
1581                 $relocate["notify"] = $xpath->query("dfrn:notify/text()", $relocation)->item(0)->nodeValue;
1582                 $relocate["poll"] = $xpath->query("dfrn:poll/text()", $relocation)->item(0)->nodeValue;
1583                 $relocate["sitepubkey"] = $xpath->query("dfrn:sitepubkey/text()", $relocation)->item(0)->nodeValue;
1584
1585                 if (($relocate["avatar"] == "") AND ($relocate["photo"] != ""))
1586                         $relocate["avatar"] = $relocate["photo"];
1587
1588                 if ($relocate["addr"] == "")
1589                         $relocate["addr"] = preg_replace("=(https?://)(.*)/profile/(.*)=ism", "$3@$2", $relocate["url"]);
1590
1591                 // update contact
1592                 $r = q("SELECT `photo`, `url` FROM `contact` WHERE `id` = %d AND `uid` = %d;",
1593                         intval($importer["id"]),
1594                         intval($importer["importer_uid"]));
1595                 if (!$r)
1596                         return false;
1597
1598                 $old = $r[0];
1599
1600                 // Update the gcontact entry
1601                 $relocate["server_url"] = preg_replace("=(https?://)(.*)/profile/(.*)=ism", "$1$2", $relocate["url"]);
1602
1603                 $x = q("UPDATE `gcontact` SET
1604                                         `name` = '%s',
1605                                         `photo` = '%s',
1606                                         `url` = '%s',
1607                                         `nurl` = '%s',
1608                                         `addr` = '%s',
1609                                         `connect` = '%s',
1610                                         `notify` = '%s',
1611                                         `server_url` = '%s'
1612                         WHERE `nurl` = '%s';",
1613                                         dbesc($relocate["name"]),
1614                                         dbesc($relocate["avatar"]),
1615                                         dbesc($relocate["url"]),
1616                                         dbesc(normalise_link($relocate["url"])),
1617                                         dbesc($relocate["addr"]),
1618                                         dbesc($relocate["addr"]),
1619                                         dbesc($relocate["notify"]),
1620                                         dbesc($relocate["server_url"]),
1621                                         dbesc(normalise_link($old["url"])));
1622
1623                 // Update the contact table. We try to find every entry.
1624                 $x = q("UPDATE `contact` SET
1625                                         `name` = '%s',
1626                                         `avatar` = '%s',
1627                                         `url` = '%s',
1628                                         `nurl` = '%s',
1629                                         `addr` = '%s',
1630                                         `request` = '%s',
1631                                         `confirm` = '%s',
1632                                         `notify` = '%s',
1633                                         `poll` = '%s',
1634                                         `site-pubkey` = '%s'
1635                         WHERE (`id` = %d AND `uid` = %d) OR (`nurl` = '%s');",
1636                                         dbesc($relocate["name"]),
1637                                         dbesc($relocate["avatar"]),
1638                                         dbesc($relocate["url"]),
1639                                         dbesc(normalise_link($relocate["url"])),
1640                                         dbesc($relocate["addr"]),
1641                                         dbesc($relocate["request"]),
1642                                         dbesc($relocate["confirm"]),
1643                                         dbesc($relocate["notify"]),
1644                                         dbesc($relocate["poll"]),
1645                                         dbesc($relocate["sitepubkey"]),
1646                                         intval($importer["id"]),
1647                                         intval($importer["importer_uid"]),
1648                                         dbesc(normalise_link($old["url"])));
1649
1650                 update_contact_avatar($relocate["avatar"], $importer["importer_uid"], $importer["id"], true);
1651
1652                 if ($x === false)
1653                         return false;
1654
1655                 // update items
1656                 /// @todo This is an extreme performance killer
1657                 $fields = array(
1658                         'owner-link' => array($old["url"], $relocate["url"]),
1659                         'author-link' => array($old["url"], $relocate["url"]),
1660                         //'owner-avatar' => array($old["photo"], $relocate["photo"]),
1661                         //'author-avatar' => array($old["photo"], $relocate["photo"]),
1662                         );
1663                 foreach ($fields as $n=>$f) {
1664                         $r = q("SELECT `id` FROM `item` WHERE `%s` = '%s' AND `uid` = %d LIMIT 1",
1665                                         $n, dbesc($f[0]),
1666                                         intval($importer["importer_uid"]));
1667
1668                         if ($r) {
1669                                 $x = q("UPDATE `item` SET `%s` = '%s' WHERE `%s` = '%s' AND `uid` = %d",
1670                                                 $n, dbesc($f[1]),
1671                                                 $n, dbesc($f[0]),
1672                                                 intval($importer["importer_uid"]));
1673                                         if ($x === false)
1674                                                 return false;
1675                         }
1676                 }
1677
1678                 /// @TODO
1679                 /// merge with current record, current contents have priority
1680                 /// update record, set url-updated
1681                 /// update profile photos
1682                 /// schedule a scan?
1683                 return true;
1684         }
1685
1686         /**
1687          * @brief Updates an item
1688          *
1689          * @param array $current the current item record
1690          * @param array $item the new item record
1691          * @param array $importer Record of the importer user mixed with contact of the content
1692          * @param int $entrytype Is it a toplevel entry, a comment or a relayed comment?
1693          */
1694         private static function update_content($current, $item, $importer, $entrytype) {
1695                 $changed = false;
1696
1697                 if (edited_timestamp_is_newer($current, $item)) {
1698
1699                         // do not accept (ignore) an earlier edit than one we currently have.
1700                         if(datetime_convert("UTC","UTC",$item["edited"]) < $current["edited"])
1701                                 return(false);
1702
1703                         $r = q("UPDATE `item` SET `title` = '%s', `body` = '%s', `tag` = '%s', `edited` = '%s', `changed` = '%s' WHERE `uri` = '%s' AND `uid` = %d",
1704                                 dbesc($item["title"]),
1705                                 dbesc($item["body"]),
1706                                 dbesc($item["tag"]),
1707                                 dbesc(datetime_convert("UTC","UTC",$item["edited"])),
1708                                 dbesc(datetime_convert()),
1709                                 dbesc($item["uri"]),
1710                                 intval($importer["importer_uid"])
1711                         );
1712                         create_tags_from_itemuri($item["uri"], $importer["importer_uid"]);
1713                         update_thread_uri($item["uri"], $importer["importer_uid"]);
1714
1715                         $changed = true;
1716
1717                         if ($entrytype == DFRN_REPLY_RC)
1718                                 proc_run(PRIORITY_HIGH, "include/notifier.php","comment-import", $current["id"]);
1719                 }
1720
1721                 // update last-child if it changes
1722                 if($item["last-child"] AND ($item["last-child"] != $current["last-child"])) {
1723                         $r = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d",
1724                                 dbesc(datetime_convert()),
1725                                 dbesc($item["parent-uri"]),
1726                                 intval($importer["importer_uid"])
1727                         );
1728                         $r = q("UPDATE `item` SET `last-child` = %d , `changed` = '%s' WHERE `uri` = '%s' AND `uid` = %d",
1729                                 intval($item["last-child"]),
1730                                 dbesc(datetime_convert()),
1731                                 dbesc($item["uri"]),
1732                                 intval($importer["importer_uid"])
1733                         );
1734                 }
1735                 return $changed;
1736         }
1737
1738         /**
1739          * @brief Detects the entry type of the item
1740          *
1741          * @param array $importer Record of the importer user mixed with contact of the content
1742          * @param array $item the new item record
1743          *
1744          * @return int Is it a toplevel entry, a comment or a relayed comment?
1745          */
1746         private static function get_entry_type($importer, $item) {
1747                 if ($item["parent-uri"] != $item["uri"]) {
1748                         $community = false;
1749
1750                         if($importer["page-flags"] == PAGE_COMMUNITY || $importer["page-flags"] == PAGE_PRVGROUP) {
1751                                 $sql_extra = "";
1752                                 $community = true;
1753                                 logger("possible community action");
1754                         } else
1755                                 $sql_extra = " AND `contact`.`self` AND `item`.`wall` ";
1756
1757                         // was the top-level post for this action written by somebody on this site?
1758                         // Specifically, the recipient?
1759
1760                         $is_a_remote_action = false;
1761
1762                         $r = q("SELECT `item`.`parent-uri` FROM `item`
1763                                 WHERE `item`.`uri` = '%s'
1764                                 LIMIT 1",
1765                                 dbesc($item["parent-uri"])
1766                         );
1767                         if (dbm::is_result($r)) {
1768                                 $r = q("SELECT `item`.`forum_mode`, `item`.`wall` FROM `item`
1769                                         INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
1770                                         WHERE `item`.`uri` = '%s' AND (`item`.`parent-uri` = '%s' OR `item`.`thr-parent` = '%s')
1771                                         AND `item`.`uid` = %d
1772                                         $sql_extra
1773                                         LIMIT 1",
1774                                         dbesc($r[0]["parent-uri"]),
1775                                         dbesc($r[0]["parent-uri"]),
1776                                         dbesc($r[0]["parent-uri"]),
1777                                         intval($importer["importer_uid"])
1778                                 );
1779                                 if (dbm::is_result($r))
1780                                         $is_a_remote_action = true;
1781                         }
1782
1783                         // Does this have the characteristics of a community or private group action?
1784                         // If it's an action to a wall post on a community/prvgroup page it's a
1785                         // valid community action. Also forum_mode makes it valid for sure.
1786                         // If neither, it's not.
1787
1788                         if($is_a_remote_action && $community) {
1789                                 if((!$r[0]["forum_mode"]) && (!$r[0]["wall"])) {
1790                                         $is_a_remote_action = false;
1791                                         logger("not a community action");
1792                                 }
1793                         }
1794
1795                         if ($is_a_remote_action)
1796                                 return DFRN_REPLY_RC;
1797                         else
1798                                 return DFRN_REPLY;
1799
1800                 } else
1801                         return DFRN_TOP_LEVEL;
1802
1803         }
1804
1805         /**
1806          * @brief Send a "poke"
1807          *
1808          * @param array $item the new item record
1809          * @param array $importer Record of the importer user mixed with contact of the content
1810          * @param int $posted_id The record number of item record that was just posted
1811          */
1812         private static function do_poke($item, $importer, $posted_id) {
1813                 $verb = urldecode(substr($item["verb"],strpos($item["verb"], "#")+1));
1814                 if(!$verb)
1815                         return;
1816                 $xo = parse_xml_string($item["object"],false);
1817
1818                 if(($xo->type == ACTIVITY_OBJ_PERSON) && ($xo->id)) {
1819
1820                         // somebody was poked/prodded. Was it me?
1821                         foreach($xo->link as $l) {
1822                                 $atts = $l->attributes();
1823                                 switch($atts["rel"]) {
1824                                         case "alternate":
1825                                                 $Blink = $atts["href"];
1826                                                 break;
1827                                         default:
1828                                                 break;
1829                                 }
1830                         }
1831
1832                         if($Blink && link_compare($Blink,App::get_baseurl()."/profile/".$importer["nickname"])) {
1833
1834                                 // send a notification
1835                                 notification(array(
1836                                         "type"         => NOTIFY_POKE,
1837                                         "notify_flags" => $importer["notify-flags"],
1838                                         "language"     => $importer["language"],
1839                                         "to_name"      => $importer["username"],
1840                                         "to_email"     => $importer["email"],
1841                                         "uid"          => $importer["importer_uid"],
1842                                         "item"         => $item,
1843                                         "link"         => App::get_baseurl()."/display/".urlencode(get_item_guid($posted_id)),
1844                                         "source_name"  => stripslashes($item["author-name"]),
1845                                         "source_link"  => $item["author-link"],
1846                                         "source_photo" => ((link_compare($item["author-link"],$importer["url"]))
1847                                                 ? $importer["thumb"] : $item["author-avatar"]),
1848                                         "verb"         => $item["verb"],
1849                                         "otype"        => "person",
1850                                         "activity"     => $verb,
1851                                         "parent"       => $item["parent"]
1852                                 ));
1853                         }
1854                 }
1855         }
1856
1857         /**
1858          * @brief Processes several actions, depending on the verb
1859          *
1860          * @param int $entrytype Is it a toplevel entry, a comment or a relayed comment?
1861          * @param array $importer Record of the importer user mixed with contact of the content
1862          * @param array $item the new item record
1863          * @param bool $is_like Is the verb a "like"?
1864          *
1865          * @return bool Should the processing of the entries be continued?
1866          */
1867         private static function process_verbs($entrytype, $importer, &$item, &$is_like) {
1868
1869                 logger("Process verb ".$item["verb"]." and object-type ".$item["object-type"]." for entrytype ".$entrytype, LOGGER_DEBUG);
1870
1871                 if (($entrytype == DFRN_TOP_LEVEL)) {
1872                         // The filling of the the "contact" variable is done for legcy reasons
1873                         // The functions below are partly used by ostatus.php as well - where we have this variable
1874                         $r = q("SELECT * FROM `contact` WHERE `id` = %d", intval($importer["id"]));
1875                         $contact = $r[0];
1876                         $nickname = $contact["nick"];
1877
1878                         // Big question: Do we need these functions? They were part of the "consume_feed" function.
1879                         // This function once was responsible for DFRN and OStatus.
1880                         if(activity_match($item["verb"],ACTIVITY_FOLLOW)) {
1881                                 logger("New follower");
1882                                 new_follower($importer, $contact, $item, $nickname);
1883                                 return false;
1884                         }
1885                         if(activity_match($item["verb"],ACTIVITY_UNFOLLOW))  {
1886                                 logger("Lost follower");
1887                                 lose_follower($importer, $contact, $item);
1888                                 return false;
1889                         }
1890                         if(activity_match($item["verb"],ACTIVITY_REQ_FRIEND)) {
1891                                 logger("New friend request");
1892                                 new_follower($importer, $contact, $item, $nickname, true);
1893                                 return false;
1894                         }
1895                         if(activity_match($item["verb"],ACTIVITY_UNFRIEND))  {
1896                                 logger("Lost sharer");
1897                                 lose_sharer($importer, $contact, $item);
1898                                 return false;
1899                         }
1900                 } else {
1901                         if(($item["verb"] == ACTIVITY_LIKE)
1902                                 || ($item["verb"] == ACTIVITY_DISLIKE)
1903                                 || ($item["verb"] == ACTIVITY_ATTEND)
1904                                 || ($item["verb"] == ACTIVITY_ATTENDNO)
1905                                 || ($item["verb"] == ACTIVITY_ATTENDMAYBE)) {
1906                                 $is_like = true;
1907                                 $item["type"] = "activity";
1908                                 $item["gravity"] = GRAVITY_LIKE;
1909                                 // only one like or dislike per person
1910                                 // splitted into two queries for performance issues
1911                                 $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",
1912                                         intval($item["uid"]),
1913                                         dbesc($item["author-link"]),
1914                                         dbesc($item["verb"]),
1915                                         dbesc($item["parent-uri"])
1916                                 );
1917                                 if (dbm::is_result($r))
1918                                         return false;
1919
1920                                 $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",
1921                                         intval($item["uid"]),
1922                                         dbesc($item["author-link"]),
1923                                         dbesc($item["verb"]),
1924                                         dbesc($item["parent-uri"])
1925                                 );
1926                                 if (dbm::is_result($r))
1927                                         return false;
1928                         } else
1929                                 $is_like = false;
1930
1931                         if(($item["verb"] == ACTIVITY_TAG) && ($item["object-type"] == ACTIVITY_OBJ_TAGTERM)) {
1932
1933                                 $xo = parse_xml_string($item["object"],false);
1934                                 $xt = parse_xml_string($item["target"],false);
1935
1936                                 if($xt->type == ACTIVITY_OBJ_NOTE) {
1937                                         $r = q("SELECT `id`, `tag` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1938                                                 dbesc($xt->id),
1939                                                 intval($importer["importer_uid"])
1940                                         );
1941
1942                                         if (!dbm::is_result($r))
1943                                                 return false;
1944
1945                                         // extract tag, if not duplicate, add to parent item
1946                                         if($xo->content) {
1947                                                 if(!(stristr($r[0]["tag"],trim($xo->content)))) {
1948                                                         q("UPDATE `item` SET `tag` = '%s' WHERE `id` = %d",
1949                                                                 dbesc($r[0]["tag"] . (strlen($r[0]["tag"]) ? ',' : '') . '#[url=' . $xo->id . ']'. $xo->content . '[/url]'),
1950                                                                 intval($r[0]["id"])
1951                                                         );
1952                                                         create_tags_from_item($r[0]["id"]);
1953                                                 }
1954                                         }
1955                                 }
1956                         }
1957                 }
1958                 return true;
1959         }
1960
1961         /**
1962          * @brief Processes the link elements
1963          *
1964          * @param object $links link elements
1965          * @param array $item the item record
1966          */
1967         private static function parse_links($links, &$item) {
1968                 $rel = "";
1969                 $href = "";
1970                 $type = "";
1971                 $length = "0";
1972                 $title = "";
1973                 foreach ($links AS $link) {
1974                         foreach($link->attributes AS $attributes) {
1975                                 if ($attributes->name == "href")
1976                                         $href = $attributes->textContent;
1977                                 if ($attributes->name == "rel")
1978                                         $rel = $attributes->textContent;
1979                                 if ($attributes->name == "type")
1980                                         $type = $attributes->textContent;
1981                                 if ($attributes->name == "length")
1982                                         $length = $attributes->textContent;
1983                                 if ($attributes->name == "title")
1984                                         $title = $attributes->textContent;
1985                         }
1986                         if (($rel != "") AND ($href != ""))
1987                                 switch($rel) {
1988                                         case "alternate":
1989                                                 $item["plink"] = $href;
1990                                                 break;
1991                                         case "enclosure":
1992                                                 $enclosure = $href;
1993                                                 if(strlen($item["attach"]))
1994                                                         $item["attach"] .= ",";
1995
1996                                                 $item["attach"] .= '[attach]href="'.$href.'" length="'.$length.'" type="'.$type.'" title="'.$title.'"[/attach]';
1997                                                 break;
1998                                 }
1999                 }
2000         }
2001
2002         /**
2003          * @brief Processes the entry elements which contain the items and comments
2004          *
2005          * @param array $header Array of the header elements that always stay the same
2006          * @param object $xpath XPath object
2007          * @param object $entry entry elements
2008          * @param array $importer Record of the importer user mixed with contact of the content
2009          */
2010         private static function process_entry($header, $xpath, $entry, $importer) {
2011
2012                 logger("Processing entries");
2013
2014                 $item = $header;
2015
2016                 // Get the uri
2017                 $item["uri"] = $xpath->query("atom:id/text()", $entry)->item(0)->nodeValue;
2018
2019                 $item["edited"] = $xpath->query("atom:updated/text()", $entry)->item(0)->nodeValue;
2020
2021                 $current = q("SELECT `id`, `uid`, `last-child`, `edited`, `body` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2022                         dbesc($item["uri"]),
2023                         intval($importer["importer_uid"])
2024                 );
2025
2026                 // Is there an existing item?
2027                 if (dbm::is_result($current) AND edited_timestamp_is_newer($current[0], $item) AND
2028                         (datetime_convert("UTC","UTC",$item["edited"]) < $current[0]["edited"])) {
2029                         logger("Item ".$item["uri"]." already existed.", LOGGER_DEBUG);
2030                         return;
2031                 }
2032
2033                 // Fetch the owner
2034                 $owner = self::fetchauthor($xpath, $entry, $importer, "dfrn:owner", true);
2035
2036                 $item["owner-name"] = $owner["name"];
2037                 $item["owner-link"] = $owner["link"];
2038                 $item["owner-avatar"] = $owner["avatar"];
2039
2040                 // fetch the author
2041                 $author = self::fetchauthor($xpath, $entry, $importer, "atom:author", true);
2042
2043                 $item["author-name"] = $author["name"];
2044                 $item["author-link"] = $author["link"];
2045                 $item["author-avatar"] = $author["avatar"];
2046
2047                 $item["title"] = $xpath->query("atom:title/text()", $entry)->item(0)->nodeValue;
2048
2049                 $item["created"] = $xpath->query("atom:published/text()", $entry)->item(0)->nodeValue;
2050
2051                 $item["body"] = $xpath->query("dfrn:env/text()", $entry)->item(0)->nodeValue;
2052                 $item["body"] = str_replace(array(' ',"\t","\r","\n"), array('','','',''),$item["body"]);
2053                 // make sure nobody is trying to sneak some html tags by us
2054                 $item["body"] = notags(base64url_decode($item["body"]));
2055
2056                 $item["body"] = limit_body_size($item["body"]);
2057
2058                 /// @todo Do we really need this check for HTML elements? (It was copied from the old function)
2059                 if((strpos($item['body'],'<') !== false) && (strpos($item['body'],'>') !== false)) {
2060
2061                         $item['body'] = reltoabs($item['body'],$base_url);
2062
2063                         $item['body'] = html2bb_video($item['body']);
2064
2065                         $item['body'] = oembed_html2bbcode($item['body']);
2066
2067                         $config = HTMLPurifier_Config::createDefault();
2068                         $config->set('Cache.DefinitionImpl', null);
2069
2070                         // we shouldn't need a whitelist, because the bbcode converter
2071                         // will strip out any unsupported tags.
2072
2073                         $purifier = new HTMLPurifier($config);
2074                         $item['body'] = $purifier->purify($item['body']);
2075
2076                         $item['body'] = @html2bbcode($item['body']);
2077                 }
2078
2079                 /// @todo We should check for a repeated post and if we know the repeated author.
2080
2081                 // We don't need the content element since "dfrn:env" is always present
2082                 //$item["body"] = $xpath->query("atom:content/text()", $entry)->item(0)->nodeValue;
2083
2084                 $item["last-child"] = $xpath->query("dfrn:comment-allow/text()", $entry)->item(0)->nodeValue;
2085                 $item["location"] = $xpath->query("dfrn:location/text()", $entry)->item(0)->nodeValue;
2086
2087                 $georsspoint = $xpath->query("georss:point", $entry);
2088                 if ($georsspoint)
2089                         $item["coord"] = $georsspoint->item(0)->nodeValue;
2090
2091                 $item["private"] = $xpath->query("dfrn:private/text()", $entry)->item(0)->nodeValue;
2092
2093                 $item["extid"] = $xpath->query("dfrn:extid/text()", $entry)->item(0)->nodeValue;
2094
2095                 if ($xpath->query("dfrn:bookmark/text()", $entry)->item(0)->nodeValue == "true")
2096                         $item["bookmark"] = true;
2097
2098                 $notice_info = $xpath->query("statusnet:notice_info", $entry);
2099                 if ($notice_info AND ($notice_info->length > 0)) {
2100                         foreach($notice_info->item(0)->attributes AS $attributes) {
2101                                 if ($attributes->name == "source")
2102                                         $item["app"] = strip_tags($attributes->textContent);
2103                         }
2104                 }
2105
2106                 $item["guid"] = $xpath->query("dfrn:diaspora_guid/text()", $entry)->item(0)->nodeValue;
2107
2108                 // We store the data from "dfrn:diaspora_signature" in a different table, this is done in "item_store"
2109                 $dsprsig = unxmlify($xpath->query("dfrn:diaspora_signature/text()", $entry)->item(0)->nodeValue);
2110                 if ($dsprsig != "")
2111                         $item["dsprsig"] = $dsprsig;
2112
2113                 $item["verb"] = $xpath->query("activity:verb/text()", $entry)->item(0)->nodeValue;
2114
2115                 if ($xpath->query("activity:object-type/text()", $entry)->item(0)->nodeValue != "")
2116                         $item["object-type"] = $xpath->query("activity:object-type/text()", $entry)->item(0)->nodeValue;
2117
2118                 $object = $xpath->query("activity:object", $entry)->item(0);
2119                 $item["object"] = self::transform_activity($xpath, $object, "object");
2120
2121                 if (trim($item["object"]) != "") {
2122                         $r = parse_xml_string($item["object"], false);
2123                         if (isset($r->type))
2124                                 $item["object-type"] = $r->type;
2125                 }
2126
2127                 $target = $xpath->query("activity:target", $entry)->item(0);
2128                 $item["target"] = self::transform_activity($xpath, $target, "target");
2129
2130                 $categories = $xpath->query("atom:category", $entry);
2131                 if ($categories) {
2132                         foreach ($categories AS $category) {
2133                                 $term = "";
2134                                 $scheme = "";
2135                                 foreach($category->attributes AS $attributes) {
2136                                         if ($attributes->name == "term")
2137                                                 $term = $attributes->textContent;
2138
2139                                         if ($attributes->name == "scheme")
2140                                                 $scheme = $attributes->textContent;
2141                                 }
2142
2143                                 if (($term != "") AND ($scheme != "")) {
2144                                         $parts = explode(":", $scheme);
2145                                         if ((count($parts) >= 4) AND (array_shift($parts) == "X-DFRN")) {
2146                                                 $termhash = array_shift($parts);
2147                                                 $termurl = implode(":", $parts);
2148
2149                                                 if(strlen($item["tag"]))
2150                                                         $item["tag"] .= ",";
2151
2152                                                 $item["tag"] .= $termhash."[url=".$termurl."]".$term."[/url]";
2153                                         }
2154                                 }
2155                         }
2156                 }
2157
2158                 $enclosure = "";
2159
2160                 $links = $xpath->query("atom:link", $entry);
2161                 if ($links)
2162                         self::parse_links($links, $item);
2163
2164                 // Is it a reply or a top level posting?
2165                 $item["parent-uri"] = $item["uri"];
2166
2167                 $inreplyto = $xpath->query("thr:in-reply-to", $entry);
2168                 if (is_object($inreplyto->item(0)))
2169                         foreach($inreplyto->item(0)->attributes AS $attributes)
2170                                 if ($attributes->name == "ref")
2171                                         $item["parent-uri"] = $attributes->textContent;
2172
2173                 // Get the type of the item (Top level post, reply or remote reply)
2174                 $entrytype = self::get_entry_type($importer, $item);
2175
2176                 // Now assign the rest of the values that depend on the type of the message
2177                 if (in_array($entrytype, array(DFRN_REPLY, DFRN_REPLY_RC))) {
2178                         if (!isset($item["object-type"]))
2179                                 $item["object-type"] = ACTIVITY_OBJ_COMMENT;
2180
2181                         if ($item["contact-id"] != $owner["contact-id"])
2182                                 $item["contact-id"] = $owner["contact-id"];
2183
2184                         if (($item["network"] != $owner["network"]) AND ($owner["network"] != ""))
2185                                 $item["network"] = $owner["network"];
2186
2187                         if ($item["contact-id"] != $author["contact-id"])
2188                                 $item["contact-id"] = $author["contact-id"];
2189
2190                         if (($item["network"] != $author["network"]) AND ($author["network"] != ""))
2191                                 $item["network"] = $author["network"];
2192
2193                         // This code was taken from the old DFRN code
2194                         // When activated, forums don't work.
2195                         // And: Why should we disallow commenting by followers?
2196                         // the behaviour is now similar to the Diaspora part.
2197                         //if($importer["rel"] == CONTACT_IS_FOLLOWER) {
2198                         //      logger("Contact ".$importer["id"]." is only follower. Quitting", LOGGER_DEBUG);
2199                         //      return;
2200                         //}
2201                 }
2202
2203                 if ($entrytype == DFRN_REPLY_RC) {
2204                         $item["type"] = "remote-comment";
2205                         $item["wall"] = 1;
2206                 } elseif ($entrytype == DFRN_TOP_LEVEL) {
2207                         if (!isset($item["object-type"]))
2208                                 $item["object-type"] = ACTIVITY_OBJ_NOTE;
2209
2210                         // Is it an event?
2211                         if ($item["object-type"] == ACTIVITY_OBJ_EVENT) {
2212                                 logger("Item ".$item["uri"]." seems to contain an event.", LOGGER_DEBUG);
2213                                 $ev = bbtoevent($item["body"]);
2214                                 if((x($ev, "desc") || x($ev, "summary")) && x($ev, "start")) {
2215                                         logger("Event in item ".$item["uri"]." was found.", LOGGER_DEBUG);
2216                                         $ev["cid"] = $importer["id"];
2217                                         $ev["uid"] = $importer["uid"];
2218                                         $ev["uri"] = $item["uri"];
2219                                         $ev["edited"] = $item["edited"];
2220                                         $ev['private'] = $item['private'];
2221                                         $ev["guid"] = $item["guid"];
2222
2223                                         $r = q("SELECT `id` FROM `event` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2224                                                 dbesc($item["uri"]),
2225                                                 intval($importer["uid"])
2226                                         );
2227                                         if (dbm::is_result($r))
2228                                                 $ev["id"] = $r[0]["id"];
2229
2230                                         $event_id = event_store($ev);
2231                                         logger("Event ".$event_id." was stored", LOGGER_DEBUG);
2232                                         return;
2233                                 }
2234                         }
2235                 }
2236
2237                 if (!self::process_verbs($entrytype, $importer, $item, $is_like)) {
2238                         logger("Exiting because 'process_verbs' told us so", LOGGER_DEBUG);
2239                         return;
2240                 }
2241
2242                 // Update content if 'updated' changes
2243                 if (dbm::is_result($current)) {
2244                         if (self::update_content($r[0], $item, $importer, $entrytype))
2245                                 logger("Item ".$item["uri"]." was updated.", LOGGER_DEBUG);
2246                         else
2247                                 logger("Item ".$item["uri"]." already existed.", LOGGER_DEBUG);
2248                         return;
2249                 }
2250
2251                 if (in_array($entrytype, array(DFRN_REPLY, DFRN_REPLY_RC))) {
2252                         $posted_id = item_store($item);
2253                         $parent = 0;
2254
2255                         if($posted_id) {
2256
2257                                 logger("Reply from contact ".$item["contact-id"]." was stored with id ".$posted_id, LOGGER_DEBUG);
2258
2259                                 $item["id"] = $posted_id;
2260
2261                                 $r = q("SELECT `parent`, `parent-uri` FROM `item` WHERE `id` = %d AND `uid` = %d LIMIT 1",
2262                                         intval($posted_id),
2263                                         intval($importer["importer_uid"])
2264                                 );
2265                                 if (dbm::is_result($r)) {
2266                                         $parent = $r[0]["parent"];
2267                                         $parent_uri = $r[0]["parent-uri"];
2268                                 }
2269
2270                                 if(!$is_like) {
2271                                         $r1 = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `uid` = %d AND `parent` = %d",
2272                                                 dbesc(datetime_convert()),
2273                                                 intval($importer["importer_uid"]),
2274                                                 intval($r[0]["parent"])
2275                                         );
2276
2277                                         $r2 = q("UPDATE `item` SET `last-child` = 1, `changed` = '%s' WHERE `uid` = %d AND `id` = %d",
2278                                                 dbesc(datetime_convert()),
2279                                                 intval($importer["importer_uid"]),
2280                                                 intval($posted_id)
2281                                         );
2282                                 }
2283
2284                                 if($posted_id AND $parent AND ($entrytype == DFRN_REPLY_RC)) {
2285                                         logger("Notifying followers about comment ".$posted_id, LOGGER_DEBUG);
2286                                         proc_run(PRIORITY_HIGH, "include/notifier.php", "comment-import", $posted_id);
2287                                 }
2288
2289                                 return true;
2290                         }
2291                 } else { // $entrytype == DFRN_TOP_LEVEL
2292                         if(!link_compare($item["owner-link"],$importer["url"])) {
2293                                 // The item owner info is not our contact. It's OK and is to be expected if this is a tgroup delivery,
2294                                 // but otherwise there's a possible data mixup on the sender's system.
2295                                 // the tgroup delivery code called from item_store will correct it if it's a forum,
2296                                 // but we're going to unconditionally correct it here so that the post will always be owned by our contact.
2297                                 logger('Correcting item owner.', LOGGER_DEBUG);
2298                                 $item["owner-name"]   = $importer["senderName"];
2299                                 $item["owner-link"]   = $importer["url"];
2300                                 $item["owner-avatar"] = $importer["thumb"];
2301                         }
2302
2303                         if(($importer["rel"] == CONTACT_IS_FOLLOWER) && (!tgroup_check($importer["importer_uid"], $item))) {
2304                                 logger("Contact ".$importer["id"]." is only follower and tgroup check was negative.", LOGGER_DEBUG);
2305                                 return;
2306                         }
2307
2308                         // This is my contact on another system, but it's really me.
2309                         // Turn this into a wall post.
2310                         $notify = item_is_remote_self($importer, $item);
2311
2312                         $posted_id = item_store($item, false, $notify);
2313
2314                         logger("Item was stored with id ".$posted_id, LOGGER_DEBUG);
2315
2316                         if(stristr($item["verb"],ACTIVITY_POKE))
2317                                 self::do_poke($item, $importer, $posted_id);
2318                 }
2319         }
2320
2321         /**
2322          * @brief Deletes items
2323          *
2324          * @param object $xpath XPath object
2325          * @param object $deletion deletion elements
2326          * @param array $importer Record of the importer user mixed with contact of the content
2327          */
2328         private static function process_deletion($xpath, $deletion, $importer) {
2329
2330                 logger("Processing deletions");
2331
2332                 foreach($deletion->attributes AS $attributes) {
2333                         if ($attributes->name == "ref")
2334                                 $uri = $attributes->textContent;
2335                         if ($attributes->name == "when")
2336                                 $when = $attributes->textContent;
2337                 }
2338                 if ($when)
2339                         $when = datetime_convert("UTC", "UTC", $when, "Y-m-d H:i:s");
2340                 else
2341                         $when = datetime_convert("UTC", "UTC", "now", "Y-m-d H:i:s");
2342
2343                 if (!$uri OR !$importer["id"])
2344                         return false;
2345
2346                 /// @todo Only select the used fields
2347                 $r = q("SELECT `item`.*, `contact`.`self` FROM `item` INNER JOIN `contact` on `item`.`contact-id` = `contact`.`id`
2348                                 WHERE `uri` = '%s' AND `item`.`uid` = %d AND `contact-id` = %d AND NOT `item`.`file` LIKE '%%[%%' LIMIT 1",
2349                                 dbesc($uri),
2350                                 intval($importer["uid"]),
2351                                 intval($importer["id"])
2352                         );
2353                 if (!dbm::is_result($r)) {
2354                         logger("Item with uri ".$uri." from contact ".$importer["id"]." for user ".$importer["uid"]." wasn't found.", LOGGER_DEBUG);
2355                         return;
2356                 } else {
2357
2358                         $item = $r[0];
2359
2360                         $entrytype = self::get_entry_type($importer, $item);
2361
2362                         if(!$item["deleted"])
2363                                 logger('deleting item '.$item["id"].' uri='.$uri, LOGGER_DEBUG);
2364                         else
2365                                 return;
2366
2367                         if($item["object-type"] == ACTIVITY_OBJ_EVENT) {
2368                                 logger("Deleting event ".$item["event-id"], LOGGER_DEBUG);
2369                                 event_delete($item["event-id"]);
2370                         }
2371
2372                         if(($item["verb"] == ACTIVITY_TAG) && ($item["object-type"] == ACTIVITY_OBJ_TAGTERM)) {
2373
2374                                 $xo = parse_xml_string($item["object"],false);
2375                                 $xt = parse_xml_string($item["target"],false);
2376
2377                                 if($xt->type == ACTIVITY_OBJ_NOTE) {
2378                                         $i = q("SELECT `id`, `contact-id`, `tag` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2379                                                 dbesc($xt->id),
2380                                                 intval($importer["importer_uid"])
2381                                         );
2382                                         if (dbm::is_result($i)) {
2383
2384                                                 // For tags, the owner cannot remove the tag on the author's copy of the post.
2385
2386                                                 $owner_remove = (($item["contact-id"] == $i[0]["contact-id"]) ? true: false);
2387                                                 $author_remove = (($item["origin"] && $item["self"]) ? true : false);
2388                                                 $author_copy = (($item["origin"]) ? true : false);
2389
2390                                                 if($owner_remove && $author_copy)
2391                                                         return;
2392                                                 if($author_remove || $owner_remove) {
2393                                                         $tags = explode(',',$i[0]["tag"]);
2394                                                         $newtags = array();
2395                                                         if(count($tags)) {
2396                                                                 foreach($tags as $tag)
2397                                                                         if(trim($tag) !== trim($xo->body))
2398                                                                                 $newtags[] = trim($tag);
2399                                                         }
2400                                                         q("UPDATE `item` SET `tag` = '%s' WHERE `id` = %d",
2401                                                                 dbesc(implode(',',$newtags)),
2402                                                                 intval($i[0]["id"])
2403                                                         );
2404                                                         create_tags_from_item($i[0]["id"]);
2405                                                 }
2406                                         }
2407                                 }
2408                         }
2409
2410                         if($entrytype == DFRN_TOP_LEVEL) {
2411                                 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s',
2412                                                 `body` = '', `title` = ''
2413                                         WHERE `parent-uri` = '%s' AND `uid` = %d",
2414                                                 dbesc($when),
2415                                                 dbesc(datetime_convert()),
2416                                                 dbesc($uri),
2417                                                 intval($importer["uid"])
2418                                         );
2419                                 create_tags_from_itemuri($uri, $importer["uid"]);
2420                                 create_files_from_itemuri($uri, $importer["uid"]);
2421                                 update_thread_uri($uri, $importer["uid"]);
2422                         } else {
2423                                 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s',
2424                                                 `body` = '', `title` = ''
2425                                         WHERE `uri` = '%s' AND `uid` = %d",
2426                                                 dbesc($when),
2427                                                 dbesc(datetime_convert()),
2428                                                 dbesc($uri),
2429                                                 intval($importer["uid"])
2430                                         );
2431                                 create_tags_from_itemuri($uri, $importer["uid"]);
2432                                 create_files_from_itemuri($uri, $importer["uid"]);
2433                                 update_thread_uri($uri, $importer["importer_uid"]);
2434                                 if($item["last-child"]) {
2435                                         // ensure that last-child is set in case the comment that had it just got wiped.
2436                                         q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d ",
2437                                                 dbesc(datetime_convert()),
2438                                                 dbesc($item["parent-uri"]),
2439                                                 intval($item["uid"])
2440                                         );
2441                                         // who is the last child now?
2442                                         $r = q("SELECT `id` FROM `item` WHERE `parent-uri` = '%s' AND `type` != 'activity' AND `deleted` = 0 AND `moderated` = 0 AND `uid` = %d
2443                                                 ORDER BY `created` DESC LIMIT 1",
2444                                                         dbesc($item["parent-uri"]),
2445                                                         intval($importer["uid"])
2446                                         );
2447                                         if (dbm::is_result($r)) {
2448                                                 q("UPDATE `item` SET `last-child` = 1 WHERE `id` = %d",
2449                                                         intval($r[0]["id"])
2450                                                 );
2451                                         }
2452                                 }
2453                                 // if this is a relayed delete, propagate it to other recipients
2454
2455                                 if($entrytype == DFRN_REPLY_RC) {
2456                                         logger("Notifying followers about deletion of post ".$item["id"], LOGGER_DEBUG);
2457                                         proc_run(PRIORITY_HIGH, "include/notifier.php","drop", $item["id"]);
2458                                 }
2459                         }
2460                 }
2461         }
2462
2463         /**
2464          * @brief Imports a DFRN message
2465          *
2466          * @param text $xml The DFRN message
2467          * @param array $importer Record of the importer user mixed with contact of the content
2468          * @param bool $sort_by_date Is used when feeds are polled
2469          */
2470         public static function import($xml,$importer, $sort_by_date = false) {
2471
2472                 if ($xml == "")
2473                         return;
2474
2475                 if($importer["readonly"]) {
2476                         // We aren't receiving stuff from this person. But we will quietly ignore them
2477                         // rather than a blatant "go away" message.
2478                         logger('ignoring contact '.$importer["id"]);
2479                         return;
2480                 }
2481
2482                 $doc = new DOMDocument();
2483                 @$doc->loadXML($xml);
2484
2485                 $xpath = new DomXPath($doc);
2486                 $xpath->registerNamespace("atom", NAMESPACE_ATOM1);
2487                 $xpath->registerNamespace("thr", NAMESPACE_THREAD);
2488                 $xpath->registerNamespace("at", NAMESPACE_TOMB);
2489                 $xpath->registerNamespace("media", NAMESPACE_MEDIA);
2490                 $xpath->registerNamespace("dfrn", NAMESPACE_DFRN);
2491                 $xpath->registerNamespace("activity", NAMESPACE_ACTIVITY);
2492                 $xpath->registerNamespace("georss", NAMESPACE_GEORSS);
2493                 $xpath->registerNamespace("poco", NAMESPACE_POCO);
2494                 $xpath->registerNamespace("ostatus", NAMESPACE_OSTATUS);
2495                 $xpath->registerNamespace("statusnet", NAMESPACE_STATUSNET);
2496
2497                 $header = array();
2498                 $header["uid"] = $importer["uid"];
2499                 $header["network"] = NETWORK_DFRN;
2500                 $header["type"] = "remote";
2501                 $header["wall"] = 0;
2502                 $header["origin"] = 0;
2503                 $header["contact-id"] = $importer["id"];
2504
2505                 // Update the contact table if the data has changed
2506
2507                 // The "atom:author" is only present in feeds
2508                 if ($xpath->query("/atom:feed/atom:author")->length > 0)
2509                         self::fetchauthor($xpath, $doc->firstChild, $importer, "atom:author", false, $xml);
2510
2511                 // Only the "dfrn:owner" in the head section contains all data
2512                 if ($xpath->query("/atom:feed/dfrn:owner")->length > 0)
2513                         self::fetchauthor($xpath, $doc->firstChild, $importer, "dfrn:owner", false, $xml);
2514
2515                 logger("Import DFRN message for user ".$importer["uid"]." from contact ".$importer["id"], LOGGER_DEBUG);
2516
2517                 // The account type is new since 3.5.1
2518                 if ($xpath->query("/atom:feed/dfrn:account_type")->length > 0) {
2519                         $accounttype = intval($xpath->evaluate("/atom:feed/dfrn:account_type/text()", $context)->item(0)->nodeValue);
2520
2521                         if ($accounttype != $importer["contact-type"])
2522                                 q("UPDATE `contact` SET `contact-type` = %d WHERE `id` = %d",
2523                                         intval($accounttype),
2524                                         intval($importer["id"])
2525                                 );
2526                 }
2527
2528                 // is it a public forum? Private forums aren't supported with this method
2529                 // This is deprecated since 3.5.1
2530                 $forum = intval($xpath->evaluate("/atom:feed/dfrn:community/text()", $context)->item(0)->nodeValue);
2531
2532                 if ($forum != $importer["forum"])
2533                         q("UPDATE `contact` SET `forum` = %d WHERE `forum` != %d AND `id` = %d",
2534                                 intval($forum), intval($forum),
2535                                 intval($importer["id"])
2536                         );
2537
2538                 $mails = $xpath->query("/atom:feed/dfrn:mail");
2539                 foreach ($mails AS $mail)
2540                         self::process_mail($xpath, $mail, $importer);
2541
2542                 $suggestions = $xpath->query("/atom:feed/dfrn:suggest");
2543                 foreach ($suggestions AS $suggestion)
2544                         self::process_suggestion($xpath, $suggestion, $importer);
2545
2546                 $relocations = $xpath->query("/atom:feed/dfrn:relocate");
2547                 foreach ($relocations AS $relocation)
2548                         self::process_relocation($xpath, $relocation, $importer);
2549
2550                 $deletions = $xpath->query("/atom:feed/at:deleted-entry");
2551                 foreach ($deletions AS $deletion)
2552                         self::process_deletion($xpath, $deletion, $importer);
2553
2554                 if (!$sort_by_date) {
2555                         $entries = $xpath->query("/atom:feed/atom:entry");
2556                         foreach ($entries AS $entry)
2557                                 self::process_entry($header, $xpath, $entry, $importer);
2558                 } else {
2559                         $newentries = array();
2560                         $entries = $xpath->query("/atom:feed/atom:entry");
2561                         foreach ($entries AS $entry) {
2562                                 $created = $xpath->query("atom:published/text()", $entry)->item(0)->nodeValue;
2563                                 $newentries[strtotime($created)] = $entry;
2564                         }
2565
2566                         // Now sort after the publishing date
2567                         ksort($newentries);
2568
2569                         foreach ($newentries AS $entry)
2570                                 self::process_entry($header, $xpath, $entry, $importer);
2571                 }
2572                 logger("Import done for user ".$importer["uid"]." from contact ".$importer["id"], LOGGER_DEBUG);
2573         }
2574 }
2575 ?>