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