-
Notifications
You must be signed in to change notification settings - Fork 0
/
gopherserversmf.php
799 lines (592 loc) · 18.5 KB
/
gopherserversmf.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
<?php
/*
* Gopher for SMF
* by: vbgamer45
* https://wwww.smfhacks.com
* https://github.com/VBGAMER45/gopherserversmf
* Licensed: under MIT
*/
// Notes For SMF 2.0.x and SMF 2.1.x requires MySQLI, sockets enabled in PHP
set_time_limit(0);
// Constants to adjust
// Gopher Bind address either an IP or DOMAIN -
define("GOPHER_BINDADDRESS","127.0.0.1");
define("GOPHER_PORT","70");
// Database
define("SMF_DB_SERVER",'localhost');
define("SMF_DB",'smf');
define("SMF_DB_USERNAME",'smfuser');
define("SMF_DB_PASSWORD", '');
define("SMF_DB_PREFIX",'smf_');
// Site url
define("SITE_TITLE",'MY SMF Forum');
define("SITE_URL",'https://myforum.com');
// Display debugging information
define("DEBUG_MODE",1);
if (DEBUG_MODE)
{
error_reporting(E_ALL);
ini_set("display_errors",1);
}
ob_implicit_flush();
$db = '';
$gopherClient = array();
// nad0r1 at hush dot ai
// Based on https://www.php.net/manual/en/function.socket-read.php#79314
if (($sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP)) === false)
{
echo "socket_create() failed " . socket_strerror(socket_last_error()) . "\n";
}
// set the option to reuse the port
socket_set_option($sock, SOL_SOCKET, SO_REUSEADDR, 1);
if (socket_bind($sock,GOPHER_BINDADDRESS, GOPHER_PORT) === false)
{
echo "socket_bind() failed: " . socket_strerror(socket_last_error($sock)) . "\n";
}
if (socket_listen($sock, 5) === false)
{
echo "socket_listen() failed" . socket_strerror(socket_last_error($sock)) . "\n";
}
//clients array
$clients = array();
$clientLastTime = array();
do {
$read = array();
$read[] = $sock;
$write = NULL;
$except = NULL;
$tv_sec = 5;
$read = array_merge($read,$clients);
// Set up a blocking call to socket_select
if(socket_select($read,$write, $except, $tv_sec) < 1)
{
// SocketServer::debug("Problem blocking socket_select?");
continue;
}
// Handle new Connections
if (in_array($sock, $read)) {
if (($msgsock = socket_accept($sock)) === false) {
echo "socket_accept() failed: " . socket_strerror(socket_last_error($sock)) . "\n";
break;
}
else
{
$peerAddress = '';
$peerPort = '';
socket_getpeername($msgsock,$peerAddress,$peerPort);
echo 'New Client: ' . $peerAddress . "\n";
}
$found = 0;
foreach($clients as $key => $tmp)
{
if (!isset($clients[$key]))
{
$clients[$key] = $msgsock;
$found = 1;
echo 'Reusing Client: ' . $key . "\n";
}
}
if ($found == 0)
$clients[] = $msgsock;
}
// $i = 0;
// Handle Input
foreach ($clients as $key => $client) { // for each client
$closeSocket = 0;
/*
if (!empty($clientLastTime[$key]) && ($clientLastTime[$key]+ 60) > time())
{
echo "Closing Client: $key";
unset($gopherClient[$key]);
unset($clients[$key]);
socket_close($client);
continue;
}
*/
if (in_array($client, $read)) {
if (false === ($buf = socket_read($client, 2048, PHP_BINARY_READ))) {
echo "socket_read() failed: " . socket_strerror(socket_last_error($client)) . "\n";
//break 2;
unset($gopherClient[$key]);
unset($clients[$key]);
socket_close($client);
continue;
}
if (!$buf = trim($buf)) {
// continue;
}
// Not used by gopher just for use in console apps.
if ($buf == 'quit') {
unset($clients[$key]);
socket_close($client);
break;
}
// Output for console
echo "Client: $key Gopher: $buf\n";
$buf = trim($buf);
$clientLastTime[$key] = time();
if (empty($gopherClient[$key]))
{
$gopherClient[$key] = new Gopher_Server();
$gopherClient[$key]->setHostname(GOPHER_BINDADDRESS);
$gopherClient[$key]->setPort(GOPHER_PORT);
}
$tokens = explode("\t",$buf);
$tokenParts =explode('/',$tokens[0]);
if (!isset($tokenParts[1]))
$tokenParts[1] = '';
if (DEBUG_MODE)
{
print_r($tokenParts);
echo 'After Split: ' . '/' . $tokenParts[1] . "\n";
}
if ($tokenParts[1] == 'caps.txt')
{
echo 'FOUND CAPS';
// Show text file
$fileData = file_get_contents(dirname(__FILE__).'/caps.txt');
$fileData .= chr(32) . "\r\n". "." . "\r\n" . chr(0);
socket_write($client, $fileData, strlen($fileData));
$closeSocket = 1;
echo 'Closing Socket: ' . $key;
socket_shutdown($client,1);
socket_close($client);
unset($gopherClient[$key]);
unset($clients[$key]);
break;
}
$tokens[0] = '/' . $tokenParts[1];
// Display the Main Listing
if ($tokens[0] == '/' || $tokens[0] == '/forums' || empty($tokens[0]))
{
// Show forum boards!!
$db = ConnectDB();
$db_prefix = SMF_DB_PREFIX;
$gopherClient[$key]->WriteDirectory("Return " . SITE_TITLE . " - Home","/");
$gopherClient[$key]->WriteText("---------------------------------------------------------");
$gopherClient[$key]->WriteHTMLLink(SITE_URL,SITE_URL);
$gopherClient[$key]->WriteText("---------------------------------------------------------");
$typeDisplay = $tokenParts[2];
if (empty($typeDisplay))
{
// Show categories
$request1 = sitequery("SELECT
c.ID_CAT, c.cat_order, c.name
FROM {$db_prefix}categories AS c
ORDER BY c.cat_order ASC", $db);
while ($row1 = mysqli_fetch_assoc($request1))
{
$catid = $row1['ID_CAT'];
$request2 = sitequery("SELECT
b.name, b.num_posts, b.ID_BOARD, b.ID_CAT, b.child_level, b.ID_PARENT, b.board_order
FROM {$db_prefix}boards AS b
WHERE (FIND_IN_SET(-1, b.member_groups) != 0) AND $catid = b.ID_CAT Order by b.board_order asc
", $db);
$b_count = mysqli_affected_rows($db);
if ($b_count !=0)
{
$gopherClient[$key]->WriteText("*****************************************************");
$gopherClient[$key]->WriteText($row1['name']);
$gopherClient[$key]->WriteText("*****************************************************");
// List the forums and subforums
while ($row2 = mysqli_fetch_assoc($request2))
{
$gopherClient[$key]->WriteDirectory($row2['name'],"/forums/b/" . $row2['ID_BOARD']);
$gopherClient[$key]->WriteText("Total Posts: " . $row2['num_posts']);
}
}
}
}
// Topic listing and sub boards
if ($typeDisplay == 'b')
{
$boardid = (int) $tokenParts[3];
$start = 0;
if (!empty($tokenParts[4]))
$start = (int) $tokenParts[4];
$request = sitequery("
SELECT
b.name, b.num_topics
FROM {$db_prefix}boards AS b
WHERE b.ID_BOARD = $boardid AND (FIND_IN_SET(-1, b.member_groups) != 0)", $db);
$row = mysqli_fetch_assoc($request);
if (mysqli_num_rows($request) == 0)
$gopherClient[$key]->WriteText('The topic or board you are looking for appears to be either missing or off limits to you');
else
{
$totalResult = sitequery("SELECT
count(*) as total
FROM {$db_prefix}messages AS m, {$db_prefix}topics AS t
WHERE m.ID_BOARD = $boardid AND m.ID_MSG = t.ID_FIRST_MSG",$db);
$totalRow = mysqli_fetch_assoc($totalResult);
$totalRecords = $totalRow['total'];
$totalPages = $totalRecords / 10;
$startpos = ($start * 10);
// Lets show the board
$request2 = sitequery("
SELECT
m.subject, t.ID_TOPIC, t.num_replies
FROM {$db_prefix}messages AS m, {$db_prefix}topics AS t
WHERE m.ID_BOARD = $boardid AND m.ID_MSG = t.ID_FIRST_MSG
ORDER BY t.ID_LAST_MSG DESC
LIMIT $startpos,10",$db);
$i = 0;
while($row2 = mysqli_fetch_assoc($request2))
{
$i++;
$gopherClient[$key]->WriteDirectory($row2['subject'],"/forums/p/" . $row2['ID_TOPIC']);
$gopherClient[$key]->WriteText($row2['num_replies'] . ' replies');
}
$gopherClient[$key]->WriteText("*****************************************************");
// Show previous page
if ($start > 1)
{
$gopherClient[$key]->WriteDirectory("Previous Page","/forums/b/$boardid/" . ($start - 1));
}
if ($totalPages > 1 && $start < $totalPages)
{
if ($start == 0)
$start = 1;
$gopherClient[$key]->WriteDirectory("Next Page","/forums/b/$boardid/" . ($start + 1));
}
}
}
// View Post
if ($typeDisplay == 'p')
{
$topicid = (int) $tokenParts[3];
$start = 0;
if (!empty($tokenParts[4]))
$start = (int) $tokenParts[4];
$request = sitequery("
SELECT
m.subject, t.num_replies, b.name, b.ID_BOARD, m.ID_BOARD
FROM ({$db_prefix}messages AS m, {$db_prefix}topics AS t,
{$db_prefix}boards AS b)
WHERE b.ID_BOARD = m.ID_BOARD AND t.ID_TOPIC = $topicid AND m.ID_MSG = t.ID_FIRST_MSG AND (FIND_IN_SET(-1, b.member_groups) != 0)",$db);
$row = mysqli_fetch_assoc($request);
if (mysqli_num_rows($request) == 0)
$gopherClient[$key]->WriteText('The topic or board you are looking for appears to be either missing or off limits to you');
else
{
$totalResult = sitequery("SELECT
count(*) as total
FROM {$db_prefix}messages AS m
LEFT JOIN {$db_prefix}boards AS b ON(b.ID_BOARD = m.ID_BOARD)
WHERE m.ID_TOPIC = $topicid AND (FIND_IN_SET(-1, b.member_groups) != 0)",$db);
$totalRow = mysqli_fetch_assoc($totalResult);
$totalRecords = $totalRow['total'];
$totalPages = $totalRecords / 10;
$startpos = ($start * 10);
// Get all posts in a topic
$request2 = sitequery("
SELECT
m.subject, m.poster_name, m.body, m.poster_time, m.ID_MSG
FROM {$db_prefix}messages AS m
LEFT JOIN {$db_prefix}boards AS b ON(b.ID_BOARD = m.ID_BOARD)
WHERE m.ID_TOPIC = $topicid AND (FIND_IN_SET(-1, b.member_groups) != 0) ORDER BY m.ID_MSG ASC LIMIT $start,10", $db);
while ($row2 = mysqli_fetch_assoc($request2))
{
$gopherClient[$key]->WriteText("#Post#: " . $row2['ID_MSG'] . "--------------------------------------------------");
$gopherClient[$key]->WriteText($row2['subject']);
$gopherClient[$key]->WriteText('By: ' . $row2['poster_name'] . ' Date: ' . date("F j, Y, g:i a",$row2['poster_time']));
$gopherClient[$key]->WriteText("---------------------------------------------------------");
$row2['body'] = replaceBBcodes($row2['body']);
$lines = explode("<br />",$row2['body']);
foreach($lines as $line)
{
$line = wordwrap($line,64,"<br />",false);
// Start of link code
$reg_exUrl = "/(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/";
preg_match_all($reg_exUrl, $line, $matches);
$usedPatterns = array();
foreach ($matches[0] as $pattern)
{
if (!array_key_exists($pattern, $usedPatterns))
{
$usedPatterns[$pattern] = true;
$line = str_replace($pattern, "<br />$pattern<br />", $line);
// $tmp = explode('\n',$line);
//foreach($tmp as $line2);
}
}
$splitLine = explode("<br />",$line);
foreach($splitLine as $tmpLine)
{
if (!empty($tmpLine))
{
$tmpLine = trim($tmpLine);
if (substr_count($tmpLine,"http://") > 0 || substr_count($tmpLine,"https://"))
{
$gopherClient[$key]->WriteHTMLLink($tmpLine,$tmpLine);
}
else
$gopherClient[$key]->WriteText($tmpLine);
}
}
}
}
$gopherClient[$key]->WriteText("*****************************************************");
// Show previous page
if ($start > 1)
{
$gopherClient[$key]->WriteDirectory("Previous Page", "/forums/p/$topicid/" . ($start - 1));
}
if ($totalPages > 1 && $start < $totalPages)
{
if ($start == 0)
$start = 1;
$gopherClient[$key]->WriteDirectory("Next Page", "/forums/p/$topicid/" . ($start + 1));
}
}
}
$response = $gopherClient[$key]->ReturnResponse();
socket_write($client, $response, strlen($response));
$closeSocket = 1;
}
else
{
$gopherClient[$key]->WriteDirectory(SITE_TITLE . " - Home","/");
$gopherClient[$key]->WriteText("---------------------------------------------------------");
$gopherClient[$key]->WriteText("Nothing found here. Is Earl here?????");
$gopherClient[$key]->WriteText("---------------------------------------------------------");
$response = $gopherClient[$key]->ReturnResponse();
socket_write($client, $response, strlen($response));
$closeSocket = 1;
}
if ($closeSocket == 1)
{
echo 'Closing Socket: ' . $key;
socket_shutdown($client,1);
socket_close($client);
unset($gopherClient[$key]);
unset($clients[$key]);
}
}
}
} while (true);
socket_close($sock);
function ConnectDB()
{
global $db;
$db = mysqli_connect(SMF_DB_SERVER, SMF_DB_USERNAME, SMF_DB_PASSWORD, SMF_DB) or die("Unable to connect to database!");
return $db;
}
function sitequery($query,$link)
{
global $db;
if (empty($link))
$link = $db;
$result = mysqli_query($link,$query);
return $result;
}
class Gopher_Server {
/*
by: evert https://github.com/evert/PHPGopherServer
Modified by vbgamer45
Licensed under MIT.
A blogpost with more information can be found here:
http://www.rooftopsolutions.nl/blog/100
*/
/**
* hostname of this server
*
* @var string
*/
private $hostname = '';
private $dataItems = array();
/**
* default port
*
* @var int
*/
private $port = 70;
/**
* ASCII based textfile
*/
const G_TEXTFILE = '0';
/**
* Directory
*/
const G_DIRECTORY = '1';
/**
* CSO phonebook (old and unsupported protocol)
*/
const G_CSO = '2';
/**
* Error message (unsupported)
*/
const G_ERROR = '3';
/**
* Macintosh binhex file
*/
const G_MACFILE = '4';
/**
* MS-DOS binary
*/
const G_DOSFILE = '5';
/**
* Unix UUEncoded file
*/
const G_UUENCODED = '6';
/**
* Link to a search service
*/
const G_SEARCH = '7';
/**
* Link to a telnet server
*/
const G_TELNET = '8';
/**
* Unix binary file
*/
const G_BINARY = '9';
/**
* Redundant server (unsupported)
*/
const G_REDUNDANTSERVER = '+';
/**
* Link to a TN3270 terminal (unsupported)
*/
const G_TN3270 = 'T';
/**
* Link to a GIF image
*/
const G_GIF = 'g';
/**
* Link to any other image
*/
const G_IMAGE = 'I';
/**
* In-line informational text
*/
const G_TEXT = 'i';
/**
* HTML file
*/
const G_HTML = 'h';
/**
* Set the hostname (required!)
*
* @param string $hostname
* @return void
*/
public function setHostName($hostname)
{
$this->hostname = $hostname;
}
public function setPort($port)
{
$this->port = $port;
}
function ReturnResponse()
{
$data = $this->encodeResponse($this->dataItems);
// clear response
$this->dataItems = array();
return $data . "\r\n";
}
public function WriteText($text)
{
if (strlen($text) > 64)
{
$tmp = str_split($text,64);
foreach($tmp as $line)
{
$this->dataItems[] = array(self::G_TEXT, $line);
}
}
else
$this->dataItems[] = array(self::G_TEXT, $text);
}
public function WriteDirectory($title,$location)
{
if (strlen($title) > 64)
{
$title = substr($title,0,62) . '...';
}
$this->dataItems[] = array(self::G_DIRECTORY, $title, $location);
}
public function WriteSearch($title,$location)
{
if (strlen($title) > 64)
{
$title = substr($title,0,62) . '...';
}
$this->dataItems[] = array(self::G_SEARCH, $title, $location);
}
public function WriteHTMLLink($title,$location)
{
$location = "URL:" . $location;
$this->dataItems[] = array(self::G_HTML, $title, $location);
}
/**
* encode the response in a gopher format
*
* @param array $data
* @return string
*/
public function encodeResponse($data)
{
$raw = '';
foreach($data as $item)
{
// here we gather information about an item and fill in the missing fields
$type = $item[0];
$title = $item[1];
$location = isset($item[2])?$item[2]:$title;
$server = isset($item[3])?$item[3]:$this->hostname;
$port = isset($item[4])?$item[4]:$this->port;
switch($type)
{
// If the type is text, we will leave the other items empty
case self::G_TEXT :
$location = 'fake';
$server = '(NULL)';
$port = '0';
break;
}
// The tab-seperated directory item
$raw.=$type . $title . "\t" . $location . "\t" . $server . "\t" . $port . "\n";
}
// A dot on the end of the request
$raw.=".";
return $raw;
}
}
function un_htmlspecialchars($string)
{
// SMF 2.0.17 BSD
static $translation;
if (!isset($translation))
$translation = array_flip(get_html_translation_table(HTML_SPECIALCHARS, ENT_QUOTES)) + array(''' => '\'', ' ' => ' ');
return strtr($string, $translation);
}
function replaceBBcodes($text)
{
$text = un_htmlspecialchars($text);
// BBcode array
$find = array(
'~\[b\](.*?)\[/b\]~s',
'~\[i\](.*?)\[/i\]~s',
'~\[u\](.*?)\[/u\]~s',
'~\[size=([^"><]*?)\](.*?)\[/size\]~s',
'~\[color=([^"><]*?)\](.*?)\[/color\]~s',
'~\[url=((?:ftp|https?)://[^"><]*?)\](.*?)\[/url\]~s',
'~\[url\]((?:ftp|https?)://[^"><]*?)\[/url\]~s',
'~\[img width=(0-9*) height=(0-9*)\](https?://[^"><]*?\.(?:jpg|jpeg|gif|png|bmp))\[/img\]~s',
'~\[img\](https?://[^"><]*?\.(?:jpg|jpeg|gif|png|bmp))\[/img\]~s',
);
$replace = array(
'$1', //b
'$1', //i
'$1', //u
'$2', // size
'$2', // olor
'$2<br />$1', //url=
'$1', // url
'$3', //img
'$1',
);
return preg_replace($find, $replace, $text);
}