-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathphoenix.php
executable file
·2349 lines (2018 loc) · 79.3 KB
/
phoenix.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
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/php
<?php
/*
(c) 2022 Chris Royle
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
$hostname = gethostname();
include_once "conf.php";
$options = getopt("n:a:dhfc", array("node:", "as-host:", "debug", "help", "no-fork", "console"));
if (isset($options['h']) or isset($options['help']))
{
fprintf (STDERR, "%s:
-n <nodespec> (--node) Run only on specified node numbers (see node table)
Default if not specified: all nodes
-a <hostname> (--as-host) Run as if our local hostname was <hostname>
-c (--console) Run on stdin/stdout. Must specify -n with single node.
-d (--debug) Turn on debugging to standard output (implies -f)
-h (--help) Display this help message and exit\n\n
<nodespec> (N | N-N)+ (individual node ids, or a range)\n\n",
$argv[0]);
exit();
}
$debug_flag = false;
$no_fork = false;
if (isset($options['d']) or isset($options['debug'])) {
$debug_flag = true;
$no_fork = true;
}
if ($debug_flag)
printf ("System hostname: %s\n", $hostname);
$final_nodes = array();
if (isset($options['a']) or isset($options['as-host']))
if (!isset($options['a']))
$hostname=$options['as-host'];
else $hostname=$options['a'];
$queryadd = "not";
$likestring = '^/';
if (isset($options['c']) or isset($options['console'])) // Only want ports beginning '/'
{
$queryadd = "";
$likestring = posix_ttyname(STDIN);
}
$r = dbq("select * from node where ? rlike node_host and node_port $queryadd rlike '$likestring' order by node_id asc", "s", $hostname);
if ($r['result'])
{
while ($data = @mysqli_fetch_assoc($r['result']))
$final_nodes[$data['node_id']] = $data['node_port'];
@mysqli_free_result($r['result']);
}
else
{
print "Cannot load list of nodes (".mysqli_error($dbh)."). Quitting.\n";
exit();
}
if (isset($options['n']) or isset($options['node']))
{
if (!isset($options['n']))
$options['n'] = $options['node'];
debug ("Found node option - node ".$options['n']);
// Parse node list
$particular_nodes = explode(',', $options['n']);
// Split each array element if it has the format A-B (range)
$final_nodes_tmp = array();
foreach ($particular_nodes as $pn)
{
if (preg_match('/^\d+$/', $pn) && array_key_exists($pn, $final_nodes))
$final_nodes_tmp[$pn] = $final_nodes[$pn];
else if (preg_match('/^(\d+)\-(\d+)$/', $pn, $matches))
{
$start = $matches[1]; $end = $matches[2];
for ($count = $start; $count <= $end; $count++)
if (array_key_exists($count, $final_nodes))
$final_nodes_tmp[$count] = $final_nodes[$count];
}
}
$final_nodes = $final_nodes_tmp;
}
if (sizeof($final_nodes) == 0)
{
print "No nodes identified to run.\n\n";
exit();
}
if (sizeof($final_nodes) > 1 && (isset($options['c']) or isset($options['console'])))
{
print "Set to console operation, but more than one node selected. Try -n ...?\n";
exit();
}
foreach ($final_nodes as $node_id => $node_port)
{
if (sizeof($final_nodes) > 1) // Need to fork
$pid = pcntl_fork();
else $pid = 0; // Pretend we are the child
if ($pid && ($pid == -1))
{
print "pcntl_fork() failed on creating node $node_id\n. Quitting.\n";
exit();
}
if (!$pid) // Child
{
open_db(); // Re-open DB
$r = dbq("select * from node where node_id = ?", "d", $node_id);
if ($r['numrows'] == 0)
{
@mysqli_free_result($r['result']);
print "Cannot find node $node_id in database. Quitting.\n";
exit();
}
else
{
$data = @mysqli_fetch_assoc($r['result']);
@mysqli_free_result($r['result']);
break; // Escape the loop
}
}
}
if ($pid) // We were parent on exit from the loop
{
$status = 0;
pcntl_wait($pid, $status);
exit();
}
$port_data = $data;
$portpres = ($port_data['node_portpres'] ? $port_data['node_portpres'] : $port_data['node_port']);
$port = $port_data['node_port'];
// Initialise socket - if we are not operating on console
$sock = false;
if (!(isset($options['c']) or isset($options['console'])))
{
if (preg_match('/^\//', $port)) // Device - die.
exit();
while (!$sock) // Wait for socket to be free
{
#$sock = @socket_create_listen($port);
#if (!$sock) sleep(1);
if (($sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP)) == false)
{
print "Cannot create socket: ".socket_strerror(socket_last_error())."\n"; exit();
}
if (!socket_set_option($sock, SOL_SOCKET, SO_REUSEADDR, 1))
{
print "Cannot set socket option: ".socket_strerror(socket_last_error())."\n"; exit();
}
if (socket_bind($sock, '0.0.0.0', $port) == false)
{
print "Cannot bind socket: ".socket_strerror(socket_last_error())."\n"; exit();
}
if (!socket_listen($sock, 5))
{
print "Cannot listen on socket: ".socket_strerror(socket_last_error())."\n"; exit();
}
}
}
else
{
$sock = fopen("/dev/tty", "r+");
}
// Get configuration
$config = array();
$r = dbq("select config_var, config_val from config");
while ($row = @mysqli_fetch_assoc($r['result']))
{
$config[$row['config_var']] = $row['config_val'];
}
@mysqli_free_result($r['result']);
// Clear down all nodes
//dbq("update node set user_id=null where node_port = ?", "i", $port);
debug("Listening on port ".$port);
// Instance user information
$user_id = false;
include_once ("editor.php");
include_once ("response.php"); // Response frame handler
include_once ("ip_lib.php"); // IP communications library
// send_frame_title_userdata
// Do what send_frame_title does but from the userdata object
function send_frame_title_userdata ()
{
global $userdata;
ser_output_conn(VCLS.VCURSOROFF);
$frame_no_colour = VTYEL;
if ($userdata->preview)
$frame_no_colour = VTRED;
if ($userdata->editing) // The if for editing comes second because preview is always on if editing
$frame_no_colour = VTBLU;
$frame_ip_header = $userdata->frame_data["ip_header"];
$frame_pageno = $userdata->frame_current;
//if (isset($userdata->frame_data['frame_displaynumber']))
//$frame_pageno = $userdata->frame_data['frame_displaynumber'];
//else
//$frame_pageno = $userdata->frame_data["frame_pageno"].$userdata->frame_data["frame_subframeid"];
$frame_time = date("H:i");
if ((!$userdata->preview) && (!$userdata->editing))
{
if (preg_match('/hide_ip/', $userdata->frame_data['frame_flags'])) // I.e. we are not hiding the IP
$frame_ip_header="";
if (preg_match('/hide_time/', $userdata->frame_data['frame_flags'])) // I.e. not hiding the time
$frame_time="";
if (preg_match('/hide_frame_id/', $userdata->frame_data['frame_flags'])) // I.e. not hiding the frame ID
$frame_pageno="";
}
ser_output_conn(sprintf("%- 19s".$frame_no_colour."%10s ".VTWHT."%5s", $frame_ip_header, $frame_pageno, $frame_time));
// Some 80's style computation delay
eighties_delay(0.7);
}
// transplant data
// Put substituted variables into a line of frame data
function transplant_data($myline, $pos, $str, $padlen, $centre = false)
{
$str = trim($str);
$str = substr($str, 0, $padlen); // Truncate if necessary
if ($centre)
$skip = intval(($padlen - strlen($str))/2);
else $skip = 0;
$str = str_repeat(' ', $skip).$str.str_repeat(' ', ($padlen - strlen($str) - $skip));
if ($pos + strlen($str) > 39)
$str = substr($str, 0, 39-$pos); // Make sure we don't go over the line
/* if ($centre)
{
$skip = intval(($padlen - strlen($str))/2);
if ($skip > 0)
{
for ($counter = $pos; $counter <= $pos+$skip; $counter++)
$myline[$counter] = chr(32);
$pos = $pos + $skip;
}
}
else $skip = 0;
*/
for ($counter = 0; $counter < strlen($str); $counter++)
$myline[$pos+$counter] = $str[$counter];
/*
if (($skip + strlen($str)) < $padlen)
for ($counter = $pos+strlen($str)+$skip; $counter <= $pos+$padlen; $counter++)
if (($counter) <= 39)
$myline[$counter] = chr(32);
*/
return $myline;
}
function send_frame_userdata($startbyte = 0, $allow_keys = true)
{
global $userdata;
// Deliver here
// Split into 40-character lines
$frame_data = $userdata->frame_data["frame_content"];
// Calculate valid routes
$keys = "".implode("", array_keys($userdata->frame_routes));
$keys = VDKEYSTAR.VDKEYENTER.$keys;
if ($userdata->is_msg_reading)
$keys = $keys."udUD0"; // Allows unread, delete, return to index
$ret = array(TX_OK, $frame_data, 880);
$framelines = intval(strlen($frame_data) / 40);
if (strlen($frame_data) > 0)
$framelines++;
$userdata->frame_displayed = 0;
if ($startbyte == 0)
{
$start_row = 1;
$start_char = 0;
}
else
{
$start_row = intval($startbyte/40)+1;
$start_char = ($startbyte % 40);
goto_xy($userdata->conn, $start_char, $start_row);
}
if ($userdata->tx_baud == $userdata->rx_baud)
$baud_rate = $userdata->tx_baud." baud";
else
$baud_rate = $userdata->tx_baud."/".$userdata->rx_baud;
$framevars = array(
"NODENAME" => array($userdata->node_name, 15),
"SPEED" => array($baud_rate, 9),
"USERID" => array($userdata->user_id.userid_checkdigit($userdata->user_id), 7),
"REMOTEADDR" => array($userdata->remote_host, 38),
"REMOTEIP" => array($userdata->remote_addr, 15),
"RPRT" => array(trim(substr($userdata->remote_port,-5)), 5),
"USERNAME" => array($userdata->user_name ? $userdata->user_name : "", 25),
"LOGINTIME" => array(date("D d/m/Y H:i", $userdata->login_time), 20),
"LASTLOGIN" => array($userdata->previous_login_time, 19)
);
if ($userdata->is_msg_reading) // Populate @SENDER with source name and render the rest of the data, too
{
$framevars["SENDER"] = array($userdata->msg_data['user_realname'], 25);
$framevars["MSGDATE"] = array($userdata->msg_data['sent_time'], 19);
// Insert recipient, subject and msg text
// Look for recipient, subject and text in the response fields list
$recip_index = $subject_index = $text_index = null;
foreach ($userdata->frame_response as $v)
{
switch ($v['fr_fieldname'])
{
case 'USER':
$recip_index['start'] = $v['fr_start'] % 40;
$recip_index['length'] = $v['fr_end'] - $v['fr_start'] + 1;
$recip_index['frameline'] = intval($v['fr_end'] / 40) + 1;
break;
case 'SUBJECT':
$subject_index['start'] = $v['fr_start'] % 40;
$subject_index['length'] = $v['fr_end'] - $v['fr_start'] + 1;
$subject_index['frameline'] = intval($v['fr_end'] / 40) + 1;
break;
case 'TEXT':
$text_index['start_x'] = $v['fr_start'] % 40;
$text_index['start_y'] = intval($v['fr_start'] / 40) + 1;
$text_index['end_x'] = $v['fr_end'] % 40;
$text_index['lines'] = intval($v['fr_end'] / 40) + 1 - $text_index['start_y'] + 1;
$text_index['linelength'] = ($text_index['end_x'] % 40) - ($text_index['start_x'] % 40) + 1;
break;
}
}
}
else // in case we are on a sending screen, set it to our name
{
$framevars["SENDER"] = $framevars["USERNAME"];
$framevars["MSGDATE"] = array("Now", 19);
}
if ($userdata->is_msg_index)
{
// Populate up @n, @FROMn, @SUBJECTn, @DATEn here
for ($c = 0; $c < 5; $c++)
{
$displaynum = $c+1;
if (isset($userdata->msg_index_data[$c]))
{
$framevars[$displaynum] = array(sprintf("%01d", $c+1), 2);
$framevars["FROM".$displaynum] = array($userdata->msg_index_data[$c][0], 20); // Sender
$framevars["SUBJECT".$displaynum] = array($userdata->msg_index_data[$c][1], 29); // Subject
$framevars["DATE".$displaynum] = array($userdata->msg_index_data[$c][2].($userdata->msg_index_data[$c][3] == 'New' ? '*' : ' '), 6); // Date - flash for new
}
else
{
$framevars[$displaynum] = array("",2); // Blank out the numeric index variable
$framevars["FROM".$displaynum] = array("", 20); // Sender
$framevars["DATE".$displaynum] = array("", 6); // Date
$framevars["SUBJECT".$displaynum] = array("", 29); // Subject
}
}
}
else debug ("Not a message index frame - did not populate the index fields");
for ($frameline = $start_row; $frameline <= ($framelines+1); $frameline++)
{
// In case we have no straggling data, don't try and display if it doesn't exist
if ((40*($frameline-1)) <= strlen($frame_data))
{
$myline = substr($frame_data, (40*($frameline-1)), 40);
if (!$userdata->editing && preg_match('/framevars/', $userdata->frame_data["frame_flags"])) // Substitute frame variables
{
foreach ($framevars as $k => $v)
{
//if (($pos = strpos($myline, "@".$k)) or ($pos = strpos($myline, "\\".$k)))
//debug ("Transplanting $v[0] at $pos padded to $v[1]");
if ($pos = strpos($myline, "@".$k))
$myline = transplant_data($myline, $pos, $v[0], $v[1]);
else if ($pos = strpos($myline, "\\".$k))
$myline = transplant_data($myline, $pos, $v[0], $v[1], true);
}
}
// Transplant in any message reading stuff
if ($userdata->is_msg_reading && ($frameline == $recip_index['frameline']))
$myline = transplant_data($myline, $recip_index['start'], $userdata->msg_data['recip'], $recip_index['length']);
if ($userdata->is_msg_reading && ($frameline == $subject_index['frameline']))
$myline = transplant_data($myline, $subject_index['start'], $userdata->msg_data['msg_subject'], $subject_index['length']);
if ($userdata->is_msg_reading && ($frameline >= $text_index['start_y']) &&
($frameline < ($text_index['start_y'] + count($userdata->msg_data['wrapped_display']))))
$myline = transplant_data($myline, $text_index['start_x'], $userdata->msg_data['wrapped_display'][$frameline - $text_index['start_y']], $text_index['linelength']);
$myline = rtrim($myline);
if (($startbyte != 0) && ($frameline == $start_row))
if (strlen($myline) >= $start_char) // Start char is within the start line - i.e. it isn't in some space at the end
$myline = substr($myline, $start_char); // Balance of string to be output
else // Nothing to display - set to empty
$myline = "";
if (strlen($myline) == 0)
$ending="\n";
else if (strlen($myline) < 40) // If equal to 40, the cursor will wrap to the next line.
$ending = "\r\n";
else $ending = "";
$out_ret = ser_output_conn_keys ($myline.$ending, $allow_keys ? $keys : false); // Need to add keys when we've got them
if (($out_ret[0] == TX_HANGUP) or ($out_ret[0] == TX_OK_KEY))
{
$ret = array($out_ret[0], $out_ret[1], (($frameline-1)*40+($out_ret[2]-1)));
break;
}
}
}
$userdata->frame_displayed = $ret[2];
if (!$userdata->editing && preg_match('/disconnect/', $userdata->frame_data['frame_flags'])) // Disconnect on transmission complete
$ret[0] = TX_DISCONNECT;
return $ret;
}
// Load frame currently specified in $userdata
function load_frame_userdata()
{
global $userdata;
//return load_frame_data($userdata->frame_data["frame_pageno"], $userdata->frame_data["frame_subframeid"], $userdata->preview);
return load_frame_data(substr($userdata->frame_current, 0, -1), substr($userdata->frame_current, -1), $userdata->preview);
}
// is_dynamic
// Returns an array of useful stuff if the page number (i.e. all subframes) is dynamic
function is_dynamic ($page_no)
{
global $userdata;
debug ("Checking if $page_no is dynamic");
$ret = false;
#$query = "select dyn_start, dyn_end from dynamic where dyn_start <= ".$page_no." and dyn_end >= ".$page_no;
$r = dbq("select dyn_start, dyn_end from dynamic where dyn_start <= ? and dyn_end >= ?", "ii", $page_no, $page_no);
if ($r['result'])
{
if ($r['numrows'] == 1)
{
debug ("Page $page_no is dynamic.");
$ret = true;
}
@mysqli_free_result($r['result']);
}
return $ret;
}
function load_dynamic_ip_info($page_no)
{
global $userdata;
$ret = null;
//$query = "select ip_id, ip_header, LENGTH(ip_base) as ip_base_len from information_provider where left(?, IF(ip_base=0, 0, LENGTH(ip_base))) = if(ip_base=0, '', ip_base) AND LENGTH(?) >= LENGTH(ip_base) order by ip_base_len DESC LIMIT 1";
//$r = dbq($query, "ss", strval($page_no), strval($page_no));
$query = "select ip_id, ip_header, LENGTH(ip_base) as ip_base_len,user_id from information_provider where ? RLIKE concat(ip_base_regex, '.*') order by ip_base_len DESC LIMIT 1";
$r = dbq($query, "s", strval($page_no));
if ($r['result'])
{
$row = @mysqli_fetch_assoc($r['result']);
@mysqli_free_result($r['result']);
$ret = $row;
}
else debug ("Loading IP info for dynamic page $page_no failed");
return ($ret);
}
// find_msgs($mb_id)
// Clears out and re-creates the temporary table containing current active messages on a particular board
function find_msgs($mb_id)
{
global $userdata;
if (is_array($mb_id))
$mb_id = implode(',', $mb_id);
$r = dbq("
CREATE TEMPORARY TABLE msg_temp
SELECT msg.*,
date_format(msg.msg_date, '%a %e %b %y %H:%i') as sent_time,
user.user_realname,
msg_read.mr_flags,
user_recip.user_realname as recip,
IF(msg_read.mr_flags IS NULL, 'New', 'Read') as msg_new
FROM msg left join msg_read on msg.msg_id = msg_read.msg_id,
user,
user as user_recip
WHERE msg.mb_id IN ($mb_id)
AND msg.msg_dest = ?
AND msg.msg_sender = user.user_id
AND msg.msg_dest = user_recip.user_id
", "i", $userdata->user_id);
// And then broadcast messages that are read, new, but not deleted
$r = dbq("
INSERT INTO msg_temp
SELECT msg.*,
date_format(msg.msg_date, '%a %e %b %y %H:%i') as sent_time,
user.user_realname,
msg_read.mr_flags,
'All' as recip,
IF(msg_read.mr_flags IS NULL, 'New', 'Read') as msg_new
FROM msg left join msg_read on msg.msg_id = msg_read.msg_id AND msg_read.user_id = ?,
user
WHERE msg.mb_id IN ($mb_id)
AND msg.msg_dest IS NULL
AND msg.msg_sender = user.user_id
", "i", $userdata->user_id);
$r = dbq("select count(*) as number from msg_temp");
if ($r['success'])
{
$d = @mysqli_fetch_assoc($r['result']);
$n = $d['number'];
@mysqli_free_result($r['result']);
debug ("find_msgs $mb_id found $n messages");
}
$r = dbq("delete from msg_temp where mr_flags = 'Deleted'"); // This is inefficient and ought to be fixable in the queries above. Suggestions on a postcard to anyone but me.
}
// is_msg_index($frame_pageno, $frame_subframeid)
// Returns:
// false if not an index page
// false if it is an index page but insufficient msgs on the board
// no. of available msgs if it is an index page and there are sufficient msgs
// Returns true if this is a message index page which appears at least once in msgboard
function is_msg_index($frame_pageno, $frame_subframeid)
{
global $userdata;
$r = dbq("
SELECT mb_id
FROM msgboard
WHERE frame_pageno_list = ?
", "i", $frame_pageno);
if ($r['success'])
{
if ($r['numrows'] >= 1)
{
$mb_id = array();
while ($d = @mysqli_fetch_assoc($r['result']))
array_push($mb_id, $d['mb_id']);
$ret = true;
debug ("is_msg_index($frame_pageno, $frame_subframeid) found message board (".implode(',',$mb_id).")");
}
else $ret = false;
@mysqli_free_result($r['result']);
}
else $ret = false;
// Now see if there are sufficient messages for this frame to "exist" virtually
// If not, return false - and the system will just produce a frame not found error.
if ($ret === true)
{
$min_msgs = ((ord($frame_subframeid) - ord('a')) * 5) + 1;
find_msgs($mb_id);
//$actual_msgs = check_for_new_mail($mb_id, false); // Second param means we get all undeleted messages, not just new ones
$r = dbq("select count(*) as c from msg_temp"); // The temporary table with the stuff in it we want
if (!$r['success'])
$actual_msgs = 0;
else
{
$d = @mysqli_fetch_assoc($r['result']);
$actual_msgs = $d['c'];
@mysqli_free_result($r['result']);
}
if (($actual_msgs < $min_msgs) and ($frame_subframeid != 'a')) // Insufficient messages and not on the 'a' frame
{
debug ("is_msg_index($frame_pageno, $frame_subframeid) discovered only $actual_msgs msgs. Min is $min_msgs. Returned false.");
$ret = false;
}
else
{
$ret = $actual_msgs;
// Populate the array of dates, times, etc.
$userdata->msg_index_data = array();
$r = dbq("select *, if(date(msg_date) = date(now()), date_format(msg_date, '%H:%i'), date_format(msg_date, '%d/%m')) as msg_stamp from msg_temp order by msg_date asc limit ?, 5", "i", $min_msgs -1); // LIMIT index is ordered from 0, whereas min_msgs is an actual count
if ($r['success'])
{
while ($d = @mysqli_fetch_assoc($r['result']))
array_push($userdata->msg_index_data, array($d['user_realname'], $d['msg_subject'], $d['msg_stamp'], $d['msg_new']));
@mysqli_free_result($r['result']);
debug ("is_msg_index() populated ".count($userdata->msg_index_data)." messages for index.");
}
}
dbq("drop table msg_temp");
}
return $ret;
}
// is_msg_reading_page($frame_pageno)
// If the page number specified is a reading page for a given message board
// (i.e. nn001, nn003, etc. where nn is the base reading page in msgboard)
// return the corresponding sending page number for the board.
// This enables the frame loader to load the material from the sending page
// When messages are read.
function is_msg_reading_page($frame_pageno, $frame_subframeid = 'a')
{
$r = dbq("
SELECT frame_pageno_send, frame_pageno_list, mb_id
FROM msgboard
WHERE LEFT(?, LENGTH(frame_pageno_list)) = frame_pageno_list
AND
LENGTH(?) > LENGTH(frame_pageno_list)
ORDER BY LENGTH(frame_pageno_list) DESC
", "ss", $frame_pageno, $frame_pageno);
$ret = false;
if ($r['success'])
{
if ($r['numrows'] < 1)
$ret = false;
else
{
$mb_id = array();
while ($d = @mysqli_fetch_assoc($r['result']))
{
array_push($mb_id,$d['mb_id']);
$frame_pageno_list = $d['frame_pageno_list']; // They should all be the same!
}
}
@mysqli_free_result($r['result']);
}
else $ret = false;
if (isset($mb_id) and count($mb_id) > 0) // Load the message
{
find_msgs($mb_id);
global $userdata;
$msg_number = intval(substr($frame_pageno, -3));
debug ("is_msg_reading_page: Looking for msg_number ".$msg_number);
$r = dbq("SELECT msg_temp.*, msgboard.frame_pageno_send from msg_temp, msgboard where msg_temp.mb_id = msgboard.mb_id order by msg_date asc limit ?, 1", "i", ($msg_number - 1));
debug ("is_msg_reading_page: Select from temporary table - number of rows: ".$r['numrows']);
if (!$r['success'])
$ret = false;
else
{
//$subpage_number = substr($frame_pageno, strlen($list_page)); // to end of string
//$msg_number = intval($subpage_number);
if ($r['numrows'] != 1)
$ret = false;
else
{
$userdata->msg_data = @mysqli_fetch_assoc($r['result']);
// Get the sending page - we need to return it
$ret = $userdata->msg_data['frame_pageno_send'];
// Now word-wrap the message based on the width of the text field on the frame
// NB always works to the published frame.
$fr_r = dbq ("
SELECT fr_start, fr_end
FROM frame left join frame_response on frame.frame_id = frame_response.frame_id
WHERE frame.frame_pageno = ?
AND frame.frame_subframeid = ?
AND frame_response.fr_fieldname = 'TEXT'
AND !FIND_IN_SET('unpublished', frame.frame_flags)
", "is", substr($ret, 0, -1), substr($ret, -1));
if (!$fr_r['success'])
$ret = false;
else
{
$field_data = @mysqli_fetch_assoc($fr_r['result']);
@mysqli_free_result($fr_r);
// Calculate rows & line length
$rows_per_frame = intval($field_data['fr_end'] / 40) - intval($field_data['fr_start'] / 40) + 1;
$linelength = ($field_data['fr_end'] % 40) - ($field_data['fr_start'] % 40) + 1;
// Which frame number are we on?
$frame_number = ord($frame_subframeid) - ord('a') + 1;
// Render the message wordwrapped
$t = render_wrap_str($userdata->msg_data['msg_text'], $linelength, 0);
$userdata->msg_data['wrapped'] = $t['wrapped'];
// Now see how many frame's worth we have got
$total_frames = intval(count($userdata->msg_data['wrapped']) / $rows_per_frame);
if ((count($userdata->msg_data['wrapped']) % $rows_per_frame) > 0)
$total_frames++;
debug ("is_msg_reading_page: Msg has total frames: $total_frames, total lines: ".count($userdata->msg_data['wrapped']).". Frame sought: $frame_subframeid ($frame_number)");
if ($total_frames < $frame_number) // Frame therefore doesn't exist - nothing to put on it
{
debug("is_msg_reading_page: This msg has only $total_frames frames' worth of data, but frame number $frame_number attempted. Returning false.");
$ret = false;
}
else // Put the right set of lines into wrapped_display
{
$c = ($frame_number -1) * $rows_per_frame;
$c_end = $c + $rows_per_frame - 1;
$userdata->msg_data['wrapped_display'] = array();
while (($c <= $c_end) && ($c < count($userdata->msg_data['wrapped'])))
$userdata->msg_data['wrapped_display'][] = $userdata->msg_data['wrapped'][$c++];
$userdata->msg_data['last_subframe'] = chr(ord('a')+$total_frames-1);
}
}
}
@mysqli_free_result($r['result']);
}
dbq("DROP TABLE msg_temp");
}
return $ret;
}
// Load frame data from SQL or retrieve from an IP
// Returns (assoc array of frame data, assoc array of routes, assoc array of fields)
function load_frame_data($frame_pageno, $frame_subframeid, $preview)
{
global $userdata;
$ret = array(false, false, false);
$cpdata = page_get_priv ($frame_pageno, $userdata->user_id);
$userdata->frame_priv = $cpdata[0];
//debug ("page_get_priv($frame_pageno, $userdata->user_id) yielded priv: ".$cpdata[0].", area ID ".$cpdata[1].", area name ".$cpdata[2]);
if ($cpdata[0] == PRIV_NONE)
return $ret;
//if (($userdata->preview or $userdata->editing) && !check_privs($frame_pageno.$frame_subframeid))
if (($userdata->preview or $userdata->editing) && !($cpdata[0] & PRIV_OWNER))
{
log_event('Priv Violation', $userdata->user_id, "Attempt to preview/edit ".$frame_pageno.$frame_subframeid);
$userdata->editing = $userdata->preview = false;
}
else
{
$userdata->frame_data = $userdata->frame_routes = $userdata->frame_response = null;
// Clear response data
$userdata->frame_response = $userdata->frame_routes = array();
// If in preview mode, load the unpublished version
// But not if it doesn't exist. The priv check is done above
if (($userdata->preview && is_unpublished($frame_pageno.$frame_subframeid)) || $userdata->editing)
$preview_extra = " and find_in_set('unpublished', frame.frame_flags)";
else
$preview_extra = " and !find_in_set('unpublished', frame.frame_flags)";
debug("Loading frame [".$frame_pageno."] subframe [".$frame_subframeid."]");
if (is_dynamic($frame_pageno) && (!$userdata->editing && !$userdata->preview))
{
if (!($dynamic_ip_data = load_dynamic_ip_info($frame_pageno)))
{ debug ("Load dynamic frame data failed");
$ret = array(false, false, false);
}
else
{
// Clear response variables
$userdata->frame_response = array();
$dynamic_data = ip_dynamic($dynamic_ip_data['ip_id'], $userdata->user_id, $frame_pageno, $frame_subframeid);
if ($dynamic_data == array(IPR_CALLFAILURE) || $dynamic_data == array(IPR_BADDATA))
$ret = array(false, false, false);
else
{
$frame_data_decoded = base64_decode($dynamic_data['frame_content']);
if (strlen($frame_data_decoded != 880)) // Error / e.g. frame not found
$ret = array(false, false, false);
for ($count = 0; $count < strlen($frame_data_decoded); $count++)
if (($frame_data_decoded[$count] == chr(127)) or ($frame_data_decoded[$count] < chr(32) or $frame_data_decoded[$count] > chr(159)))
$frame_data_decoded[$count] = chr(32);
$userdata->frame_data['frame_content'] = $frame_data_decoded;
$userdata->frame_data['frame_pageno'] = $frame_pageno;
$userdata->frame_data['frame_subframeid'] = $frame_subframeid;
$userdata->frame_data['frame_flags'] = "login";
$userdata->frame_data['frame_id'] = -1;
$userdata->frame_data['frame_fr_ip_function'] = null;
$userdata->frame_data['ip_id'] = $dynamic_ip_data['ip_id'];
$userdata->frame_data['ip_header'] = $dynamic_ip_data['ip_header'];
$userdata->frame_response = $dynamic_data['frame_response'];
$userdata->frame_routes = $dynamic_data['frame_routes'];
$userdata->frame_data['frame_next'] = $dynamic_data['frame_next'];
$ret[0] = $userdata->frame_data;
$ret[1] = $userdata->frame_routes;
$ret[2] = $userdata->frame_response;
}
}
}
else
{
// Work out if this is a message index or message reading frame
// What we do is this:
// If we are being asked for nnnnn(b-z) where nnnnna is the message index frame (default 78a)
// Then, since it is 5 message indexes per page, we work out whether (ord(b) (or whatever) less (ord(a)) * 5 < total number
// of messages. So that that calculation for frame (a) will be "IS 0 < total". If it is, we do nothing and the frame won't
// be found (which is right, because there will be no messages).
// If it is less than the total, we spook the system into loading the "a" frame data and then we populate it
// with the right set of indexes according to whether it was a, b, c, etc. by populating the variables.
// Those variables are @1, @2, etc. for the message no., @SUBJECT1, @SUBJECT2 etc., @FROM1, @FROM2, ...
// and there is a special one for the bottom which will be blank if this is the last set of messages, and
// "# for more" if it isn't.
// We also populate the routes the similarly - by making 1 on frame A go to (e.g.) 78001, 1 on frame B go to 78006.
// When one of those frames is sought, we make it load the base image from the corresponding sending frame - so that
// if there is a special format for that frame (e.g. valentines frame), it can be loaded and the text put into the
// format it was originally sent in. Obviously if someone changes the sending frame after someone has sent a message
// then it may go wonky. The mb_id is stored with the message so that we can get the right one.
$frame_pageno_to_load = $frame_pageno;
$frame_subframeid_to_load = $frame_subframeid;
//$msg_index = $msg_reading = false;
$userdata->is_msg_index = $userdata->is_msg_reading = false;
if (($actual_msgs = is_msg_index($frame_pageno, $frame_subframeid)) !== false)
{
$frame_subframeid_to_load = "a";
//$msg_index = true;
$userdata->is_msg_index = true;
}
if ($p = is_msg_reading_page($frame_pageno, $frame_subframeid))
{
// Note that p will have a subframe suffix on it
// Because the sending page may not be 'a'.
// Contrast the index pages which must always start at 'a'.
debug ("Message reading page detected - sending page is $p");
$frame_pageno_to_load = substr($p,0,-1);
$frame_subframeid_to_load = substr($p,-1);
//$msg_reading = true;
$userdata->is_msg_reading = true;
$userdata->underlying_page = $frame_pageno_to_load.$frame_subframeid_to_load;
// is_msg_reading_page() will have loaded the msg data into $userdata
}
//$query = "
//select left(from_base64(frame_content),880) as frame_content, frame_id, left(ip_header,20) as ip_header, frame_flags, frame_id, frame_pageno, frame_subframeid, frame.ip_id, frame_next,frame_fr_ip_function, frame.area_id from frame, information_provider where frame_pageno=? and frame_subframeid=? and frame.ip_id = information_provider.ip_id".$preview_extra." LIMIT 1";
$query = "
select left(from_base64(frame_content),880) as frame_content, frame_id, frame_flags, frame_id, frame_pageno, frame_subframeid, frame.ip_id, frame_next,frame_fr_ip_function, frame.area_id from frame where frame_pageno=? and frame_subframeid=? ".$preview_extra." LIMIT 1";
$r = dbq($query, "is", $frame_pageno_to_load, $frame_subframeid_to_load);
debug ("Frame load query returned ".$r['numrows']." rows for frame ".$frame_pageno_to_load.$frame_subframeid_to_load);
if ($r['numrows'] == 1)
{
debug("Frame $frame_pageno$frame_subframeid - SQL data loaded");
$ret[0] = @mysqli_fetch_assoc($r['result']);
$userdata->frame_data = $ret[0];
@mysqli_free_result($r['result']);
// The ip_id in the framestore is not in fact accurate! We should get it by looking up whose IP this really is.
$ip_info = load_dynamic_ip_info($frame_pageno_to_load);
$userdata->frame_data['ip_header'] = $ip_info['ip_header'];
$userdata->frame_data['ip_id'] = $ip_info['ip_id'];
//debug("Frame content length ".strlen($userdata->frame_data['frame_content']).": ".substr($userdata->frame_data['frame_content'], 0, 30)."...");
// Load routes
$query = "
SELECT frame_keypress, frame_key_action, frame_key_metadata1, frame_key_metadata2, frame_next from frame, frame_key
WHERE frame.frame_id = frame_key.frame_id and frame_key.frame_id = ? ".$preview_extra;
// note that frame_next will be the same in all rows. We just need it in case we trip off subframe 'z'
$r = dbq($query, "i", $ret[0]['frame_id']);
if ($r['result'])
{
while ($row = @mysqli_fetch_assoc($r['result']))
{
$frame_next = $row['frame_next'];
$userdata->frame_data['frame_next'] = $frame_next;
$routes = array(
$row['frame_key_action'],
$row['frame_key_metadata1'],
$row['frame_key_metadata2'] );
$userdata->frame_routes[$row['frame_keypress']] = $routes;
}
$ret[1] = $userdata->frame_routes;
@mysqli_free_result($r['result']);
}
else
{
show_error($userdata->conn, "System database error");
logoff($conn);
}