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