]> git.mxchange.org Git - friendica.git/blob - include/dfrn.php
Poco fields now moved to the header, function to create formatted location string
[friendica.git] / include / dfrn.php
1 <?php
2 require_once('include/items.php');
3 require_once('include/Contact.php');
4 require_once('include/ostatus.php');
5
6 /**
7  * @brief Generates the atom entries for delivery.php
8  *
9  * This function is used whenever content is transmitted via DFRN.
10  *
11  * @param array $items Item elements
12  * @param array $owner Owner record
13  *
14  * @return string DFRN entries
15  */
16 function dfrn_entries($items,$owner) {
17
18         $doc = new DOMDocument('1.0', 'utf-8');
19         $doc->formatOutput = true;
20
21         $root = dfrn_add_header($doc, $owner, "dfrn:owner", "", false);
22
23         if(! count($items))
24                 return trim($doc->saveXML());
25
26         foreach($items as $item) {
27                 $entry = dfrn_entry($doc, "text", $item, $owner, $item["entry:comment-allow"], $item["entry:cid"]);
28                 $root->appendChild($entry);
29         }
30
31         return(trim($doc->saveXML()));
32 }
33
34 /**
35  * @brief Generate an atom feed for the given user
36  *
37  * This function is called when another server is pulling data from the user feed.
38  *
39  * @param App $a
40  * @param string $dfrn_id
41  * @param string $owner_nick Owner nick name
42  * @param string $last_update Date of the last update
43  * @param int $direction
44  *
45  * @return string DFRN feed entries
46  */
47 function dfrn_feed(&$a, $dfrn_id, $owner_nick, $last_update, $direction = 0) {
48
49         $sitefeed    = ((strlen($owner_nick)) ? false : true); // not yet implemented, need to rewrite huge chunks of following logic
50         $public_feed = (($dfrn_id) ? false : true);
51         $starred     = false;   // not yet implemented, possible security issues
52         $converse    = false;
53
54         if($public_feed && $a->argc > 2) {
55                 for($x = 2; $x < $a->argc; $x++) {
56                         if($a->argv[$x] == 'converse')
57                                 $converse = true;
58                         if($a->argv[$x] == 'starred')
59                                 $starred = true;
60                         if($a->argv[$x] === 'category' && $a->argc > ($x + 1) && strlen($a->argv[$x+1]))
61                                 $category = $a->argv[$x+1];
62                 }
63         }
64
65
66
67         // default permissions - anonymous user
68
69         $sql_extra = " AND `item`.`allow_cid` = '' AND `item`.`allow_gid` = '' AND `item`.`deny_cid`  = '' AND `item`.`deny_gid`  = '' ";
70
71         $r = q("SELECT `contact`.*, `user`.`uid` AS `user_uid`, `user`.`nickname`, `user`.`timezone`, `user`.`page-flags`
72                 FROM `contact` INNER JOIN `user` ON `user`.`uid` = `contact`.`uid`
73                 WHERE `contact`.`self` = 1 AND `user`.`nickname` = '%s' LIMIT 1",
74                 dbesc($owner_nick)
75         );
76
77         if(! count($r))
78                 killme();
79
80         $owner = $r[0];
81         $owner_id = $owner['user_uid'];
82         $owner_nick = $owner['nickname'];
83
84         $sql_post_table = "";
85         $visibility = "";
86
87         if(! $public_feed) {
88
89                 $sql_extra = '';
90                 switch($direction) {
91                         case (-1):
92                                 $sql_extra = sprintf(" AND `issued-id` = '%s' ", dbesc($dfrn_id));
93                                 $my_id = $dfrn_id;
94                                 break;
95                         case 0:
96                                 $sql_extra = sprintf(" AND `issued-id` = '%s' AND `duplex` = 1 ", dbesc($dfrn_id));
97                                 $my_id = '1:' . $dfrn_id;
98                                 break;
99                         case 1:
100                                 $sql_extra = sprintf(" AND `dfrn-id` = '%s' AND `duplex` = 1 ", dbesc($dfrn_id));
101                                 $my_id = '0:' . $dfrn_id;
102                                 break;
103                         default:
104                                 return false;
105                                 break; // NOTREACHED
106                 }
107
108                 $r = q("SELECT * FROM `contact` WHERE `blocked` = 0 AND `pending` = 0 AND `contact`.`uid` = %d $sql_extra LIMIT 1",
109                         intval($owner_id)
110                 );
111
112                 if(! count($r))
113                         killme();
114
115                 $contact = $r[0];
116                 require_once('include/security.php');
117                 $groups = init_groups_visitor($contact['id']);
118
119                 if(count($groups)) {
120                         for($x = 0; $x < count($groups); $x ++)
121                                 $groups[$x] = '<' . intval($groups[$x]) . '>' ;
122                         $gs = implode('|', $groups);
123                 }
124                 else
125                         $gs = '<<>>' ; // Impossible to match
126
127                 $sql_extra = sprintf("
128                         AND ( `allow_cid` = '' OR     `allow_cid` REGEXP '<%d>' )
129                         AND ( `deny_cid`  = '' OR NOT `deny_cid`  REGEXP '<%d>' )
130                         AND ( `allow_gid` = '' OR     `allow_gid` REGEXP '%s' )
131                         AND ( `deny_gid`  = '' OR NOT `deny_gid`  REGEXP '%s')
132                 ",
133                         intval($contact['id']),
134                         intval($contact['id']),
135                         dbesc($gs),
136                         dbesc($gs)
137                 );
138         }
139
140         if($public_feed)
141                 $sort = 'DESC';
142         else
143                 $sort = 'ASC';
144
145         $date_field = "`changed`";
146         $sql_order = "`item`.`parent` ".$sort.", `item`.`created` ASC";
147
148         if(! strlen($last_update))
149                 $last_update = 'now -30 days';
150
151         if(isset($category)) {
152                 $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` ",
153                                 dbesc(protect_sprintf($category)), intval(TERM_OBJ_POST), intval(TERM_CATEGORY), intval($owner_id));
154                 //$sql_extra .= file_tag_file_query('item',$category,'category');
155         }
156
157         if($public_feed) {
158                 if(! $converse)
159                         $sql_extra .= " AND `contact`.`self` = 1 ";
160         }
161
162         $check_date = datetime_convert('UTC','UTC',$last_update,'Y-m-d H:i:s');
163
164         //      AND ( `item`.`edited` > '%s' OR `item`.`changed` > '%s' )
165         //      dbesc($check_date),
166
167         $r = q("SELECT STRAIGHT_JOIN `item`.*, `item`.`id` AS `item_id`,
168                 `contact`.`name`, `contact`.`network`, `contact`.`photo`, `contact`.`url`,
169                 `contact`.`name-date`, `contact`.`uri-date`, `contact`.`avatar-date`,
170                 `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
171                 `contact`.`id` AS `contact-id`, `contact`.`uid` AS `contact-uid`,
172                 `sign`.`signed_text`, `sign`.`signature`, `sign`.`signer`
173                 FROM `item` $sql_post_table
174                 INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
175                 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
176                 LEFT JOIN `sign` ON `sign`.`iid` = `item`.`id`
177                 WHERE `item`.`uid` = %d AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`parent` != 0
178                 AND ((`item`.`wall` = 1) $visibility) AND `item`.$date_field > '%s'
179                 $sql_extra
180                 ORDER BY $sql_order LIMIT 0, 300",
181                 intval($owner_id),
182                 dbesc($check_date),
183                 dbesc($sort)
184         );
185
186         // Will check further below if this actually returned results.
187         // We will provide an empty feed if that is the case.
188
189         $items = $r;
190
191         $doc = new DOMDocument('1.0', 'utf-8');
192         $doc->formatOutput = true;
193
194         $alternatelink = $owner['url'];
195
196         if(isset($category))
197                 $alternatelink .= "/category/".$category;
198
199         if ($public_feed)
200                 $author = "dfrn:owner";
201         else
202                 $author = "author";
203
204         $root = dfrn_add_header($doc, $owner, $author, $alternatelink, true);
205
206         // This hook can't work anymore
207         //      call_hooks('atom_feed', $atom);
208
209         if(! count($items)) {
210                 $atom = trim($doc->saveXML());
211
212                 call_hooks('atom_feed_end', $atom);
213
214                 return $atom;
215         }
216
217         foreach($items as $item) {
218
219                 // prevent private email from leaking.
220                 if($item['network'] === NETWORK_MAIL)
221                         continue;
222
223                 // public feeds get html, our own nodes use bbcode
224
225                 if($public_feed) {
226                         $type = 'html';
227                         // catch any email that's in a public conversation and make sure it doesn't leak
228                         if($item['private'])
229                                 continue;
230                 }
231                 else {
232                         $type = 'text';
233                 }
234
235                 $entry = dfrn_entry($doc, $type, $item, $owner, true);
236                 $root->appendChild($entry);
237
238         }
239
240         $atom = trim($doc->saveXML());
241
242         call_hooks('atom_feed_end', $atom);
243
244         return $atom;
245 }
246
247 /**
248  * @brief Create XML text for DFRN mails
249  *
250  * @param array $item message elements
251  * @param array $owner Owner record
252  *
253  * @return string DFRN mail
254  */
255 function dfrn_mail($item, $owner) {
256         $doc = new DOMDocument('1.0', 'utf-8');
257         $doc->formatOutput = true;
258
259         $root = dfrn_add_header($doc, $owner, "dfrn:owner", "", false);
260
261         $mail = $doc->createElement("dfrn:mail");
262         $sender = $doc->createElement("dfrn:sender");
263
264         xml_add_element($doc, $sender, "dfrn:name", $owner['name']);
265         xml_add_element($doc, $sender, "dfrn:uri", $owner['url']);
266         xml_add_element($doc, $sender, "dfrn:avatar", $owner['thumb']);
267
268         $mail->appendChild($sender);
269
270         xml_add_element($doc, $mail, "dfrn:id", $item['uri']);
271         xml_add_element($doc, $mail, "dfrn:in-reply-to", $item['parent-uri']);
272         xml_add_element($doc, $mail, "dfrn:sentdate", datetime_convert('UTC', 'UTC', $item['created'] . '+00:00' , ATOM_TIME));
273         xml_add_element($doc, $mail, "dfrn:subject", $item['title']);
274         xml_add_element($doc, $mail, "dfrn:content", $item['body']);
275
276         $root->appendChild($mail);
277
278         return(trim($doc->saveXML()));
279 }
280
281 /**
282  * @brief Create XML text for DFRN friend suggestions
283  *
284  * @param array $item suggestion elements
285  * @param array $owner Owner record
286  *
287  * @return string DFRN suggestions
288  */
289 function dfrn_fsuggest($item, $owner) {
290         $doc = new DOMDocument('1.0', 'utf-8');
291         $doc->formatOutput = true;
292
293         $root = dfrn_add_header($doc, $owner, "dfrn:owner", "", false);
294
295         $suggest = $doc->createElement("dfrn:suggest");
296
297         xml_add_element($doc, $suggest, "dfrn:url", $item['url']);
298         xml_add_element($doc, $suggest, "dfrn:name", $item['name']);
299         xml_add_element($doc, $suggest, "dfrn:photo", $item['photo']);
300         xml_add_element($doc, $suggest, "dfrn:request", $item['request']);
301         xml_add_element($doc, $suggest, "dfrn:note", $item['note']);
302
303         $root->appendChild($suggest);
304
305         return(trim($doc->saveXML()));
306 }
307
308 /**
309  * @brief Create XML text for DFRN relocations
310  *
311  * @param array $owner Owner record
312  * @param int $uid User ID
313  *
314  * @return string DFRN relocations
315  */
316 function dfrn_relocate($owner, $uid) {
317
318         $a = get_app();
319
320         /* get site pubkey. this could be a new installation with no site keys*/
321         $pubkey = get_config('system','site_pubkey');
322         if(! $pubkey) {
323                 $res = new_keypair(1024);
324                 set_config('system','site_prvkey', $res['prvkey']);
325                 set_config('system','site_pubkey', $res['pubkey']);
326         }
327
328         $rp = q("SELECT `resource-id` , `scale`, type FROM `photo`
329                         WHERE `profile` = 1 AND `uid` = %d ORDER BY scale;", $uid);
330         $photos = array();
331         $ext = Photo::supportedTypes();
332         foreach($rp as $p){
333                 $photos[$p['scale']] = $a->get_baseurl().'/photo/'.$p['resource-id'].'-'.$p['scale'].'.'.$ext[$p['type']];
334         }
335         unset($rp, $ext);
336
337         $doc = new DOMDocument('1.0', 'utf-8');
338         $doc->formatOutput = true;
339
340         $root = dfrn_add_header($doc, $owner, "dfrn:owner", "", false);
341
342         $relocate = $doc->createElement("dfrn:relocate");
343
344         xml_add_element($doc, $relocate, "dfrn:url", $owner['url']);
345         xml_add_element($doc, $relocate, "dfrn:name", $owner['name']);
346         xml_add_element($doc, $relocate, "dfrn:photo", $photos[4]);
347         xml_add_element($doc, $relocate, "dfrn:thumb", $photos[5]);
348         xml_add_element($doc, $relocate, "dfrn:micro", $photos[6]);
349         xml_add_element($doc, $relocate, "dfrn:request", $owner['request']);
350         xml_add_element($doc, $relocate, "dfrn:confirm", $owner['confirm']);
351         xml_add_element($doc, $relocate, "dfrn:notify", $owner['notify']);
352         xml_add_element($doc, $relocate, "dfrn:poll", $owner['poll']);
353         xml_add_element($doc, $relocate, "dfrn:sitepubkey", get_config('system','site_pubkey'));
354
355         $root->appendChild($relocate);
356
357         return(trim($doc->saveXML()));
358 }
359
360 /**
361  * @brief Adds the header elements for the DFRN protocol
362  *
363  * @param object $doc XML document
364  * @param array $owner Owner record
365  * @param string $authorelement Element name for the author
366  * @param string $alternatelink link to profile or category
367  * @param bool $public Is it a header for public posts?
368  *
369  * @return object XML root object
370  */
371 function dfrn_add_header($doc, $owner, $authorelement, $alternatelink = "", $public = false) {
372         $a = get_app();
373
374         if ($alternatelink == "")
375                 $alternatelink = $owner['url'];
376
377         $root = $doc->createElementNS(NS_ATOM, 'feed');
378         $doc->appendChild($root);
379
380         $root->setAttribute("xmlns:thr", NS_THR);
381         $root->setAttribute("xmlns:at", "http://purl.org/atompub/tombstones/1.0");
382         $root->setAttribute("xmlns:media", NS_MEDIA);
383         $root->setAttribute("xmlns:dfrn", "http://purl.org/macgirvin/dfrn/1.0");
384         $root->setAttribute("xmlns:activity", NS_ACTIVITY);
385         $root->setAttribute("xmlns:georss", NS_GEORSS);
386         $root->setAttribute("xmlns:poco", NS_POCO);
387         $root->setAttribute("xmlns:ostatus", NS_OSTATUS);
388         $root->setAttribute("xmlns:statusnet", NS_STATUSNET);
389
390         xml_add_element($doc, $root, "id", $a->get_baseurl()."/profile/".$owner["nick"]);
391         xml_add_element($doc, $root, "title", $owner["name"]);
392
393         $attributes = array("uri" => "https://friendi.ca", "version" => FRIENDICA_VERSION."-".DB_UPDATE_VERSION);
394         xml_add_element($doc, $root, "generator", FRIENDICA_PLATFORM, $attributes);
395
396         $attributes = array("rel" => "license", "href" => "http://creativecommons.org/licenses/by/3.0/");
397         xml_add_element($doc, $root, "link", "", $attributes);
398
399         $attributes = array("rel" => "alternate", "type" => "text/html", "href" => $alternatelink);
400         xml_add_element($doc, $root, "link", "", $attributes);
401
402         ostatus_hublinks($doc, $root);
403
404         if ($public) {
405                 $attributes = array("rel" => "salmon", "href" => $a->get_baseurl()."/salmon/".$owner["nick"]);
406                 xml_add_element($doc, $root, "link", "", $attributes);
407
408                 $attributes = array("rel" => "http://salmon-protocol.org/ns/salmon-replies", "href" => $a->get_baseurl()."/salmon/".$owner["nick"]);
409                 xml_add_element($doc, $root, "link", "", $attributes);
410
411                 $attributes = array("rel" => "http://salmon-protocol.org/ns/salmon-mention", "href" => $a->get_baseurl()."/salmon/".$owner["nick"]);
412                 xml_add_element($doc, $root, "link", "", $attributes);
413         }
414
415         if ($owner['page-flags'] == PAGE_COMMUNITY)
416                 xml_add_element($doc, $root, "dfrn:community", 1);
417
418         xml_add_element($doc, $root, "updated", datetime_convert("UTC", "UTC", "now", ATOM_TIME));
419
420         $author = dfrn_add_author($doc, $owner, $authorelement, $public);
421         $root->appendChild($author);
422
423         return $root;
424 }
425
426 /**
427  * @brief Adds the author element in the header for the DFRN protocol
428  *
429  * @param object $doc XML document
430  * @param array $owner Owner record
431  * @param string $authorelement Element name for the author
432  *
433  * @return object XML author object
434  */
435 function dfrn_add_author($doc, $owner, $authorelement, $public) {
436         $a = get_app();
437
438         $author = $doc->createElement($authorelement);
439
440         $namdate = datetime_convert('UTC', 'UTC', $owner['name-date'].'+00:00' , ATOM_TIME);
441         $uridate = datetime_convert('UTC', 'UTC', $owner['uri-date'].'+00:00', ATOM_TIME);
442         $picdate = datetime_convert('UTC', 'UTC', $owner['avatar-date'].'+00:00', ATOM_TIME);
443
444         $attributes = array("dfrn:updated" => $namdate);
445         xml_add_element($doc, $author, "name", $owner["name"], $attributes);
446
447         $attributes = array("dfrn:updated" => $namdate);
448         xml_add_element($doc, $author, "uri", $a->get_baseurl().'/profile/'.$owner["nickname"], $attributes);
449
450         $attributes = array("rel" => "photo", "type" => "image/jpeg", "dfrn:updated" => $picdate,
451                                 "media:width" => 175, "media:height" => 175, "href" => $owner['photo']);
452         xml_add_element($doc, $author, "link", "", $attributes);
453
454         $attributes = array("rel" => "avatar", "type" => "image/jpeg", "dfrn:updated" => $picdate,
455                                 "media:width" => 175, "media:height" => 175, "href" => $owner['photo']);
456         xml_add_element($doc, $author, "link", "", $attributes);
457
458         $birthday = feed_birthday($owner['user_uid'], $owner['timezone']);
459
460         if ($birthday)
461                 xml_add_element($doc, $author, "dfrn:birthday", $birthday);
462
463         // The following fields will only be generated if this isn't for a public feed
464         if ($public)
465                 return $author;
466
467         // Only show contact details when we are allowed to
468         $r = q("SELECT `profile`.`about`, `profile`.`name`, `profile`.`homepage`, `user`.`nickname`, `user`.`timezone`,
469                         `profile`.`locality`, `profile`.`region`, `profile`.`country-name`, `profile`.`pub_keywords`, `profile`.`dob`
470                 FROM `profile`
471                         INNER JOIN `user` ON `user`.`uid` = `profile`.`uid`
472                         WHERE `profile`.`is-default` AND NOT `user`.`hidewall` AND `user`.`uid` = %d",
473                 intval($owner['user_uid']));
474         if ($r) {
475                 $profile = $r[0];
476                 xml_add_element($doc, $author, "poco:displayName", $profile["name"]);
477                 xml_add_element($doc, $author, "poco:updated", $namdate);
478
479                 if (trim($profile["dob"]) != "0000-00-00")
480                         xml_add_element($doc, $author, "poco:birthday", "0000-".date("m-d", strtotime($profile["dob"])));
481
482                 xml_add_element($doc, $author, "poco:note", $profile["about"]);
483                 xml_add_element($doc, $author, "poco:preferredUsername", $profile["nickname"]);
484
485                 $savetz = date_default_timezone_get();
486                 date_default_timezone_set($profile["timezone"]);
487                 xml_add_element($doc, $author, "poco:utcOffset", date("P"));
488                 date_default_timezone_set($savetz);
489
490                 if (trim($profile["homepage"]) != "") {
491                         $urls = $doc->createElement("poco:urls");
492                         xml_add_element($doc, $urls, "poco:type", "homepage");
493                         xml_add_element($doc, $urls, "poco:value", $profile["homepage"]);
494                         xml_add_element($doc, $urls, "poco:primary", "true");
495                         $author->appendChild($urls);
496                 }
497
498                 if (trim($profile["pub_keywords"]) != "") {
499                         $keywords = explode(",", $profile["pub_keywords"]);
500
501                         foreach ($keywords AS $keyword)
502                                 xml_add_element($doc, $author, "poco:tags", trim($keyword));
503
504                 }
505
506                 /// @todo When we are having the XMPP address in the profile we should propagate it here
507                 $xmpp = "";
508                 if (trim($xmpp) != "") {
509                         $ims = $doc->createElement("poco:ims");
510                         xml_add_element($doc, $ims, "poco:type", "xmpp");
511                         xml_add_element($doc, $ims, "poco:value", $xmpp);
512                         xml_add_element($doc, $ims, "poco:primary", "true");
513                         $author->appendChild($ims);
514                 }
515
516                 if (trim($profile["locality"].$profile["region"].$profile["country-name"]) != "") {
517                         $element = $doc->createElement("poco:address");
518
519                         xml_add_element($doc, $element, "poco:formatted", formatted_location($profile));
520
521                         if (trim($profile["locality"]) != "")
522                                 xml_add_element($doc, $element, "poco:locality", $profile["locality"]);
523
524                         if (trim($profile["region"]) != "")
525                                 xml_add_element($doc, $element, "poco:region", $profile["region"]);
526
527                         if (trim($profile["country-name"]) != "")
528                                 xml_add_element($doc, $element, "poco:country", $profile["country-name"]);
529
530                         $author->appendChild($element);
531                 }
532         }
533
534         return $author;
535 }
536
537 /**
538  * @brief Adds the author elements in the "entry" elements of the DFRN protocol
539  *
540  * @param object $doc XML document
541  * @param string $element Element name for the author
542  * @param string $contact_url Link of the contact
543  * @param array $items Item elements
544  *
545  * @return object XML author object
546  */
547 function dfrn_add_entry_author($doc, $element, $contact_url, $item) {
548         $a = get_app();
549
550         $contact = get_contact_details_by_url($contact_url, $item["uid"]);
551
552         $author = $doc->createElement($element);
553         xml_add_element($doc, $author, "name", $contact["name"]);
554         xml_add_element($doc, $author, "uri", $contact["url"]);
555
556         /// @Todo
557         /// - Check real image type and image size
558         /// - Check which of these boths elements we should use
559         $attributes = array(
560                         "rel" => "photo",
561                         "type" => "image/jpeg",
562                         "media:width" => 80,
563                         "media:height" => 80,
564                         "href" => $contact["photo"]);
565         xml_add_element($doc, $author, "link", "", $attributes);
566
567         $attributes = array(
568                         "rel" => "avatar",
569                         "type" => "image/jpeg",
570                         "media:width" => 80,
571                         "media:height" => 80,
572                         "href" => $contact["photo"]);
573         xml_add_element($doc, $author, "link", "", $attributes);
574
575         return $author;
576 }
577
578 /**
579  * @brief Adds the activity elements
580  *
581  * @param object $doc XML document
582  * @param string $element Element name for the activity
583  * @param string $activity activity value
584  *
585  * @return object XML activity object
586  */
587 function dfrn_create_activity($doc, $element, $activity) {
588
589         if($activity) {
590                 $entry = $doc->createElement($element);
591
592                 $r = parse_xml_string($activity, false);
593                 if(!$r)
594                         return false;
595                 if($r->type)
596                         xml_add_element($doc, $entry, "activity:object-type", $r->type);
597                 if($r->id)
598                         xml_add_element($doc, $entry, "id", $r->id);
599                 if($r->title)
600                         xml_add_element($doc, $entry, "title", $r->title);
601                 if($r->link) {
602                         if(substr($r->link,0,1) === '<') {
603                                 if(strstr($r->link,'&') && (! strstr($r->link,'&amp;')))
604                                         $r->link = str_replace('&','&amp;', $r->link);
605
606                                 $r->link = preg_replace('/\<link(.*?)\"\>/','<link$1"/>',$r->link);
607
608                                 $data = parse_xml_string($r->link, false);
609                                 foreach ($data->attributes() AS $parameter => $value)
610                                         $attributes[$parameter] = $value;
611                         } else
612                                 $attributes = array("rel" => "alternate", "type" => "text/html", "href" => $r->link);
613
614                         xml_add_element($doc, $entry, "link", "", $attributes);
615                 }
616                 if($r->content)
617                         xml_add_element($doc, $entry, "content", bbcode($r->content), array("type" => "html"));
618
619                 return $entry;
620         }
621
622         return false;
623 }
624
625 /**
626  * @brief Adds the elements for attachments
627  *
628  * @param object $doc XML document
629  * @param object $root XML root
630  * @param array $item Item element
631  *
632  * @return object XML attachment object
633  */
634 function dfrn_get_attachment($doc, $root, $item) {
635         $arr = explode('[/attach],',$item['attach']);
636         if(count($arr)) {
637                 foreach($arr as $r) {
638                         $matches = false;
639                         $cnt = preg_match('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\" title=\"(.*?)\"|',$r,$matches);
640                         if($cnt) {
641                                 $attributes = array("rel" => "enclosure",
642                                                 "href" => $matches[1],
643                                                 "type" => $matches[3]);
644
645                                 if(intval($matches[2]))
646                                         $attributes["length"] = intval($matches[2]);
647
648                                 if(trim($matches[4]) != "")
649                                         $attributes["title"] = trim($matches[4]);
650
651                                 xml_add_element($doc, $root, "link", "", $attributes);
652                         }
653                 }
654         }
655 }
656
657 /**
658  * @brief Adds the "entry" elements for the DFRN protocol
659  *
660  * @param object $doc XML document
661  * @param string $type "text" or "html"
662  * @param array $item Item element
663  * @param array $owner Owner record
664  * @param bool $comment Trigger the sending of the "comment" element
665  * @param int $cid
666  *
667  * @return object XML entry object
668  */
669 function dfrn_entry($doc, $type, $item, $owner, $comment = false, $cid = 0) {
670         $a = get_app();
671
672         $mentioned = array();
673
674         if(!$item['parent'])
675                 return;
676
677         if($item['deleted']) {
678                 $attributes = array("ref" => $item['uri'], "when" => datetime_convert('UTC','UTC',$item['edited'] . '+00:00',ATOM_TIME));
679                 return xml_create_element($doc, "at:deleted-entry", "", $attributes);
680         }
681
682         $entry = $doc->createElement("entry");
683
684         if($item['allow_cid'] || $item['allow_gid'] || $item['deny_cid'] || $item['deny_gid'])
685                 $body = fix_private_photos($item['body'],$owner['uid'],$item,$cid);
686         else
687                 $body = $item['body'];
688
689         if ($type == 'html') {
690                 $htmlbody = $body;
691
692                 if ($item['title'] != "")
693                         $htmlbody = "[b]".$item['title']."[/b]\n\n".$htmlbody;
694
695                 $htmlbody = bbcode($htmlbody, false, false, 7);
696         }
697
698         $author = dfrn_add_entry_author($doc, "author", $item["author-link"], $item);
699         $entry->appendChild($author);
700
701         $dfrnowner = dfrn_add_entry_author($doc, "dfrn:owner", $item["owner-link"], $item);
702         $entry->appendChild($dfrnowner);
703
704         if(($item['parent'] != $item['id']) || ($item['parent-uri'] !== $item['uri']) || (($item['thr-parent'] !== '') && ($item['thr-parent'] !== $item['uri']))) {
705                 $parent = q("SELECT `guid` FROM `item` WHERE `id` = %d", intval($item["parent"]));
706                 $parent_item = (($item['thr-parent']) ? $item['thr-parent'] : $item['parent-uri']);
707                 $attributes = array("ref" => $parent_item, "type" => "text/html", "href" => $a->get_baseurl().'/display/'.$parent[0]['guid']);
708                 xml_add_element($doc, $entry, "thr:in-reply-to", "", $attributes);
709         }
710
711         xml_add_element($doc, $entry, "id", $item["uri"]);
712         xml_add_element($doc, $entry, "title", $item["title"]);
713
714         xml_add_element($doc, $entry, "published", datetime_convert("UTC","UTC",$item["created"]."+00:00",ATOM_TIME));
715         xml_add_element($doc, $entry, "updated", datetime_convert("UTC","UTC",$item["edited"]."+00:00",ATOM_TIME));
716
717         xml_add_element($doc, $entry, "dfrn:env", base64url_encode($body, true));
718         xml_add_element($doc, $entry, "content", (($type === 'html') ? $htmlbody : $body), array("type" => $type));
719
720         xml_add_element($doc, $entry, "link", "", array("rel" => "alternate", "type" => "text/html",
721                                                         "href" => $a->get_baseurl()."/display/".$item["guid"]));
722
723         if ($comment)
724                 xml_add_element($doc, $entry, "dfrn:comment-allow", intval($item['last-child']));
725
726         if($item['location'])
727                 xml_add_element($doc, $entry, "dfrn:location", $item['location']);
728
729         if($item['coord'])
730                 xml_add_element($doc, $entry, "georss:point", $item['coord']);
731
732         if(($item['private']) || strlen($item['allow_cid']) || strlen($item['allow_gid']) || strlen($item['deny_cid']) || strlen($item['deny_gid']))
733                 xml_add_element($doc, $entry, "dfrn:private", (($item['private']) ? $item['private'] : 1));
734
735         if($item['extid'])
736                 xml_add_element($doc, $entry, "dfrn:extid", $item['extid']);
737
738         if($item['bookmark'])
739                 xml_add_element($doc, $entry, "dfrn:bookmark", "true");
740
741         if($item['app'])
742                 xml_add_element($doc, $entry, "statusnet:notice_info", "", array("local_id" => $item['id'], "source" => $item['app']));
743
744         xml_add_element($doc, $entry, "dfrn:diaspora_guid", $item["guid"]);
745
746         if($item['signed_text']) {
747                 $sign = base64_encode(json_encode(array('signed_text' => $item['signed_text'],'signature' => $item['signature'],'signer' => $item['signer'])));
748                 xml_add_element($doc, $entry, "dfrn:diaspora_signature", $sign);
749         }
750
751         xml_add_element($doc, $entry, "activity:verb", construct_verb($item));
752
753         $actobj = dfrn_create_activity($doc, "activity:object", $item['object']);
754         if ($actobj)
755                 $entry->appendChild($actobj);
756
757         $actarg = dfrn_create_activity($doc, "activity:target", $item['target']);
758         if ($actarg)
759                 $entry->appendChild($actarg);
760
761         $tags = item_getfeedtags($item);
762
763         if(count($tags)) {
764                 foreach($tags as $t)
765                         if (($type != 'html') OR ($t[0] != "@"))
766                                 xml_add_element($doc, $entry, "category", "", array("scheme" => "X-DFRN:".$t[0].":".$t[1], "term" => $t[2]));
767         }
768
769         if(count($tags))
770                 foreach($tags as $t)
771                         if ($t[0] == "@")
772                                 $mentioned[$t[1]] = $t[1];
773
774         foreach ($mentioned AS $mention) {
775                 $r = q("SELECT `forum`, `prv` FROM `contact` WHERE `uid` = %d AND `nurl` = '%s'",
776                         intval($owner["uid"]),
777                         dbesc(normalise_link($mention)));
778                 if ($r[0]["forum"] OR $r[0]["prv"])
779                         xml_add_element($doc, $entry, "link", "", array("rel" => "mentioned",
780                                                                                 "ostatus:object-type" => ACTIVITY_OBJ_GROUP,
781                                                                                 "href" => $mention));
782                 else
783                         xml_add_element($doc, $entry, "link", "", array("rel" => "mentioned",
784                                                                                 "ostatus:object-type" => ACTIVITY_OBJ_PERSON,
785                                                                                 "href" => $mention));
786         }
787
788         dfrn_get_attachment($doc, $entry, $item);
789
790         return $entry;
791 }