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