Use short form array syntax everywhere
[friendica-addons.git] / fortunate / cookie.php
1 <?php
2
3 set_time_limit(0);
4 error_reporting(0);
5 require(".htconfig.php");
6 $db = @new mysqli($db_host,$db_user,$db_pass,$db_data);
7
8 header( "Content-type: text/html; charset=utf-8");
9 header( "Last-Modified: " . gmdate( "D, j M Y H:i:s" ) . " GMT" );
10 header( "Expires: " . gmdate( "D, j M Y H:i:s", time() ) . " GMT" );
11 header( "Cache-Control: no-store, no-cache, must-revalidate" ); // HTTP/1.1
12 header( "Cache-Control: post-check=0, pre-check=0", FALSE );
13 header( "Pragma: no-cache" ); // HTTP/1.0
14
15 $lang = 'en';
16
17 $offensive = $_GET['off'];
18 if($offensive == 'o')
19   $adult = 2;
20 elseif($offensive == 'a')
21   $adult = 1;
22 else
23   $adult = 0;
24
25 $length = (($_GET['length']) ? intval($_GET['length']) : 0);
26 $numlines = ((intval($_GET['numlines'])) ? intval($_GET['numlines']) : 0);
27 $cat = (($_GET['cat'] == '1') ? 1 : 0);
28 $equal = (($_GET['equal'] == '1') ? 1 : 0);
29 $stats = (($_GET['stats'] == '1') ? 1 : 0);
30
31 if(strlen($_GET['lang']))
32   $lang = @$db->real_escape_string($_GET['lang']);
33
34 if(strlen($_GET['pattern']))
35   $pattern = @$db->real_escape_string(urldecode($_GET['pattern']));
36
37 if(strlen($_GET['regex']))
38   $regex = @$db->real_escape_string(urldecode($_GET['regex']));
39
40 if(strlen($_GET['db']))
41   $table = @$db->real_escape_string(urldecode($_GET['db']));
42 else
43   $table = '';
44
45 if($length < 0)
46   $length = 0;
47 if($numlines < 0)
48   $numlines = 0;
49
50 function do_query($table,$length,$numlines,$adult,$cat,$limit,$lang,$pattern,$regex,$equal) {
51   global $db;
52   $rnd = mt_rand();
53   $r = [];
54
55   $typesql   = (($table)  ? " WHERE `category` = '$table' " : " WHERE 1 ");
56   $lengthsql = (($length) ? " AND LENGTH(`text`) < $length " : "" );
57
58   if($adult == 2)
59     $adultsql  = " AND offensive = 1 ";
60   elseif($adult == 1)
61     $adultsql = "";
62   else
63     $adultsql = " AND offensive = 0 ";
64
65
66   if($numlines)
67     $lengthsql .=
68     " AND (LENGTH(`text`) - LENGTH(REPLACE(`text`,\"\n\",\"\"))) <= $numlines ";
69
70   $langsql = " AND lang = '$lang' ";
71
72   $patsql = '';
73   if(strlen($pattern))
74     $patsql = " AND MATCH text AGAINST ('$pattern' IN BOOLEAN MODE) ";
75
76   $regexsql = '';
77   if(strlen($regex))
78     $regexsql = " AND text REGEXP '$regex' ";
79
80   $eqsql = '';
81
82   if($equal) {
83     $catsavail = [];
84     $res = @$db->query("SELECT DISTINCT ( `category` ) FROM `fortune`
85                            $typesql
86                            $adultsql
87                            $lengthsql
88                            $langsql
89                            $patsql
90                            $regexsql ");
91     if($res->num_rows) {
92       while($x = $res->fetch_array(MYSQL_ASSOC))
93         $catsavail[] = $x['category'];
94
95       $eqsql = " AND `category` = '"
96         . $catsavail[mt_rand(0,$res->num_rows - 1)] . "' ";
97    }
98   }
99
100   $result = @$db->query("SELECT `text`, `category` FROM `fortune`
101                          $typesql
102                          $adultsql
103                          $lengthsql
104                          $langsql
105                          $patsql
106                          $regexsql
107                          $eqsql
108                          ORDER BY RAND($rnd)
109                          LIMIT $limit");
110
111   if($result->num_rows) {
112     while($x = $result->fetch_array(MYSQL_ASSOC))
113       $r[] = fortune_to_html($x['text'])
114         .(($cat) ? "<br />[{$x['category']}]<br />" : "");
115   }
116   return $r;
117 }
118
119
120 function do_stats($table,$length,$numlines,$adult,$cat,$limit,$lang,$pattern,$regex,$equal) {
121   global $db;
122   $rnd = mt_rand();
123   $r = [];
124
125   $typesql   = (($table)  ? " WHERE `category` = '$table' " : " WHERE 1 ");
126   $lengthsql = (($length) ? " AND LENGTH(`text`) < $length " : "" );
127
128   if($adult == 2)
129     $adultsql  = " AND offensive = 1 ";
130   elseif($adult == 1)
131     $adultsql = "";
132   else
133     $adultsql = " AND offensive = 0 ";
134
135
136   if($numlines)
137     $lengthsql .=
138     " AND (LENGTH(`text`) - LENGTH(REPLACE(`text`,\"\n\",\"\"))) <= $numlines ";
139
140   $langsql = " AND lang = '$lang' ";
141
142   $patsql = '';
143   if(strlen($pattern))
144     $patsql = " AND MATCH text AGAINST ('$pattern' IN BOOLEAN MODE) ";
145
146   $regexsql = '';
147   if(strlen($regex))
148     $regexsql = " AND text REGEXP '$regex' ";
149
150   $eqsql = '';
151
152   $result = @$db->query("SELECT `text`, `category` FROM `fortune`
153                          $typesql
154                          $adultsql
155                          $lengthsql
156                          $langsql
157                          $patsql
158                          $regexsql
159                          $eqsql");
160
161
162    echo '<br />' . $result->num_rows . ' matching quotations.<br />';
163
164
165    $res = @$db->query("SELECT DISTINCT ( `category` ) FROM `fortune`
166                            $typesql
167                            $adultsql
168                            $lengthsql
169                            $langsql
170                            $patsql
171                            $regexsql ");
172     if($res->num_rows) {
173       echo '<br />Matching Databases:<br />';
174       while($x = $res->fetch_array(MYSQL_ASSOC))
175         echo $x['category'].'<br />';
176
177    }
178    else
179      echo '<br />No matching databases using those search parameters - please refine your options.<br />';
180
181
182 }
183
184
185 function fortune_to_html($s) {
186
187   // First pass - escape all the HTML entities, and while we're at it
188   // get rid of any MS-DOS end-of-line characters and expand tabs to
189   // 8 non-breaking spaces, and translate linefeeds to <br />.
190   // We also get rid of ^G which used to sound the terminal beep or bell
191   // on ASCII terminals and were humourous in some fortunes.
192   // We could map these to autoplay a short sound file but browser support
193   // is still sketchy and then there's the issue of where to locate the
194   // URL, and a lot of people find autoplay sounds downright annoying.
195   // So for now, just remove them.
196
197   $s = str_replace(
198     ["&",
199           "<",
200           ">",
201           '"',
202           "\007",
203           "\t",
204           "\r",
205           "\n"],
206
207     ["&amp;",
208           "&lt;",
209           "&gt;",
210           "&quot;",
211           "",
212           "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;",
213           "",
214           "<br />"],
215     $s);
216   // Replace pseudo diacritics
217   // These were used to produce accented characters. For instance an accented
218   // e would have been encoded by '^He - the backspace moving the cursor
219   // backward so both the single quote and the e would appear in the same
220   // character position. Umlauts were quite clever - they used a double quote
221   // as the accent mark over a normal character.
222
223   $s = preg_replace("/'\010([a-zA-Z])/","&\\1acute;",$s);
224   $s = preg_replace("/\&quot;\010([a-zA-Z])/","&\\1uml;",$s);
225   $s = preg_replace("/\`\010([a-zA-Z])/","&\\1grave;",$s);
226   $s = preg_replace("/\^\010([a-zA-Z])/","&\\1circ;",$s);
227   $s = preg_replace("/\~\010([a-zA-Z])/","&\\1tilde;",$s);
228
229   // Ignore multiple underlines for the same character. These were
230   // most useful when sent to a line printer back in the day as it
231   // would type over the same character a number of times making it
232   // much darker (e.g. bold). I think there are only one or two
233   // instances of this in the current (2008) fortune cookie database.
234
235   $s = preg_replace("/(_\010)+/","_\010",$s);
236   // Map the characters which sit underneath a backspace.
237   // If you can come up with a regex to do all of the following
238   // madness  - be my guest.
239   // It's not as simple as you think. We need to take something
240   // that has been backspaced over an arbitrary number of times
241   // and wrap a forward looking matching number of characters in
242   // HTML, whilst deciding if it's intended as an underline or
243   // strikeout sequence.
244
245   // Essentially we produce a string of '1' and '0' characters
246   // the same length as the source text.
247   // Any position which is marked '1' has been backspaced over.
248
249   $cursor = 0;
250   $dst = $s;
251   $bs_found = false;
252   for($x = 0; $x < strlen($s); $x ++) {
253     if($s[$x] == "\010" && $cursor) {
254       $bs_found = true;
255       $cursor --;
256       $dst[$cursor] = '1';
257       $dst[$x] = '0';
258       $continue;
259     }
260     else {
261       if($bs_found) {
262         $bs_found = false;
263         $cursor = $x;
264       }
265       $dst[$cursor] = '0';
266       $cursor ++;
267     }
268
269   }
270
271   $out = '';
272   $strike = false;
273   $bold = false;
274
275   // Underline sequence, convert to bold to avoid confusion with links.
276   // These were generally used for emphasis so it's a reasonable choice.
277   // Please note that this logic will fail if there is an underline sequence
278   // and also a strikeout sequence in the same fortune.
279
280   if(strstr($s,"_\010")) {
281     $len = 0;
282     for($x = 0; $x < strlen($s); $x ++) {
283       if($dst[$x] == '1') {
284         $len ++;
285         $bold = true;
286       }
287       else {
288         if($bold) {
289           $out .= '<strong>';
290           while($s[$x] == "\010")
291              $x ++;
292           $out .= substr($s,$x,$len);
293           $out .= '</strong>';
294           $x = $x + $len - 1;
295           $len = 0;
296           $bold = false;
297         }
298         else
299           $out .= $s[$x];
300       }
301     }
302   }
303
304   // These aren't seen very often these days - simulation of
305   // backspace/replace. You could occasionally see the original text
306   // on slower terminals before it got replaced. Once modems reached
307   // 4800/9600 baud in the late 70's and early 80's the effect was
308   // mostly lost - but if you find a really old fortune file you might
309   // encounter a few of these.
310
311   else {
312     for($x = 0; $x < strlen($s); $x ++) {
313       if($dst[$x] == '1') {
314         if($strike)
315           $out .= $s[$x];
316         else
317           $out .= '<strike>'.$s[$x];
318         $strike = true;
319       }
320       else {
321         if($strike)
322           $out .= '</strike>';
323         $strike = false;
324         $out .= $s[$x];
325       }
326     }
327   }
328
329   // Many of the underline sequences are also wrapped in asterisks,
330   // which was yet another way of marking ASCII as 'bold'.
331   // So if it's an underline sequence, and there are asterisks
332   // on both ends, strip the asterisks as we've already emboldened the text.
333
334   $out = preg_replace('/\*(<strong>[^<]*<\/strong>)\*/',"\\1",$out);
335
336   // Finally, remove the backspace characters which we don't need anymore.
337
338   return str_replace("\010","",$out);
339 }
340
341 $result1 = do_query($table,$length,$numlines,$adult,$cat,1,$lang,$pattern,$regex,$equal);
342
343 if(count($result1))
344   echo $result1[0];
345
346 if($stats)
347   do_stats($table,$length,$numlines,$adult,$cat,1,$lang,$pattern,$regex,$equal);
348
349