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