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