]> git.mxchange.org Git - friendica.git/blob - include/bb2diaspora.php
c197c755819713737faa2c195d12d6c050934542
[friendica.git] / include / bb2diaspora.php
1 <?php
2
3 require_once("include/oembed.php");
4 require_once("include/event.php");
5 require_once("library/markdown.php");
6 require_once("include/html2bbcode.php");
7 require_once("include/bbcode.php");
8 require_once("library/html-to-markdown/HTML_To_Markdown.php");
9
10 /**
11  * @brief Callback function to replace a Diaspora style mention in a mention for Friendica
12  *
13  * @param array $match Matching values for the callback
14  * @return text Replaced mention
15  */
16 function diaspora_mention2bb($match) {
17         if ($match[2] == '') {
18                 return;
19         }
20
21         /// @todo Don't use probe
22         //$data = Probe::uri($match[2]);
23         $data = get_contact_details_by_addr($match[2]);
24
25         $name = $match[1];
26
27         if ($name == '') {
28                 $name = $data['name'];
29         }
30
31         return '@[url='.$data['url'].']'.$name.'[/url]';
32 }
33
34 // we don't want to support a bbcode specific markdown interpreter
35 // and the markdown library we have is pretty good, but provides HTML output.
36 // So we'll use that to convert to HTML, then convert the HTML back to bbcode,
37 // and then clean up a few Diaspora specific constructs.
38
39 function diaspora2bb($s) {
40
41         $s = html_entity_decode($s, ENT_COMPAT, 'UTF-8');
42
43         // Handles single newlines
44         $s = str_replace("\r", '<br>', $s);
45
46         $s = str_replace("\n", " \n", $s);
47
48         // Replace lonely stars in lines not starting with it with literal stars
49         $s = preg_replace('/^([^\*]+)\*([^\*]*)$/im', '$1\*$2', $s);
50
51         // The parser cannot handle paragraphs correctly
52         $s = str_replace(array('</p>', '<p>', '<p dir="ltr">'), array('<br>', '<br>', '<br>'), $s);
53
54         // Escaping the hash tags
55         $s = preg_replace('/\#([^\s\#])/', '&#35;$1', $s);
56
57         $s = Markdown($s);
58
59         $regexp = "/@\{(?:([^\}]+?); )?([^\} ]+)\}/";
60         $s = preg_replace_callback($regexp, 'diaspora_mention2bb', $s);
61
62         $s = str_replace('&#35;', '#', $s);
63
64         $search = array(" \n", "\n ");
65         $replace = array("\n", "\n");
66         do {
67                 $oldtext = $s;
68                 $s = str_replace($search, $replace, $s);
69         } while ($oldtext != $s);
70
71         $s = str_replace("\n\n", '<br>', $s);
72
73         $s = html2bbcode($s);
74
75         // protect the recycle symbol from turning into a tag, but without unescaping angles and naked ampersands
76         $s = str_replace('&#x2672;', html_entity_decode('&#x2672;', ENT_QUOTES, 'UTF-8'), $s);
77
78         // Convert everything that looks like a link to a link
79         $s = preg_replace('/([^\]=]|^)(https?\:\/\/)([a-zA-Z0-9:\/\-?&;.=_~#%$!+,@]+(?<!,))/ism', '$1[url=$2$3]$2$3[/url]', $s);
80
81         //$s = preg_replace("/([^\]\=]|^)(https?\:\/\/)(vimeo|youtu|www\.youtube|soundcloud)([a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/ism", '$1[url=$2$3$4]$2$3$4[/url]',$s);
82         $s = bb_tag_preg_replace('/\[url\=?(.*?)\]https?:\/\/www.youtube.com\/watch\?v\=(.*?)\[\/url\]/ism', '[youtube]$2[/youtube]', 'url', $s);
83         $s = bb_tag_preg_replace('/\[url\=https?:\/\/www.youtube.com\/watch\?v\=(.*?)\].*?\[\/url\]/ism'   , '[youtube]$1[/youtube]', 'url', $s);
84         $s = bb_tag_preg_replace('/\[url\=?(.*?)\]https?:\/\/vimeo.com\/([0-9]+)(.*?)\[\/url\]/ism'        , '[vimeo]$2[/vimeo]'    , 'url', $s);
85         $s = bb_tag_preg_replace('/\[url\=https?:\/\/vimeo.com\/([0-9]+)\](.*?)\[\/url\]/ism'              , '[vimeo]$1[/vimeo]'    , 'url', $s);
86
87         // remove duplicate adjacent code tags
88         $s = preg_replace('/(\[code\])+(.*?)(\[\/code\])+/ism', '[code]$2[/code]', $s);
89
90         // Don't show link to full picture (until it is fixed)
91         $s = scale_external_images($s, false);
92
93         return $s;
94 }
95
96 /**
97  * @brief Callback function to replace a Friendica style mention in a mention for Diaspora
98  *
99  * @param array $match Matching values for the callback
100  * @return text Replaced mention
101  */
102 function diaspora_mentions($match) {
103
104         $contact = get_contact_details_by_url($match[3]);
105
106         if (!isset($contact['addr'])) {
107                 $contact = Probe::uri($match[3]);
108         }
109
110         if (!isset($contact['addr'])) {
111                 return $match[0];
112         }
113
114         $mention = '@{'.$match[2].'; '.$contact['addr'].'}';
115         return $mention;
116 }
117
118 function bb2diaspora($Text,$preserve_nl = false, $fordiaspora = true) {
119
120         $a = get_app();
121
122         $OriginalText = $Text;
123
124         // Since Diaspora is creating a summary for links, this function removes them before posting
125         if ($fordiaspora)
126                 $Text = bb_remove_share_information($Text);
127
128         /**
129          * Transform #tags, strip off the [url] and replace spaces with underscore
130          */
131         $URLSearchString = "^\[\]";
132         $Text = preg_replace_callback("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/i", create_function('$match',
133                 'return \'#\'. str_replace(\' \', \'_\', $match[2]);'
134         ), $Text);
135
136         // Converting images with size parameters to simple images. Markdown doesn't know it.
137         $Text = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $Text);
138
139         // Convert it to HTML - don't try oembed
140         if ($fordiaspora) {
141                 $Text = bbcode($Text, $preserve_nl, false, 3);
142
143                 // Add all tags that maybe were removed
144                 if (preg_match_all("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",$OriginalText, $tags)) {
145                         $tagline = "";
146                         foreach($tags[2] as $tag) {
147                                 $tag = html_entity_decode($tag, ENT_QUOTES, 'UTF-8');
148                                 if (!strpos(html_entity_decode($Text, ENT_QUOTES, 'UTF-8'), "#".$tag))
149                                         $tagline .= "#".$tag." ";
150                         }
151                         $Text = $Text." ".$tagline;
152                 }
153
154         } else
155                 $Text = bbcode($Text, $preserve_nl, false, 4);
156
157         // mask some special HTML chars from conversation to markdown
158         $Text = str_replace(array('&lt;','&gt;','&amp;'),array('&_lt_;','&_gt_;','&_amp_;'),$Text);
159
160         // If a link is followed by a quote then there should be a newline before it
161         // Maybe we should make this newline at every time before a quote.
162         $Text = str_replace(array("</a><blockquote>"), array("</a><br><blockquote>"), $Text);
163
164         $stamp1 = microtime(true);
165
166         // Now convert HTML to Markdown
167         $Text = new HTML_To_Markdown($Text);
168
169         // unmask the special chars back to HTML
170         $Text = str_replace(array('&_lt_;','&_gt_;','&_amp_;'),array('&lt;','&gt;','&amp;'),$Text);
171
172         $a->save_timestamp($stamp1, "parser");
173
174         // Libertree has a problem with escaped hashtags.
175         $Text = str_replace(array('\#'), array('#'), $Text);
176
177         // Remove any leading or trailing whitespace, as this will mess up
178         // the Diaspora signature verification and cause the item to disappear
179         $Text = trim($Text);
180
181         if ($fordiaspora) {
182                 $URLSearchString = "^\[\]";
183                 $Text = preg_replace_callback("/([@]\[(.*?)\])\(([$URLSearchString]*?)\)/ism", 'diaspora_mentions', $Text);
184         }
185
186         call_hooks('bb2diaspora',$Text);
187
188         return $Text;
189 }
190
191 function unescape_underscores_in_links($m) {
192         $y = str_replace('\\_','_', $m[2]);
193         return('[' . $m[1] . '](' . $y . ')');
194 }
195
196 function format_event_diaspora($ev) {
197
198         if(! ((is_array($ev)) && count($ev)))
199                 return '';
200
201         $bd_format = t('l F d, Y \@ g:i A') ; // Friday January 18, 2011 @ 8 AM
202
203         $o = 'Friendica event notification:' . "\n";
204
205         $o .= '**' . (($ev['summary']) ? bb2diaspora($ev['summary']) : bb2diaspora($ev['desc'])) .  '**' . "\n";
206
207         $o .= t('Starts:') . ' ' . '['
208                 . (($ev['adjust']) ? day_translate(datetime_convert('UTC', 'UTC',
209                         $ev['start'] , $bd_format ))
210                         :  day_translate(datetime_convert('UTC', 'UTC',
211                         $ev['start'] , $bd_format)))
212                 .  '](' . App::get_baseurl() . '/localtime/?f=&time=' . urlencode(datetime_convert('UTC','UTC',$ev['start'])) . ")\n";
213
214         if(! $ev['nofinish'])
215                 $o .= t('Finishes:') . ' ' . '['
216                         . (($ev['adjust']) ? day_translate(datetime_convert('UTC', 'UTC',
217                                 $ev['finish'] , $bd_format ))
218                                 :  day_translate(datetime_convert('UTC', 'UTC',
219                                 $ev['finish'] , $bd_format )))
220                         . '](' . App::get_baseurl() . '/localtime/?f=&time=' . urlencode(datetime_convert('UTC','UTC',$ev['finish'])) . ")\n";
221
222         if(strlen($ev['location']))
223                 $o .= t('Location:') . bb2diaspora($ev['location'])
224                         . "\n";
225
226         $o .= "\n";
227         return $o;
228 }