Re-engineered with Laravel

This commit is contained in:
Deon George 2018-12-02 01:50:34 +04:00
parent c227f25db1
commit 4504818e25
40 changed files with 6585 additions and 958 deletions

41
.env.example Normal file
View File

@ -0,0 +1,41 @@
APP_NAME=Laravel
APP_ENV=local
APP_KEY=
APP_DEBUG=true
APP_BIND=0.0.0.0
APP_PORT=516
APP_URL=http://localhost
LOG_CHANNEL=stack
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=homestead
DB_USERNAME=homestead
DB_PASSWORD=secret
BROADCAST_DRIVER=log
CACHE_DRIVER=file
QUEUE_CONNECTION=sync
SESSION_DRIVER=file
SESSION_LIFETIME=120
REDIS_HOST=127.0.0.1
REDIS_PASSWORD=null
REDIS_PORT=6379
MAIL_DRIVER=smtp
MAIL_HOST=smtp.mailtrap.io
MAIL_PORT=2525
MAIL_USERNAME=null
MAIL_PASSWORD=null
MAIL_ENCRYPTION=null
PUSHER_APP_ID=
PUSHER_APP_KEY=
PUSHER_APP_SECRET=
PUSHER_APP_CLUSTER=mt1
MIX_PUSHER_APP_KEY="${PUSHER_APP_KEY}"
MIX_PUSHER_APP_CLUSTER="${PUSHER_APP_CLUSTER}"

5
.gitattributes vendored Normal file
View File

@ -0,0 +1,5 @@
* text=auto
*.css linguist-vendored
*.scss linguist-vendored
*.js linguist-vendored
CHANGELOG.md export-ignore

17
.gitignore vendored Normal file
View File

@ -0,0 +1,17 @@
/node_modules
/public/hot
/public/storage
/storage/*.key
/vendor
/.idea
/.vscode
/nbproject
/.vagrant
Homestead.json
Homestead.yaml
npm-debug.log
yarn-error.log
.env
.phpunit.result.cache
devel/
data/

299
app/Classes/Frame.php Normal file
View File

@ -0,0 +1,299 @@
<?php
namespace App\Classes;
use Illuminate\Support\Facades\Log;
/**
* Handles all aspects of frame
*
* Frame are constructed:
* + First line is the header, displaying TITLE/CUG TITLE|PAGE #|COST
* + Up to $frame_length for content
* + Input/Status Line
*
* NOTES:
* + Frames are stored in binary. ESC codes are stored as a single char < 32.
* + Header is on line 1.
* + Input field is on Line 24.
* + 'i' Frames are info frames, no looking for fields. (Lines 2-23)
* + 'ip' Frames are Information Provider frames - no header added. (Lines 1-23)
* + 'a' Frames have active frames with responses.
* + 't' Frames terminate the session
*
* To Consider
* + 'x' External frames - living in another viewdata server
*
* @package App\Classes
*/
class Frame
{
private $frame = NULL;
private $output = NULL;
private $frame_length = 22;
private $frame_width = 40;
private $header_length = 20; // 20
private $pagenum_length = 9; // 11 (prefixed with a color, suffixed with frame)
private $cost_length = 7; // 9 (prefixed with a color, suffixed with unit)
private $cost_unit = 'u';
private $fieldmap = ['s'=>'systel','n'=>'username','a'=>'address#','d'=>'%date'];
public $fields = NULL; // The fields in this frame.
// @todo Move this to the database
private $header = RED.'T'.BLUE.'E'.GREEN.'S'.YELLOW.'T'.MAGENTA.'!';
public function __construct(\App\Models\Frame $o,string $msg=NULL)
{
$this->frame = $o;
$this->output = $this->hasFlag('clear') ? CLS : HOME;
if ($msg)
$this->output .= UP.$msg.HOME;
if (! $this->hasFlag('ip')) {
// Set the page header: CUG/Site Name | Page # | Cost
$this->output .= $this->render_header($this->header).
$this->render_page($this->frame->frame_id,$this->frame->subframe_id).
$this->render_cost($this->frame->cost);
}
// Calculate fields and render output.
$this->fields();
}
public function __toString()
{
return $this->output;
}
/**
* Convert the frame from Binary to Output
* Look for fields within the frame.
*
* @param int $startline
*/
public function fields($startline=0)
{
$infield = FALSE;
$this->fields = collect();
if ($startline)
$this->output .= str_repeat(DOWN,$startline);
// $fieldadrline = 1;
// Scan the frame for a field start
for ($y=$startline;$y<=$this->frame_length;$y++)
{
$fieldx = $fieldy = FALSE;
for ($x=0;$x<$this->frame_width;$x++)
{
$posn = $y*40+$x;
$byte = ord(isset($this->frame->frame_content{$posn}) ? $this->frame->frame_content{$posn} : ' ')%128;
// dump(sprintf('Y: %s,X: %s, POSN: %s, BYTE: %s',$y,$x,$posn,$byte));
// Check for start-of-field
if ($byte == ord(ESC)) { // Esc designates start of field (Esc-K is end of edit)
$infield = TRUE;
$fieldlength = 0;
$fieldtype = ord(substr($this->frame->frame_content,$posn+1,1))%128;
$byte = ord(' '); // Replace ESC with space.
} else {
if ($infield) {
if ($byte == $fieldtype) {
$fieldlength++;
$byte = ord(' '); // Replace field with space.
if ($fieldx === false) {
$fieldx = $x;
$fieldy = $y;
}
// Is this a magic field?
// @todo For page redisplay *00, we should show entered contents - for refresh *09 we should show updated contents
if (array_get($this->fieldmap,chr($fieldtype)) ) {
$field = $this->fieldmap[chr($fieldtype)];
//dump(['infield','byte'=>$byte,'fieldtype'=>$fieldtype,'field'=>$field,'strpos'=>strpos($field,'#')]);
/*
// address field has many lines. increment when hit on first character.
if ($fieldlength == 1 && strpos($field,'#') !== false) {
$field = str_replace('#',$fieldadrline,$field);
dump(['field'=>$field,'fieldadrline'=>$fieldadrline,'fieldadrline'=>$fieldadrline]);
$fieldadrline++;
}
*/
// Replace field with Date
if ($field == '%date') {
if ($fieldlength == 1)
$datetime = strtoupper(date('D d M Y H:i:s'));
if ($fieldlength <= strlen($datetime))
$byte = ord($datetime{$fieldlength-1});
}
// @todo user data
/* else if (isset($user[$field])) {
if ($fieldlength <= strlen($user[$field])) {
$byte = ord($user[$field]{$fieldlength-1});
}
} /*else // pre-load field contents. PAM or *00 ?
if (isset($fields[what]['value'])) {
} */
}
} else {
Log::debug(sprintf('Frame: %s%s, Field found at [%s,%s], Type: %s, Length: %s','TBA','TBA',$fieldx,$fieldy,$fieldtype,$fieldlength));
$this->fields->push([
'type'=>chr($fieldtype),
'length'=>$fieldlength,
'x'=>$fieldx,
'y'=>$fieldy,
]);
$infield = FALSE;
$fieldx = $fieldy = FALSE;
}
}
}
// truncate end of lines
if (isset($pageflags['tru']) && substr($this->frame->frame_content,$y*40+$x,40-$x) === str_repeat(' ',40-$x)) {
$this->output .= CR . LF;
break;
}
$this->output .= ($byte < 32) ? ESC.chr($byte+64) : chr($byte);
}
}
}
/**
* Return the Frame Number
*/
public function framenum()
{
return $this->frame->frame_id.$this->frame->subframe_id;
}
/**
* Return the flag for this page
*
* CLEAR: Clear Screen before rendering.
*
* @param $flag
* @return bool
*/
private function hasFlag($flag)
{
return $this->frame->hasFlag($flag);
}
/**
* Render the cost of the frame
*
* @param int $cost
* @return string
* @throws \Exception
*/
private function render_cost(int $cost)
{
if ($cost > 999)
throw new \Exception('Price too high');
if ($cost > 100)
$color = RED;
elseif ($cost > 0)
$color = YELLOW;
else
$color = GREEN;
return sprintf($color.'% '.$this->cost_length.'.0f%s',$cost,$this->cost_unit);
}
/**
* Render the Site Header
*
* @param string $header
* @return bool|string
*/
private function render_header(string $header)
{
$filler = ($this->strlenv($header) < $this->header_length) ? str_repeat(' ',$this->header_length-$this->strlenv($header)) : '';
return substr($header.$filler,0,$this->header_length+substr_count($this->header,ESC));
}
/**
* Render the Frame Number
*
* @param int $num
* @param string $frame
* @return string
* @throws \Exception
*/
private function render_page(int $num,string $frame)
{
if ($num > 999999999)
throw new \Exception('Page Number too big',500);
if (strlen($frame) !== 1)
throw new \Exception('Frame invalid',500);
return sprintf(WHITE.'% '.$this->pagenum_length.'.0f%s',$num,$frame);
}
/**
* Calculate the length of text
*
* ESC characters are two chars, and need to be counted as one.
*
* @param $text
* @return int
*/
function strlenv($text) {
return strlen($text)-substr_count($text,ESC);
}
public static function testFrame()
{
// Simulate a DB load
$o = new \App\Models\Frame;
$o->frame_content = '';
$o->flags = ['ip'];
$o->frametype = 'a';
$o->frame_id = 999;
$o->subframe_id = 'a';
// Header
$o->frame_content .= substr(R_RED.'T'.R_BLUE.'E'.R_GREEN.'S'.R_YELLOW.'T-12345678901234567890',0,20).
R_WHITE.'999999999a'.R_RED.sprintf('%07.0f',999).'u';
$o->frame_content .= str_repeat('+-',18).' '.R_RED.'01';
$o->frame_content .= 'Date: '.ESC.str_repeat('d',25).str_repeat('+-',4);
$o->frame_content .= 'Name: '.ESC.str_repeat('u',5).str_repeat('+-',14);
$o->frame_content .= 'Address: '.ESC.str_repeat('a',20).''.str_repeat('+-',5);
$o->frame_content .= ' : '.ESC.str_repeat('a',20).''.str_repeat('+-',5);
return $o;
}
/**
* Return the Frame Type
*/
public function type()
{
return $this->frame->type();
}
}

View File

@ -0,0 +1,928 @@
<?php
/**
* Viewdata/Videotex Server
*
* Inspired by Rob O'Donnell at irrelevant.com
*/
namespace App\Console\Commands;
use App\Classes\Frame;
use Illuminate\Console\Command;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Support\Facades\Log;
use Sock\{SocketClient,SocketServer,SocketException};
class Server extends Command
{
// @todo Understand how is this used.
private $fieldoptions = ['f'=>['edit'=>TRUE],'a'=>['edit'=>TRUE]];
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'server';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Start Videotex Server';
/**
* Create a new command instance.
*
* @return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
* @return mixed
* @throws \Sock\SocketException
*/
public function handle()
{
/**
* Check dependencies
*/
if (! extension_loaded('sockets' ) ) {
throw new SocketException(SocketException::CANT_ACCEPT,'Missing sockets extension');
}
if (! extension_loaded('pcntl' ) ) {
throw new SocketException(SocketException::CANT_ACCEPT,'Missing pcntl extension');
}
// @todo Deprecate this function
define('MSG_TIMEWARP_ON', WHITE . 'TIMEWARP ON' . GREEN . 'VIEW INFO WITH *02');
define('MSG_TIMEWARP_OFF', WHITE . 'TIMEWARP OFF' . GREEN . 'VIEWING DATE IS FIXED');
define('MSG_TIMEWARP_TO', GREEN . 'TIMEWARP TO %s');
define('MSG_TIMEWARP', WHITE . 'OTHER VERSIONS EXIST' . GREEN . 'KEY *02 TO VIEW');
// @todo Deprecate this
include_once('classes/vvdatabase.class.php');
$server = new SocketServer(config('app.port'),config('app.bind'));
$server->init();
$server->setConnectionHandler([$this,'onConnect']);
$server->listen();
}
/**
* Connection handler
*/
function onConnect(SocketClient $client) {
Log::info('Connection from: ',['client'=>$client->getAddress()]);
// @todo To Deprecate in favour of config()
global $config;
include ('config/config.php');
$childpid = pcntl_fork();
if ($childpid == -1)
throw new SocketException(SocketException::CANT_ACCEPT,'Could not fork process');
// Parent return ready for next connection
elseif ($childpid)
return;
// We are now the child.
// @todo Need to intercept any crashes and close the TCP port.
$session_init = $session_option = FALSE;
$session_note = ''; // TCP Session Notice
$session_term = ''; // TCP Terminal Type
$client->send(TCP_IAC.TCP_DO.TCP_OPT_SUP_GOAHEAD); // DO SUPPRES GO AHEAD
$client->send(TCP_IAC.TCP_WONT.TCP_OPT_LINEMODE); // WONT LINEMODE
$client->send(TCP_IAC.TCP_DO.TCP_OPT_ECHO); // DO ECHO
// $client->send(TCP_IAC.TCP_AYT); // AYT
$client->send(TCP_IAC.TCP_DO.TCP_OPT_TERMTYPE.TCP_IAC.TCP_SB.TCP_OPT_TERMTYPE.TCP_OPT_ECHO.TCP_IAC.TCP_SE); // Request Term Type
$client->send(CLS);
$read = '';
// @todo Deprecate and have an exception handler handle this.
// like throw new FatalClientException(CLS.UP.ERR_DATABASE,500,NULL,$client);
// @todo Get the login page, and if it is not available, throw the ERR_DATEBASE error.
$db = new \vvdb();
// Connect to database. Returns error message if unable to connect.
$r = $db->connect($config['dbserver'],$config['database'],$config['dbuser'], $config['dbpass']);
/*
if (!empty($r)) {
http_response_code(500);
$client->send(CLS . UP . ERR_DATABASE);
die ($r);
}
*/
// $user will eventually contain validated user details.
$user = array( 'systel' => '019990001',
'username' => 'DEMONSTRATION DATA USER',
'address1' => '8 HERBAL HILL',
'address2' => 'LONDON',
'address3' => 'EC1R 5EJ',
'address4' => '',
'address5' => '',
'CUGS' => array( 7800, 15500), // Closed User Groups this user has access to
);
$history = array(); // backup history
$cmd = ''; // current *command being typed in
$mode = false; // input mode.
$prevmode = false; // previous mode
$timewarp = false;
$action = ACTION_GOTO; // do something if set. used here to trigger a goto to the login form.
if (isset($config['loginpage'])) {
$page = $config['loginpage'];
$subpage = 'a';
} else if (!empty($service['start_page'])) {
$page = $service['start_page'];
$subpage = 'a';
} else {
$page = '999'; // next page
$subpage = 'a';
}
$curpage = ''; // current page
$cursub = '';
$curfield = null; // current input field
$curfp = 0; // current field, position within.
$blp = 0; // botton line polluted (by this no. of characters)
$resetpsn = false; // flag to reset position (used in fields)
if (! isset($config['varient_id']))
$config['varient_id'] = NULL;
$service = $db->getServiceById($config['service_id']);
//dd($service);
$varient = $db->getAllVarients($config['service_id'], $config['varient_id']);
if ($varient === false) {
die ("no varient");
}
$varient = reset($varient);
$matches = array();
if (preg_match('@'.$service['page_format'].'@',$service['start_frame'],$matches)) {
$page = $matches[1];
$subpage = $matches[2];
echo " Using start page ".$page.$subpage."\n";
}
// $start = $service['start_frame'];
// where to start from
while( $action != ACTION_TERMINATE ) {
// Read a character from the client session
$read = $client->read(1);
if ($read != '') {
dump(sprintf('Mode: [%s] CMD: [%s] frame: [%s] Received [%s (%s)]',$mode,$cmd,$page,$read,ord($read)));
// Client initiation input
// TELNET http://pcmicro.com/netfoss/telnet.html
if ($read == TCP_IAC OR $session_init OR $session_option)
{
Log::debug(sprintf('Session Char (%s)',ord($read)),['init'=>$session_init,'option'=>$session_option]);
switch ($read) {
// Command being sent.
case TCP_IAC:
$session_init = TRUE;
$session_note = 'IAC ';
continue 2;
case TCP_SB:
$session_option = TRUE;
continue 2;
case TCP_SE:
$session_option = $session_init = FALSE;
Log::debug('Session Terminal: '.$session_term);
break;
case TCP_DO:
$session_note .= 'DO ';
continue 2;
case TCP_WILL:
$session_note .= 'WILL ';
continue 2;
case TCP_WONT:
$session_note .= 'WONT ';
continue 2;
case TCP_OPT_TERMTYPE:
continue 2;
case TCP_OPT_ECHO:
$session_note .= 'ECHO';
$session_init = FALSE;
$read = '';
Log::debug($session_note);
continue;
case TCP_OPT_SUP_GOAHEAD:
$session_note .= 'SUPPRESS GO AHEAD';
$session_init = FALSE;
$read = '';
Log::debug($session_note);
continue;
default:
if ($session_option AND $read) {
$session_term .= $read;
$read = '';
} else {
Log::debug(sprintf('Unhandled char in session_init :%s (%s)',$read,ord($read)));
}
}
}
switch($mode){
// Key presses during field input.
case MODE_FIELD:
//dump(sprintf('** Processing Keypress in MODE_FIELD [%s (%s)]. Last POS [%s]',$read,ord($read),$curfp));
$cmd = '';
$action = FALSE;
switch ($fo->type()) {
// Input frame.
case 'a':
switch ($read) {
// End of field entry.
case HASH:
// Next Field
$curfield++;
//dump(['current'=>$curfield, 'numfields'=>count($fields)]);
if ($curfield < count($fields)) { // skip past non-editable fields
for ($i = $curfield; $i < count($fields); $i++) {
if (isset($this->fieldoptions[$fields[$i]['type']]) &&
$this->fieldoptions[$fields[$i]['type']]['edit']) {
$curfield = $i;
break;
}
}
if ($curfield !== false) {
$client->send(outputPosition($fields[$curfield]['x'],$fields[$curfield]['y']).CON);
$mode = MODE_FIELD;
$fielddate[$curfield] = '';
} else {
// there were no (more) editable fields.
$action = ACTION_SUBMITRF;
}
} else {
// done them all editable fields.
$action = ACTION_SUBMITRF;
}
break;
case STAR:
$prevmode = MODE_FIELD;
$action = ACTION_STAR;
break;
case KEY_LEFT:
if ($curfp) {
$client->send(LEFT);
$curfp--;
};
break;
case KEY_RIGHT:
if ($curfp++ < $fields[$curfield]['length']) {
$client->send(RIGHT);
//$curfp++;
};
break;
case KEY_DOWN:
if ($curfp + 40 < $fields[$curfield]['length']) {
$client->send(DOWN);
$curfp = $curfp + 40;
};
break;
case KEY_UP:
if ($curfp - 40 >= 0) {
$client->send($read);
$curfp = $curfp - 40;
};
break;
case CR:
if ($curfp + $fields[$curfield]['x'] > 40) { // on second or later line of a field
$client->send($read);
$curfp = (($curfp + $fields[$curfield]['x'])%40)*40;
} else {
$client->send(outputPosition($fields[$curfield]['x'],$fields[$curfield]['y']).CON);
$curfp = 0;
}
break;
case ESC:
break; ;
// Record Data Entry
default:
if (ord($read) > 31 && $curfp < $fields[$curfield]['length']) {
$fielddata[$curfield]{$curfp} = $read;
$curfp++;
$client->send($read);
}
}
break;
// Other Frame Types - Shouldnt get here.
default:
throw new \Exception('Shouldnt get here',500);
} // switch frame types
break;
// Form submission: 1 to send, 2 not to send.
case MODE_SUBMITRF:
switch($read){
// @todo Input received, process it.
case '1':
dump(['s'=>$service,'f'=>$fielddata]);
if(TRUE) {
sendBaseline($client, $blp, MSG_SENT);
$mode = MODE_RFSENT;
} else {
sendBaseline($client, $blp, ERR_NOTSENT);
$mode = MODE_RFERROR;
}
break;
case '2':
sendBaseline($client, $blp, MSG_NOTSENT);;
$mode = MODE_RFNOTSENT;
break;
case STAR:
$action = ACTION_STAR;
break;
}
break;
// Response form after Sent processing
// @todo To fix.
case MODE_RFSENT:
$client->send(COFF);
if ($read == HASH) {
if (!empty($pagedata['route1'])) {
$action = ACTION_GOTO;
$page = $pagedata['route1'];
$subpage = 'a';
} else if ($r = $db->getFrame($service['service_id'],$varient['varient_id'],$page,chr(1+ord($subpage)))) {
$action = ACTION_GOTO;
$page = $curpage;
$subpage = chr(1+ord($subpage));
} else if (!empty($pagedata['route0'])) {
$action = ACTION_GOTO;
$page = $pagedata['route0'];
$subpage = 'a';
// No further routes defined, go home.
} else {
$action = ACTION_GOTO;
$page = '0';
$subpage = 'a';
}
} elseif ($read == STAR) {
$action = ACTION_STAR;
break;
}
break;
// Response form after NOT sending
case MODE_RFNOTSENT:
// Response form ERROR
// @todo To fix
case MODE_RFERROR:
$client->send(COFF);
if ($read == HASH) {
if (!empty($pagedata['route2'])) {
$action = ACTION_GOTO;
$page = $pagedata['route2'];
$subpage = 'a';
} else if ($r = $db->getFrame($service['service_id'],$varient['varient_id'],$page,chr(1+ord($subpage)))) {
$action = ACTION_GOTO;
$page = $curpage;
$subpage = chr(1+ord($subpage));
} else if (!empty($pagedata['route0'])) {
$action = ACTION_GOTO;
$page = $pagedata['route0'];
$subpage = 'a';
// No further routes defined, go home.
} else {
$action = ACTION_GOTO;
$page = '0';
$subpage = 'a';
}
} else if ($read == STAR) {
$action = ACTION_STAR;
break;
}
break;
/*
List of alternate options has been presented
*/
case MODE_WARPTO: // expecting a timewarp selection
if (isset($alts[$read - 1 ])) {
$v = $db->getAllVarients($config['service_id'], $alts[$read - 1]['varient_id']);
if (!empty($v)) {
$varient = reset($v);
$page = $curpage;
$subpage = $cursub;
$action = ACTION_GOTO;
break;
}
}
// if wasn't a valid warpto keypress,
//drop into
// Not doing anything in particular.
case FALSE:
$cmd = '';
Log::debug('Idle',['pid'=>'TBA']);
switch ($read) {
case HASH:
$action = ACTION_NEXT;
break;
case STAR:
$action = ACTION_STAR;
break;
// Frame Routing
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
if (isset($pagedata['route' . $read]) && $pagedata['route' . $read] != '*') {
$action = ACTION_GOTO;
$page = $pagedata['route' . $read];
$subpage = 'a';
break;
} else {
sendBaseline($client, $blp, ERR_ROUTE);
$mode = $action = false;
}
break;
}
break;
/*
currently accepting baseline imput after a * was received
*/
case MODE_BL: // entering a baseline command
echo "was waiting for page number\n";
// if it's a number, continue entry
if (strpos('0123456789',$read) !== false) { // numeric
$cmd .= $read;
$client->send($read);
$blp++;
}
// if we hit a special numeric command, deal with it.
if ($cmd === '00') { // refresh page
$client->send(COFF);
$action = ACTION_RELOAD;
$cmd = '';
break;
}
if ($cmd === '09') { // reload page
$client->send(COFF);
$action = ACTION_GOTO;
$cmd = '';
break;
}
if ($cmd === '02') { // new for emulator
$client->send(COFF);
$action = ACTION_INFO;
$cmd = '';
break;
}
if (($cmd === '01')) { // new for emulator
$client->send(COFF);
$timewarp = !$timewarp;
sendBaseline($client, $blp,
( $timewarp ? MSG_TIMEWARP_ON : MSG_TIMEWARP_OFF));
$cmd = '';
$action = $mode = false;
}
// another star aborts the command.
if ($read === "*") { // abort command or reset input field.
$action = false;
sendBaseline($client, $blp, '');
$cmd = '';
if ($prevmode == MODE_FIELD) {
$mode = $prevmode;
$prevmode = false;
$client->send(outputPosition($fields[$curfield]['x'],$fields[$curfield]['y']).CON);
$client->send(str_repeat(' ',$fields[$curfield]['length']));
// tood reset stored entered text
$resetpsn = $curfield;
} else {
$mode = false;
}
break;
}
// user hit # to complete request
if ($read === '_') { // really the # key,
$client->send(COFF);
if ($cmd === '') { // nothing typed between * and #
$action = ACTION_BACKUP;
} else { // *# means go back
$page = $cmd;
$subpage = 'a';
$action = ACTION_GOTO;
}
$cmd = ''; // finished with this now
break;
}
break;
default:
echo "not sure what we were doing\n";
} // switch $mode
} // something in $read
/*
This section performs some action if it is deemed necessary
*/
if ($action) {
echo "Performing action $action\n";
}
switch($action){
case ACTION_STAR:
echo " star command started\n";
sendBaseline($client, $blp, GREEN . '*', true);
$client->send(CON);
$action = false;
$mode = MODE_BL;
break;
case ACTION_SUBMITRF:
$action = false;
sendBaseline($client, $bpl, MSG_SENDORNOT);
$mode = MODE_SUBMITRF;
break;
case ACTION_BACKUP:
// do we have anywhere to go?
if (count($history) > 1) { // because current page should always be in there.
array_pop($history); // drop current page to reveal previous
}
list($page, $subpage) = end($history); // get new last entry,
echo "Backing up to $page$subpage\n";
// drop into
case ACTION_NEXT:
if ($action == ACTION_NEXT) {
$cursub = $subpage;
$subpage = chr(ord($subpage)+1);
}
case ACTION_GOTO:
// $client->send(HOME . UP . GREEN . "Searching for page $page");
// $blp = 20 + strlenv($page);
// look for requested page
try {
$fo = (new \App\Models\Frame)->fetch($page,$subpage);
} catch (ModelNotFoundException $e) {
Log::debug(sprintf('Frame: %s%s NOT found',$page,$subpage));
if ($action == ACTION_NEXT) {
$subpage = $cursub; // Put subpage back as it was
}
sendBaseline($client, $blp, ERR_PAGE);
$mode = $action = FALSE;
break;
}
dump(['m'=>__METHOD__,'service'=>$service['service_id'],'varient'=>$varient['varient_id'],'frame'=>$fo->framenum(),'type'=>$fo->type()]);
// validate if we have access top it
/* if (isset($m['access']) && $m['access'] == 'n') {
sendBaseline($client, $blp, ERR_PAGE);
$mode = $action = false;
break;
}
if (isset($m['cug']) && is_numeric($m['cug']) && $m['cug'] && !in_array($m['cug'],$usercugs)) {
sendBaseline($client, $blp, ERR_PRIVATE);
$mode = $action = false;
break;
}
*/
// we have access...
if ($r['varient_id'] != $varient['varient_id']) {
if (empty($v['varient_date'])) {
sendBaseline($client, $blp, sprintf(MSG_TIMEWARP_TO, 'unknown date') );
} else {
sendBaseline($client, $blp, sprintf(MSG_TIMEWARP_TO,date('j f Y',strtotime($v['varient_date']))) );
}
$varient = array_merge($varient, array_intersect_key($r, $varient));
}
//var_dump(['B','r'=>$r,'m'=>$m]);
//$pagedata = array_merge($r, $m);
//$varient = $v;
$curpage = $page;
$cursub = $subpage;
$cufield = 0;
$curfp = 0;
//$pageflags = $db->getFrameTypeFlags($pagedata['type']); // method missing.
$pageflags = [];
if ($action == ACTION_GOTO || $action == ACTION_NEXT) { // only if new location, not going backwards
$history[] = array($page,$subpage);
}
// drop into
case ACTION_RELOAD:
//
/* if ($pageflags['clear']) {
$output = CLS;
$blp = 0;
} else {
$output = HOME;
}
*/
// print_r($pageflags); print_r($pagedata);
switch($fo->type()){
default:
case 'i': // standard frame
if ($timewarp && 1 < count(
$alts = $db->getAlternateFrames($service['service_id'],$varient['varient_id'],$curpage,$cursub)
)) {
$msg = MSG_TIMEWARP;
} else {
$msg = '';
}
$output = getOutputx($curpage, $cursub, [], $pageflags, $msg);
//var_dump(['output'=>$output,'curpage'=>$curpage,'cursub'=>$cursub,'pagedata'=>$pagedata,'pageflag'=>$pageflags,'m'=>$msg]);
$blp = strlenv($msg);
$client->send($output);
$mode = $action = false;
break;
case 'a': // active frame. Prestel uses this for Response Framea.
/*
if ($timewarp && 1 < count(
$alts = $db->getAlternateFrames($service['service_id'],$varient['varient_id'],$curpage,$cursub)
)) {
$msg = MSG_TIMEWARP;
} else {
$msg = '';
}
*/
// this is a glorious hack to fix three out of 30,000 pages but might
// break lots more.
//$pagedata = str_replace(chr(12),chr(27),$pagedata);
// holds data entered by user.
$fielddata = array();
$fields = $fo->fields;
$msg = '?';
$output = getOutputx($curpage, $cursub, [], $pageflags, $msg, $user, $fields);
$blp = strlenv($msg);
$client->send($output);
if ($fields->count()) {
// dump($fields,count($fields));
// need t skip to first field that is..
// of a field type that is editable
// or finish.
$curfield = FALSE;
for ($i = 0; $i < count($fields); $i++) {
//dump($this->fieldoptions,$i,isset($this->fieldoptions[$fields[$i]['type']]));
if (isset($this->fieldoptions[$fields[$i]['type']]) &&
$this->fieldoptions[$fields[$i]['type']]['edit']) {
$curfield = $i;
break;
}
}
$resetpsn = $curfield;
if ($curfield !== false) {
$mode = MODE_FIELD;
} else {
// there were no editable fields.
$mode = MODE_COMPLETE;
}
$curfp = 0;
//dump(['curfield'=>$curfield,'mode'=>$mode]);
}
break;
case 't': // terminate
$output = getOutputx($curpage, $cursub, [], $pageflags);
$client->send($output);
$action = ACTION_TERMINATE;
break;
} // switch
break;
case ACTION_INFO: // special emulator command
$mode = false;
$cmd='';
$action = false;
$output = outputPosition(0,0) . WHITE . NEWBG . RED . 'TIMEWARP INFO FOR Pg.' . BLUE . $curpage . $cursub . WHITE;
$output .= outputPosition(0,1) . WHITE . NEWBG . BLUE . 'Service : ' . substr($service['service_name'] . str_repeat(' ',27),0,27) ;
$output .= outputPosition(0,2) . WHITE . NEWBG . BLUE . 'Varient : ' . substr($varient['varient_name'] . str_repeat(' ',27),0,27) ;
$output .= outputPosition(0,3) . WHITE . NEWBG . BLUE . 'Dated : ' . substr(date('j F Y',strtotime($varient['varient_date'])) . str_repeat(' ',27),0,27);
$alts = $db->getAlternateFrames($service['service_id'],$varient['varient_id'],$curpage,$cursub);
if (count($alts) > 1) {
$n = 1;
$output .= outputPosition(0,4) . WHITE . NEWBG . RED . 'ALTERNATIVE VERSIONS:' . str_repeat(' ',16);
$y = 5;
foreach ($alts as $ss){
// if (is_numeric($ss['varient_date'])) {
$date = date('d M Y', strtotime($ss['varient_date']));
// } else {
// $date = 'unknown';
// }
$line = WHITE . NEWBG;
if ($timewarp) {
$line .= RED . $n;
}
$line .= BLUE . $date . ' ' . $ss['varient_name'];
$output .= outputPosition(0,$y) . $line . str_repeat(' ',40-strlenv($line));
$y++;
$n++;
}
if ($timewarp) {
$mode = MODE_WARPTO;
}
}
$client->send($output);
break;
default:
;
} // switch $action
if ($resetpsn !== false && isset($fields[$resetpsn])) {
$client->send(outputPosition($fields[$resetpsn]['x'],$fields[$resetpsn]['y']).CON);
$resetpsn = false;
}
if( $read === null || socket_last_error()) {
printf( "[%s] Disconnected\n", $client->getaddress() );
return false;
}
}
$client->close();
printf( "[%s] Disconnected\n", $client->getaddress() );
}
}
function strlenv($text){
return strlen($text) - substr_count($text, ESC);
}
function sendBaseline($client, &$blp, $text, $reposition = false){
$client->send(HOME . UP . $text .
( $blp > strlenv($text) ? str_repeat(' ',$blp-strlenv($text)) .
( $reposition ? HOME . UP . str_repeat(RIGHT, strlenv($text)) : '' )
: '')
);
$blp = strlenv($text);
return;
}
function outputPosition($x,$y){
if ($y < 12) {
if ($x < 21) {
return HOME . str_repeat(DOWN, $y) . str_repeat(RIGHT, $x);
} else {
return HOME . str_repeat(DOWN, $y+1) . str_repeat(LEFT, 40-$x);
}
} else {
if ($x < 21) {
return HOME . str_repeat(UP, 24-$y) . str_repeat(RIGHT, $x);
} else {
return HOME . str_repeat(UP, 24-$y) . str_repeat(LEFT, 40-$x);
}
}
}
/*
return a screen output ... $msg sent on baseline just after the cls.
remember to update $blp manually after calling this.
*/
function getOutputx($page, $subpage, $pagedata, $pageflags, $msg = '', $user = array(), &$fields = null, &$frame_content = null) {
global $blp;
global $fieldmap; // @todo this is not set outside of the class.
$price = isset($pagerecord['price']) ? $pagerecord['price'] : 0;
// get textual content.
$fo = (new \App\Models\Frame)->fetch($page,$subpage);
$text = (string)$fo;
//$text = $pagedata['frame_content'];
// dump(['C'=>__METHOD__,'frame_content'=>$text,'msg'=>$output,'p'=>$page,'s'=>$subpage,'startline'=>$startline,'frame'=>$fo,'fields'=>$fo->fields($startline)]);
return (string)$fo;
}

42
app/Console/Kernel.php Normal file
View File

@ -0,0 +1,42 @@
<?php
namespace App\Console;
use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;
class Kernel extends ConsoleKernel
{
/**
* The Artisan commands provided by your application.
*
* @var array
*/
protected $commands = [
//
];
/**
* Define the application's command schedule.
*
* @param \Illuminate\Console\Scheduling\Schedule $schedule
* @return void
*/
protected function schedule(Schedule $schedule)
{
// $schedule->command('inspire')
// ->hourly();
}
/**
* Register the commands for the application.
*
* @return void
*/
protected function commands()
{
$this->load(__DIR__.'/Commands');
require base_path('routes/console.php');
}
}

View File

@ -0,0 +1,51 @@
<?php
namespace App\Exceptions;
use Exception;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
class Handler extends ExceptionHandler
{
/**
* A list of the exception types that are not reported.
*
* @var array
*/
protected $dontReport = [
//
];
/**
* A list of the inputs that are never flashed for validation exceptions.
*
* @var array
*/
protected $dontFlash = [
'password',
'password_confirmation',
];
/**
* Report or log an exception.
*
* @param \Exception $exception
* @return void
*/
public function report(Exception $exception)
{
parent::report($exception);
}
/**
* Render an exception into an HTTP response.
*
* @param \Illuminate\Http\Request $request
* @param \Exception $exception
* @return \Illuminate\Http\Response
*/
public function render($request, Exception $exception)
{
return parent::render($request, $exception);
}
}

51
app/Models/Frame.php Normal file
View File

@ -0,0 +1,51 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Frame extends Model
{
/**
* Fetch a specific frame from the database
*
* @param int $page
* @param string $frame
* @return mixed
*/
public function fetch(int $page,string $frame): \App\Classes\Frame
{
if ($page == '999' and $frame == 'a')
{
return new \App\Classes\Frame(\App\Classes\Frame::testFrame());
}
return new \App\Classes\Frame($this->where('frame_id',$page)->where('subframe_id',$frame)->firstOrFail());
}
/**
* Return the frame cost
*
* @return int
*/
public function getCostAttribute()
{
// @todo NOT in DB
return rand(0,999);
}
public function hasFlag(string $flag)
{
// @todo When flags is in the DB update this.
return isset($this->flags) ? in_array($flag,$this->flags,FALSE) : FALSE;
}
/**
* Frame Types
*/
public function type()
{
// @todo in DB
return isset($this->frametype) ? $this->frametype : 'i';
}
}

View File

@ -0,0 +1,28 @@
<?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider
{
/**
* Bootstrap any application services.
*
* @return void
*/
public function boot()
{
//
}
/**
* Register any application services.
*
* @return void
*/
public function register()
{
//
}
}

View File

@ -0,0 +1,30 @@
<?php
namespace App\Providers;
use Illuminate\Support\Facades\Gate;
use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;
class AuthServiceProvider extends ServiceProvider
{
/**
* The policy mappings for the application.
*
* @var array
*/
protected $policies = [
'App\Model' => 'App\Policies\ModelPolicy',
];
/**
* Register any authentication / authorization services.
*
* @return void
*/
public function boot()
{
$this->registerPolicies();
//
}
}

View File

@ -0,0 +1,21 @@
<?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Facades\Broadcast;
class BroadcastServiceProvider extends ServiceProvider
{
/**
* Bootstrap any application services.
*
* @return void
*/
public function boot()
{
Broadcast::routes();
require base_path('routes/channels.php');
}
}

View File

@ -0,0 +1,34 @@
<?php
namespace App\Providers;
use Illuminate\Support\Facades\Event;
use Illuminate\Auth\Events\Registered;
use Illuminate\Auth\Listeners\SendEmailVerificationNotification;
use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider;
class EventServiceProvider extends ServiceProvider
{
/**
* The event listener mappings for the application.
*
* @var array
*/
protected $listen = [
Registered::class => [
SendEmailVerificationNotification::class,
],
];
/**
* Register any events for your application.
*
* @return void
*/
public function boot()
{
parent::boot();
//
}
}

View File

@ -0,0 +1,73 @@
<?php
namespace App\Providers;
use Illuminate\Support\Facades\Route;
use Illuminate\Foundation\Support\Providers\RouteServiceProvider as ServiceProvider;
class RouteServiceProvider extends ServiceProvider
{
/**
* This namespace is applied to your controller routes.
*
* In addition, it is set as the URL generator's root namespace.
*
* @var string
*/
protected $namespace = 'App\Http\Controllers';
/**
* Define your route model bindings, pattern filters, etc.
*
* @return void
*/
public function boot()
{
//
parent::boot();
}
/**
* Define the routes for the application.
*
* @return void
*/
public function map()
{
$this->mapApiRoutes();
$this->mapWebRoutes();
//
}
/**
* Define the "web" routes for the application.
*
* These routes all receive session state, CSRF protection, etc.
*
* @return void
*/
protected function mapWebRoutes()
{
Route::middleware('web')
->namespace($this->namespace)
->group(base_path('routes/web.php'));
}
/**
* Define the "api" routes for the application.
*
* These routes are typically stateless.
*
* @return void
*/
protected function mapApiRoutes()
{
Route::prefix('api')
->middleware('api')
->namespace($this->namespace)
->group(base_path('routes/api.php'));
}
}

53
artisan Executable file
View File

@ -0,0 +1,53 @@
#!/usr/bin/env php
<?php
define('LARAVEL_START', microtime(true));
/*
|--------------------------------------------------------------------------
| Register The Auto Loader
|--------------------------------------------------------------------------
|
| Composer provides a convenient, automatically generated class loader
| for our application. We just need to utilize it! We'll require it
| into the script here so that we do not have to worry about the
| loading of any our classes "manually". Feels great to relax.
|
*/
require __DIR__.'/vendor/autoload.php';
$app = require_once __DIR__.'/bootstrap/app.php';
/*
|--------------------------------------------------------------------------
| Run The Artisan Application
|--------------------------------------------------------------------------
|
| When we run the console application, the current CLI command will be
| executed in this console and the response sent back to a terminal
| or another output device for the developers. Here goes nothing!
|
*/
$kernel = $app->make(Illuminate\Contracts\Console\Kernel::class);
$status = $kernel->handle(
$input = new Symfony\Component\Console\Input\ArgvInput,
new Symfony\Component\Console\Output\ConsoleOutput
);
/*
|--------------------------------------------------------------------------
| Shutdown The Application
|--------------------------------------------------------------------------
|
| Once Artisan has finished running, we will fire off the shutdown events
| so that any final work may be done by the application before we shut
| down the process. This is the last thing to happen to the request.
|
*/
$kernel->terminate($input, $status);
exit($status);

55
bootstrap/app.php Normal file
View File

@ -0,0 +1,55 @@
<?php
/*
|--------------------------------------------------------------------------
| Create The Application
|--------------------------------------------------------------------------
|
| The first thing we will do is create a new Laravel application instance
| which serves as the "glue" for all the components of Laravel, and is
| the IoC container for the system binding all of the various parts.
|
*/
$app = new Illuminate\Foundation\Application(
$_ENV['APP_BASE_PATH'] ?? dirname(__DIR__)
);
/*
|--------------------------------------------------------------------------
| Bind Important Interfaces
|--------------------------------------------------------------------------
|
| Next, we need to bind some important interfaces into the container so
| we will be able to resolve them when needed. The kernels serve the
| incoming requests to this application from both the web and CLI.
|
*/
$app->singleton(
Illuminate\Contracts\Http\Kernel::class,
App\Http\Kernel::class
);
$app->singleton(
Illuminate\Contracts\Console\Kernel::class,
App\Console\Kernel::class
);
$app->singleton(
Illuminate\Contracts\Debug\ExceptionHandler::class,
App\Exceptions\Handler::class
);
/*
|--------------------------------------------------------------------------
| Return The Application
|--------------------------------------------------------------------------
|
| This script returns the application instance. The instance is given to
| the calling script so we can separate the building of the instances
| from the actual running of the application and sending responses.
|
*/
return $app;

2
bootstrap/cache/.gitignore vendored Normal file
View File

@ -0,0 +1,2 @@
*
!.gitignore

84
composer.json Normal file
View File

@ -0,0 +1,84 @@
{
"name": "laravel/laravel",
"type": "project",
"description": "The Laravel Framework.",
"keywords": [
"framework",
"laravel"
],
"license": "MIT",
"require": {
"php": "^7.1.3",
"fideloper/proxy": "^4.0",
"laravel/framework": "5.7.*",
"laravel/tinker": "^1.0",
"lukaszkujawa/php-multithreaded-socket-server": "0.0.*"
},
"require-dev": {
"beyondcode/laravel-dump-server": "^1.0",
"filp/whoops": "^2.0",
"fzaninotto/faker": "^1.4",
"mockery/mockery": "^1.0",
"nunomaduro/collision": "^2.0",
"phpunit/phpunit": "^7.0"
},
"config": {
"optimize-autoloader": true,
"preferred-install": "dist",
"sort-packages": true
},
"extra": {
"laravel": {
"dont-discover": []
}
},
"autoload": {
"psr-0": {
"Sock\\": "vendor/lukaszkujawa/php-multithreaded-socket-server/sock/"
},
"psr-4": {
"App\\": "app/"
},
"files": [
"bootstrap/constants.php"
],
"classmap": [
"database/seeds",
"database/factories"
]
},
"autoload-dev": {
"psr-4": {
"Tests\\": "tests/"
}
},
"minimum-stability": "dev",
"prefer-stable": true,
"repositories": {
"sock": {
"type": "package",
"package": {
"name": "lukaszkujawa/php-multithreaded-socket-server",
"description": "Sag with fixed unitialized variables",
"version": "0.0.1",
"source": {
"url": "https://github.com/lukaszkujawa/php-multithreaded-socket-server",
"type": "git",
"reference": "master"
}
}
}
},
"scripts": {
"post-autoload-dump": [
"Illuminate\\Foundation\\ComposerScripts::postAutoloadDump",
"@php artisan package:discover --ansi"
],
"post-root-package-install": [
"@php -r \"file_exists('.env') || copy('.env.example', '.env');\""
],
"post-create-project-cmd": [
"@php artisan key:generate --ansi"
]
}
}

4149
composer.lock generated Normal file

File diff suppressed because it is too large Load Diff

241
config/app.php Normal file
View File

@ -0,0 +1,241 @@
<?php
return [
/*
|--------------------------------------------------------------------------
| Application Name
|--------------------------------------------------------------------------
|
| This value is the name of your application. This value is used when the
| framework needs to place the application's name in a notification or
| any other location as required by the application or its packages.
|
*/
'name' => env('APP_NAME', 'Laravel'),
/*
|--------------------------------------------------------------------------
| Application Environment
|--------------------------------------------------------------------------
|
| This value determines the "environment" your application is currently
| running in. This may determine how you prefer to configure various
| services the application utilizes. Set this in your ".env" file.
|
*/
'env' => env('APP_ENV', 'production'),
/*
|--------------------------------------------------------------------------
| Application Debug Mode
|--------------------------------------------------------------------------
|
| When your application is in debug mode, detailed error messages with
| stack traces will be shown on every error that occurs within your
| application. If disabled, a simple generic error page is shown.
|
*/
'debug' => env('APP_DEBUG', false),
/*
|--------------------------------------------------------------------------
| Application URL
|--------------------------------------------------------------------------
|
| This URL is used by the console to properly generate URLs when using
| the Artisan command line tool. You should set this to the root of
| your application so that it is used when running Artisan tasks.
|
*/
'url' => env('APP_URL', 'http://localhost'),
'asset_url' => env('ASSET_URL', null),
/*
|--------------------------------------------------------------------------
| Application Port
|--------------------------------------------------------------------------
|
| Videotex Server Port
|
*/
'bind' => env('APP_BIND','0.0.0.0'),
'port' => env('APP_PORT',516),
/*
|--------------------------------------------------------------------------
| Application Timezone
|--------------------------------------------------------------------------
|
| Here you may specify the default timezone for your application, which
| will be used by the PHP date and date-time functions. We have gone
| ahead and set this to a sensible default for you out of the box.
|
*/
'timezone' => 'UTC',
/*
|--------------------------------------------------------------------------
| Application Locale Configuration
|--------------------------------------------------------------------------
|
| The application locale determines the default locale that will be used
| by the translation service provider. You are free to set this value
| to any of the locales which will be supported by the application.
|
*/
'locale' => 'en',
/*
|--------------------------------------------------------------------------
| Application Fallback Locale
|--------------------------------------------------------------------------
|
| The fallback locale determines the locale to use when the current one
| is not available. You may change the value to correspond to any of
| the language folders that are provided through your application.
|
*/
'fallback_locale' => 'en',
/*
|--------------------------------------------------------------------------
| Faker Locale
|--------------------------------------------------------------------------
|
| This locale will be used by the Faker PHP library when generating fake
| data for your database seeds. For example, this will be used to get
| localized telephone numbers, street address information and more.
|
*/
'faker_locale' => 'en_US',
/*
|--------------------------------------------------------------------------
| Encryption Key
|--------------------------------------------------------------------------
|
| This key is used by the Illuminate encrypter service and should be set
| to a random, 32 character string, otherwise these encrypted strings
| will not be safe. Please do this before deploying an application!
|
*/
'key' => env('APP_KEY'),
'cipher' => 'AES-256-CBC',
/*
|--------------------------------------------------------------------------
| Autoloaded Service Providers
|--------------------------------------------------------------------------
|
| The service providers listed here will be automatically loaded on the
| request to your application. Feel free to add your own services to
| this array to grant expanded functionality to your applications.
|
*/
'providers' => [
/*
* Laravel Framework Service Providers...
*/
Illuminate\Auth\AuthServiceProvider::class,
Illuminate\Broadcasting\BroadcastServiceProvider::class,
Illuminate\Bus\BusServiceProvider::class,
Illuminate\Cache\CacheServiceProvider::class,
Illuminate\Foundation\Providers\ConsoleSupportServiceProvider::class,
Illuminate\Cookie\CookieServiceProvider::class,
Illuminate\Database\DatabaseServiceProvider::class,
Illuminate\Encryption\EncryptionServiceProvider::class,
Illuminate\Filesystem\FilesystemServiceProvider::class,
Illuminate\Foundation\Providers\FoundationServiceProvider::class,
Illuminate\Hashing\HashServiceProvider::class,
Illuminate\Mail\MailServiceProvider::class,
Illuminate\Notifications\NotificationServiceProvider::class,
Illuminate\Pagination\PaginationServiceProvider::class,
Illuminate\Pipeline\PipelineServiceProvider::class,
Illuminate\Queue\QueueServiceProvider::class,
Illuminate\Redis\RedisServiceProvider::class,
Illuminate\Auth\Passwords\PasswordResetServiceProvider::class,
Illuminate\Session\SessionServiceProvider::class,
Illuminate\Translation\TranslationServiceProvider::class,
Illuminate\Validation\ValidationServiceProvider::class,
Illuminate\View\ViewServiceProvider::class,
/*
* Package Service Providers...
*/
/*
* Application Service Providers...
*/
App\Providers\AppServiceProvider::class,
App\Providers\AuthServiceProvider::class,
// App\Providers\BroadcastServiceProvider::class,
App\Providers\EventServiceProvider::class,
App\Providers\RouteServiceProvider::class,
],
/*
|--------------------------------------------------------------------------
| Class Aliases
|--------------------------------------------------------------------------
|
| This array of class aliases will be registered when this application
| is started. However, feel free to register as many as you wish as
| the aliases are "lazy" loaded so they don't hinder performance.
|
*/
'aliases' => [
'App' => Illuminate\Support\Facades\App::class,
'Artisan' => Illuminate\Support\Facades\Artisan::class,
'Auth' => Illuminate\Support\Facades\Auth::class,
'Blade' => Illuminate\Support\Facades\Blade::class,
'Broadcast' => Illuminate\Support\Facades\Broadcast::class,
'Bus' => Illuminate\Support\Facades\Bus::class,
'Cache' => Illuminate\Support\Facades\Cache::class,
'Config' => Illuminate\Support\Facades\Config::class,
'Cookie' => Illuminate\Support\Facades\Cookie::class,
'Crypt' => Illuminate\Support\Facades\Crypt::class,
'DB' => Illuminate\Support\Facades\DB::class,
'Eloquent' => Illuminate\Database\Eloquent\Model::class,
'Event' => Illuminate\Support\Facades\Event::class,
'File' => Illuminate\Support\Facades\File::class,
'Gate' => Illuminate\Support\Facades\Gate::class,
'Hash' => Illuminate\Support\Facades\Hash::class,
'Lang' => Illuminate\Support\Facades\Lang::class,
'Log' => Illuminate\Support\Facades\Log::class,
'Mail' => Illuminate\Support\Facades\Mail::class,
'Notification' => Illuminate\Support\Facades\Notification::class,
'Password' => Illuminate\Support\Facades\Password::class,
'Queue' => Illuminate\Support\Facades\Queue::class,
'Redirect' => Illuminate\Support\Facades\Redirect::class,
'Redis' => Illuminate\Support\Facades\Redis::class,
'Request' => Illuminate\Support\Facades\Request::class,
'Response' => Illuminate\Support\Facades\Response::class,
'Route' => Illuminate\Support\Facades\Route::class,
'Schema' => Illuminate\Support\Facades\Schema::class,
'Session' => Illuminate\Support\Facades\Session::class,
'Storage' => Illuminate\Support\Facades\Storage::class,
'URL' => Illuminate\Support\Facades\URL::class,
'Validator' => Illuminate\Support\Facades\Validator::class,
'View' => Illuminate\Support\Facades\View::class,
],
];

84
config/constants.php Normal file
View File

@ -0,0 +1,84 @@
<?php
define('MODE_BL',1); // Typing a * command on the baseline
define('MODE_FIELD',2); // typing into an imput field
define('MODE_WARPTO',3); // awaiting selection of a timewarp
define('MODE_COMPLETE',4); // Entry of data is complete ..
define('MODE_SUBMITRF',5); // asking if should send or not.
define('MODE_RFSENT',6);
define('MODE_RFERROR',7);
define('MODE_RFNOTSENT',8);
define('ACTION_RELOAD',1);
define('ACTION_GOTO',2);
define('ACTION_BACKUP',3);
define('ACTION_NEXT',4);
define('ACTION_INFO',5);
define('ACTION_TERMINATE',6);
define('ACTION_SUBMITRF',7); // Offer to submit a response frame
define('ACTION_STAR',8);
define('CON', chr(17)); // Cursor On
define('COFF', chr(20)); // Cursor Off
define('HOME', chr(30));
define('LEFT', chr(8)); // Move Cursor
define('RIGHT', chr(9)); // Move Cursor
define('DOWN', chr(10)); // Move Cursor
define('UP', chr(11)); // Move Cursor
define('CR', chr(13));
define('LF', chr(10));
define('CLS', chr(12));
define('ESC', chr(27));
define('HASH','_'); // Enter
define('STAR','*'); // Star Entry
// Keyboard presses
define('KEY_LEFT',chr(136));
define('KEY_RIGHT',chr(137));
define('KEY_DOWN',chr(138));
define('KEY_UP',chr(139));
// NOTE: This consts are effective output
define('RED', ESC . 'A');
define('GREEN', ESC . 'B');
define('YELLOW', ESC . 'C');
define('BLUE', ESC . 'D');
define('MAGENTA', ESC . 'E');
define('CYAN', ESC . 'F');
define('WHITE', ESC . 'G');
define('NEWBG', ESC . ']');
// Raw attributes - used when storing frames.
define('R_RED',chr(1));
define('R_GREEN',chr(2));
define('R_YELLOW',chr(3));
define('R_BLUE',chr(4));
define('R_MAGENT',chr(5));
define('R_CYAN',chr(6));
define('R_WHITE',chr(7));
define('FLASH',chr(8));
define('TCP_IAC',chr(255));
define('TCP_DONT',chr(254));
define('TCP_DO',chr(253));
define('TCP_WONT',chr(252));
define('TCP_WILL',chr(251));
define('TCP_SB',chr(250));
define('TCP_AYT',chr(246));
define('TCP_SE',chr(240));
define('TCP_OPT_LINEMODE',chr(34));
define('TCP_OPT_TERMTYPE',chr(24));
define('TCP_OPT_SUP_GOAHEAD',chr(3));
define('TCP_OPT_ECHO',chr(1));
define('TCP_BINARY',chr(0));
define('MSG_SENDORNOT', GREEN . 'KEY 1 TO SEND, 2 NOT TO SEND');
define('MSG_SENT', GREEN . 'MESSAGE SENT - KEY _ TO CONTINUE');
define('MSG_NOTSENT', GREEN . 'MESSAGE NOT SENT - KEY _ TO CONTINUE');
define('ERR_ROUTE', WHITE . 'MISTAKE?' . GREEN . 'TRY AGAIN OR TELL US ON *36_');
define('ERR_PAGE', ERR_ROUTE);
define('ERR_PRIVATE', WHITE . 'PRIVATE PAGE' . GREEN . '- FOR EXPLANATION *37_..');
define('ERR_DATABASE', RED . 'UNAVAILABLE AT PRESENT - PLSE TRY LATER');
define('ERR_NOTSENT', WHITE . 'MESSAGE NOT SENT DUE TO AN ERROR');

131
config/database.php Normal file
View File

@ -0,0 +1,131 @@
<?php
return [
/*
|--------------------------------------------------------------------------
| Default Database Connection Name
|--------------------------------------------------------------------------
|
| Here you may specify which of the database connections below you wish
| to use as your default connection for all database work. Of course
| you may use many connections at once using the Database library.
|
*/
'default' => env('DB_CONNECTION', 'mysql'),
/*
|--------------------------------------------------------------------------
| Database Connections
|--------------------------------------------------------------------------
|
| Here are each of the database connections setup for your application.
| Of course, examples of configuring each database platform that is
| supported by Laravel is shown below to make development simple.
|
|
| All database work in Laravel is done through the PHP PDO facilities
| so make sure you have the driver for your particular database of
| choice installed on your machine before you begin development.
|
*/
'connections' => [
'sqlite' => [
'driver' => 'sqlite',
'database' => env('DB_DATABASE', database_path('database.sqlite')),
'prefix' => '',
'foreign_key_constraints' => env('DB_FOREIGN_KEYS', true),
],
'mysql' => [
'driver' => 'mysql',
'host' => env('DB_HOST', '127.0.0.1'),
'port' => env('DB_PORT', '3306'),
'database' => env('DB_DATABASE', 'forge'),
'username' => env('DB_USERNAME', 'forge'),
'password' => env('DB_PASSWORD', ''),
'unix_socket' => env('DB_SOCKET', ''),
'charset' => 'utf8mb4',
'collation' => 'utf8mb4_unicode_ci',
'prefix' => '',
'prefix_indexes' => true,
'strict' => true,
'engine' => null,
],
'pgsql' => [
'driver' => 'pgsql',
'host' => env('DB_HOST', '127.0.0.1'),
'port' => env('DB_PORT', '5432'),
'database' => env('DB_DATABASE', 'forge'),
'username' => env('DB_USERNAME', 'forge'),
'password' => env('DB_PASSWORD', ''),
'charset' => 'utf8',
'prefix' => '',
'prefix_indexes' => true,
'schema' => 'public',
'sslmode' => 'prefer',
],
'sqlsrv' => [
'driver' => 'sqlsrv',
'host' => env('DB_HOST', 'localhost'),
'port' => env('DB_PORT', '1433'),
'database' => env('DB_DATABASE', 'forge'),
'username' => env('DB_USERNAME', 'forge'),
'password' => env('DB_PASSWORD', ''),
'charset' => 'utf8',
'prefix' => '',
'prefix_indexes' => true,
],
],
/*
|--------------------------------------------------------------------------
| Migration Repository Table
|--------------------------------------------------------------------------
|
| This table keeps track of all the migrations that have already run for
| your application. Using this information, we can determine which of
| the migrations on disk haven't actually been run in the database.
|
*/
'migrations' => 'migrations',
/*
|--------------------------------------------------------------------------
| Redis Databases
|--------------------------------------------------------------------------
|
| Redis is an open source, fast, and advanced key-value store that also
| provides a richer body of commands than a typical key-value system
| such as APC or Memcached. Laravel makes it easy to dig right in.
|
*/
'redis' => [
'client' => 'predis',
'default' => [
'host' => env('REDIS_HOST', '127.0.0.1'),
'password' => env('REDIS_PASSWORD', null),
'port' => env('REDIS_PORT', 6379),
'database' => env('REDIS_DB', 0),
],
'cache' => [
'host' => env('REDIS_HOST', '127.0.0.1'),
'password' => env('REDIS_PASSWORD', null),
'port' => env('REDIS_PORT', 6379),
'database' => env('REDIS_CACHE_DB', 1),
],
],
];

1
database/.gitignore vendored Normal file
View File

@ -0,0 +1 @@
*.sqlite

View File

@ -0,0 +1,24 @@
<?php
use Faker\Generator as Faker;
/*
|--------------------------------------------------------------------------
| Model Factories
|--------------------------------------------------------------------------
|
| This directory should contain each of the model factory definitions for
| your application. Factories provide a convenient way to generate new
| model instances for testing / seeding your application's database.
|
*/
$factory->define(App\User::class, function (Faker $faker) {
return [
'name' => $faker->name,
'email' => $faker->unique()->safeEmail,
'email_verified_at' => now(),
'password' => '$2y$10$TKh8H1.PfQx37YgCzwiKb.KjNyWgaHb9cbcoQgdIVFlYg7B77UdFm', // secret
'remember_token' => str_random(10),
];
});

0
database/migrations/.gitignore vendored Normal file
View File

View File

@ -0,0 +1,16 @@
<?php
use Illuminate\Database\Seeder;
class DatabaseSeeder extends Seeder
{
/**
* Seed the application's database.
*
* @return void
*/
public function run()
{
// $this->call(UsersTableSeeder::class);
}
}

22
package.json Normal file
View File

@ -0,0 +1,22 @@
{
"private": true,
"scripts": {
"dev": "npm run development",
"development": "cross-env NODE_ENV=development node_modules/webpack/bin/webpack.js --progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js",
"watch": "npm run development -- --watch",
"watch-poll": "npm run watch -- --watch-poll",
"hot": "cross-env NODE_ENV=development node_modules/webpack-dev-server/bin/webpack-dev-server.js --inline --hot --config=node_modules/laravel-mix/setup/webpack.config.js",
"prod": "npm run production",
"production": "cross-env NODE_ENV=production node_modules/webpack/bin/webpack.js --no-progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js"
},
"devDependencies": {
"axios": "^0.18",
"bootstrap": "^4.0.0",
"cross-env": "^5.1",
"jquery": "^3.2",
"laravel-mix": "^2.0",
"lodash": "^4.17.5",
"popper.js": "^1.12",
"vue": "^2.5.17"
}
}

33
phpunit.xml Normal file
View File

@ -0,0 +1,33 @@
<?xml version="1.0" encoding="UTF-8"?>
<phpunit backupGlobals="false"
backupStaticAttributes="false"
bootstrap="vendor/autoload.php"
colors="true"
convertErrorsToExceptions="true"
convertNoticesToExceptions="true"
convertWarningsToExceptions="true"
processIsolation="false"
stopOnFailure="false">
<testsuites>
<testsuite name="Unit">
<directory suffix="Test.php">./tests/Unit</directory>
</testsuite>
<testsuite name="Feature">
<directory suffix="Test.php">./tests/Feature</directory>
</testsuite>
</testsuites>
<filter>
<whitelist processUncoveredFilesFromWhitelist="true">
<directory suffix=".php">./app</directory>
</whitelist>
</filter>
<php>
<env name="APP_ENV" value="testing"/>
<env name="BCRYPT_ROUNDS" value="4"/>
<env name="CACHE_DRIVER" value="array"/>
<env name="MAIL_DRIVER" value="array"/>
<env name="QUEUE_CONNECTION" value="sync"/>
<env name="SESSION_DRIVER" value="array"/>
</php>
</phpunit>

21
public/.htaccess Normal file
View File

@ -0,0 +1,21 @@
<IfModule mod_rewrite.c>
<IfModule mod_negotiation.c>
Options -MultiViews -Indexes
</IfModule>
RewriteEngine On
# Handle Authorization Header
RewriteCond %{HTTP:Authorization} .
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
# Redirect Trailing Slashes If Not A Folder...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} (.+)/$
RewriteRule ^ %1 [L,R=301]
# Handle Front Controller...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [L]
</IfModule>

2
public/robots.txt Normal file
View File

@ -0,0 +1,2 @@
User-agent: *
Disallow:

21
server.php Normal file
View File

@ -0,0 +1,21 @@
<?php
/**
* Laravel - A PHP Framework For Web Artisans
*
* @package Laravel
* @author Taylor Otwell <taylor@laravel.com>
*/
$uri = urldecode(
parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH)
);
// This file allows us to emulate Apache's "mod_rewrite" functionality from the
// built-in PHP web server. This provides a convenient way to test a Laravel
// application without having installed a "real" web server software here.
if ($uri !== '/' && file_exists(__DIR__.'/public'.$uri)) {
return false;
}
require_once __DIR__.'/public/index.php';

3
storage/app/.gitignore vendored Normal file
View File

@ -0,0 +1,3 @@
*
!public/
!.gitignore

2
storage/app/public/.gitignore vendored Normal file
View File

@ -0,0 +1,2 @@
*
!.gitignore

8
storage/framework/.gitignore vendored Normal file
View File

@ -0,0 +1,8 @@
config.php
routes.php
schedule-*
compiled.php
services.json
events.scanned.php
routes.scanned.php
down

3
storage/framework/cache/.gitignore vendored Normal file
View File

@ -0,0 +1,3 @@
*
!data/
!.gitignore

View File

@ -0,0 +1,2 @@
*
!.gitignore

2
storage/framework/sessions/.gitignore vendored Normal file
View File

@ -0,0 +1,2 @@
*
!.gitignore

2
storage/framework/testing/.gitignore vendored Normal file
View File

@ -0,0 +1,2 @@
*
!.gitignore

2
storage/framework/views/.gitignore vendored Normal file
View File

@ -0,0 +1,2 @@
*
!.gitignore

2
storage/logs/.gitignore vendored Normal file
View File

@ -0,0 +1,2 @@
*
!.gitignore

View File

@ -1,958 +0,0 @@
<?php
/**
* Simple Viewdata Server
*
* @version $Id$
* @copyright 2018
*
*
* Socket code based on an example at https://github.com/lukaszkujawa/php-multithreaded-socket-server
*
* based on early Prestel behaiours
*
* New commands -
* *01 - info about a page
* *02 - Timewarp toggle - when on, will go find page from another date
*
*/
/**
* Check dependencies
*/
if( ! extension_loaded('sockets' ) ) {
echo "This example requires sockets extension (http://www.php.net/manual/en/sockets.installation.php)\n";
exit(-1);
}
if( ! extension_loaded('pcntl' ) ) {
echo "This example requires PCNTL extension (http://www.php.net/manual/en/pcntl.installation.php)\n";
exit(-1);
}
define ('MODE_BL',1); // Typing a * command on the baseline
define ('MODE_FIELD',2); // typing into an imput field
define ('MODE_WARPTO',3); // awaiting selection of a timewarp
define ('MODE_COMPLETE',4); // Entry of data is complete ..
define ('MODE_SUBMITRF',5); // asking if should send or not.
define ('MODE_RFSENT',6);
define ('MODE_RFERROR',7);
define ('MODE_RFNOTSENT',8);
define ('ACTION_RELOAD',1);
define ('ACTION_GOTO',2);
define ('ACTION_BACKUP',3);
define ('ACTION_NEXT',4);
define ('ACTION_INFO',5);
define ('ACTION_TERMINATE',6);
define ('ACTION_SUBMITRF',7); // offer to submit a response frame
define ('ACTION_STAR',8);
define ('CON',chr(17)); // Cursor On
define ('COFF',chr(20)); // Cursor Off
define ('HOME',chr(30));
define ('LEFT', chr(8));
define ('RIGHT',chr(9));
define ('DOWN',chr(10));
define ('UP',chr(11));
define ('CR',chr(13));
define ('LF',chr(10));
define ('CLS',chr(12));
define ('ESC',chr(27));
define ('RED',ESC.'A');
define ('GREEN',ESC.'B');
define ('YELLOW',ESC.'C');
define ('BLUE',ESC.'D');
define ('MAGENTA',ESC.'E');
define ('CYAN',ESC.'F');
define ('WHITE',ESC.'G');
define ('NEWBG',ESC .']');
define ('MSG_TIMEWARP_ON', WHITE . 'TIMEWARP ON' . GREEN . 'VIEW INFO WITH *02');
define ('MSG_TIMEWARP_OFF', WHITE . 'TIMEWARP OFF' . GREEN . 'VIEWING DATE IS FIXED');
define ('MSG_TIMEWARP_TO', GREEN.'TIMEWARP TO %s');
define ('MSG_TIMEWARP', WHITE . 'OTHER VERSIONS EXIST' . GREEN . 'KEY *02 TO VIEW');
define ('MSG_SENDORNOT', GREEN . 'KEY 1 TO SEND, 2 NOT TO SEND');
define ('MSG_SENT', GREEN . 'MESSAGE SENT - KEY _ TO CONTINUE');
define ('MSG_NOTSENT', GREEN . 'MESSAGE NOT SENT - KEY _ TO CONTINUE');
define ('ERR_ROUTE', WHITE . 'MISTAKE?' . GREEN . 'TRY AGAIN OR TELL US ON *36_');
define ('ERR_PAGE', ERR_ROUTE );
define ('ERR_PRIVATE', WHITE . 'PRIVATE PAGE' . GREEN . '- FOR EXPLANATION *37_..');
define ('ERR_DATABASE',RED . 'UNAVAILABLE AT PRESENT - PLSE TRY LATER');
define ('ERR_NOTSENT', WHITE . 'MESSAGE NOT SENT DUE TO AN ERROR');
// This maps field types to user data or system data.
$fieldmap = array('s' => 'systel', 'n' =>'username', 'a' => 'address#', 'd' => '%date');
$fieldoptions = array('f' => array('edit' => true));
include_once('classes/vvdatabase.class.php');
include_once('classes/vv.class.php');
if (count($argv) == 1) {
include_once('config/config.php');
} else {
if (count($argv) == 3 && $argv[1] == '-c') {
include_once('config/' . $argv[2]);
}
}
$db = new vvdb();
// Connect to database. Returns error message if unable to connect.
$r = $db->connect($config['dbserver'],$config['database'],$config['dbuser'], $config['dbpass']);
if (!empty($r)) {
http_response_code(500);
die ($r);
}
/**
* Connection handler
*/
function onConnect( $client ) {
global $config;
global $fieldoptions;
$pid = pcntl_fork();
if ($pid == -1) {
die('could not fork');
} else if ($pid) {
// parent process
return;
}
$read = '';
printf( "[%s] Connected at port %d\n", $client->getaddress(), $client->getPort() );
$client->send(CLS . "Connecting..");
$db = new vvdb();
// Connect to database. Returns error message if unable to connect.
$r = $db->connect($config['dbserver'],$config['database'],$config['dbuser'], $config['dbpass']);
if (!empty($r)) {
http_response_code(500);
$client->send(CLS . UP . ERR_DATABASE);
die ($r);
}
// $user will eventually contain validated user details.
$user = array( 'systel' => '019990001',
'username' => 'DEMONSTRATION DATA USER',
'address1' => '8 HERBAL HILL',
'address2' => 'LONDON',
'address3' => 'EC1R 5EJ',
'address4' => '',
'address5' => '',
'CUGS' => array( 7800, 15500), // Closed User Groups this user has access to
);
$history = array(); // backup history
$cmd = ''; // current *command being typed in
$mode = false; // input mode.
$prevmode = false; // previous mode
$timewarp = false;
$action = ACTION_GOTO; // do something if set. used here to trigger a goto to the login form.
if (isset($config['loginpage'])) {
$page = $config['loginpage'];
$subpage = 'a';
} else if (!empty($service['start_page'])) {
$page = $service['start_page'];
$subpage = 'a';
} else {
$page = '1'; // next page
$subpage = 'a';
}
$curpage = ''; // current page
$cursub = '';
$curfield = null; // current input field
$curfp = 0; // current field, position within.
$blp = 0; // botton line polluted (by this no. of characters)
$resetpsn = false; // flag to reset position (used in fields)
$service = $db->getServiceById($config['service_id']);
$varient = $db->getAllVarients($config['service_id'], $config['varient_id']);
if ($varient === false) {
die ("no varient");
}
$varient = reset($varient);
$matches = array();
if (preg_match('@'.$service['page_format'].'@',$service['start_frame'],$matches)) {
$page = $matches[1];
$subpage = $matches[2];
echo " Using start page ".$page.$subpage."\n";
}
// $start = $service['start_frame'];
// where to start from
while( $action != ACTION_TERMINATE ) {
/*
This section deals with a keypress
*/
$read = $client->read(1);
if( $read != '' ) {
printf("mode:%s cmd:%s page:%s Received %s, (%s)\n",$mode, $cmd,$page,$read, ord($read));
switch($mode){
/*
Currently accepting keypresses into an input field on an RF
*/
case MODE_FIELD: // entering data into a field
$cmd = '';
$action = false;
switch($pagedata['type']){
case 'a': // response frame
switch ($read) {
case '_': //# ends field entry
$curfield ++; //skip to next field
if ($curfield < count($fields)) { // skip past non-editable fields
for ($i = $curfield; $i < count($fields); $i++) {
if (isset($fieldoptions[$fields[$i]['type']]) &&
$fieldoptions[$fields[$i]['type']]['edit']) {
$curfield = $i;
break;
}
}
if ($curfield !== false) {
$client->send(outputPosition($fields[$curfield]['x'],$fields[$curfield]['y']).CON);
$mode = MODE_FIELD;
$fielddate[$curfield] = '';
} else {
// there were no (more) editable fields.
$action = ACTION_SUBMITRF;
}
} else {
// done them all editable fields.
$action = ACTION_SUBMITRF;
}
break;
case '*':
$prevmode = MODE_FIELD;
$action = ACTION_STAR;
break;
case chr(8): // left
if ($curfp) {
$client->send($read);
$curfp--;
};
break;
case chr(9): // right
if ($curfp < $fields[$curfield]['length']) {
$client->send($read);
$curfp++;
};
break;
case chr(10): // down
if ($curfp + 40 < $fields[$curfield]['length']) {
$client->send($read);
$curfp = $curfp + 40;
};
break;
case chr(11): // up
if ($curfp - 40 >= 0) {
$client->send($read);
$curfp = $curfp - 40;
};
break;
case chr(13): // CR
if ($curfp + $fields[$curfield]['x'] > 40) { // on second or later line of a field
$client->send($read);
$curfp = (($curfp + $fields[$curfield]['x'])%40)*40;
} else {
$client->send(outputPosition($fields[$curfield]['x'],$fields[$curfield]['y']).CON);
$curfp = 0;
}
break;
case chr(27): // Escape ?
break; ;
default:
if (ord($read) > 31 && $curfp < $fields[$curfield]['length']) {
$fielddata[$curfield]{$curfp} = $read;
$curfp++;
$client->send($read);
}
} // switch character pressed
break;
default: // other frame types ... shouldn't get here
;
} // switch frame types
break;
/*
Currently waiting at the Key 1 to send, 2 not to send prompt.
*/
case MODE_SUBMITRF:
switch($read){
case '1':
if(mail('robert@irrelevant.com', $service['service_name'], implode("\n",$fielddata))) {
sendBaseline($client, $blp, MSG_SENT);
$mode = MODE_RFSENT;
} else {
sendBaseline($client, $blp, ERR_NOTSENT);
$mode = MODE_RFERROR;
}
break;
case '2':
sendBaseline($client, $blp, MSG_NOTSENT);;
$mode = MODE_RFNOTSENT;
break;
case '*':
$action = ACTION_STAR;
break;
default:
;
} // switch;
break;
/*
Message sent key # to continue
*/
case MODE_RFSENT:
$client->send(COFF);
if ($read == '_') {
if (!empty($pagedata['route1'])) {
$action = ACTION_GOTO;
$page = $pagedata['route1'];
$subpage = 'a';
} else if ($r = $db->getFrame($service['service_id'],$varient['varient_id'],$page,chr(1+ord($subpage)))) {
$action = ACTION_GOTO;
$page = $curpage;
$subpage = chr(1+ord($subpage));
} else if (!empty($pagedata['route0'])) {
$action = ACTION_GOTO;
$page = $pagedata['route0'];
$subpage = 'a';
} else {
$action = ACTION_GOTO;
$page = '0';
$subpage = 'a';
}
} else if ($read == '*') {
$action = ACTION_STAR;
break;
}
break;
/*
message not sent, key # to continue
*/
case MODE_RFNOTSENT:
case MODE_RFERROR:
$client->send(COFF);
if ($read == '_') {
if (!empty($pagedata['route2'])) {
$action = ACTION_GOTO;
$page = $pagedata['route2'];
$subpage = 'a';
} else if ($r = $db->getFrame($service['service_id'],$varient['varient_id'],$page,chr(1+ord($subpage)))) {
$action = ACTION_GOTO;
$page = $curpage;
$subpage = chr(1+ord($subpage));
} else if (!empty($pagedata['route0'])) {
$action = ACTION_GOTO;
$page = $pagedata['route0'];
$subpage = 'a';
} else {
$action = ACTION_GOTO;
$page = '0';
$subpage = 'a';
}
} else if ($read == '*') {
$action = ACTION_STAR;
break;
}
break;
/*
List of alternate options has been presented
*/
case MODE_WARPTO: // expecting a timewarp selection
if (isset($alts[$read - 1 ])) {
$v = $db->getAllVarients($config['service_id'], $alts[$read - 1]['varient_id']);
if (!empty($v)) {
$varient = reset($v);
$page = $curpage;
$subpage = $cursub;
$action = ACTION_GOTO;
break;
}
}
// if wasn't a valid warpto keypress,
//drop into
/*
Not currently doing anything special.
Should look for route keypresses, * commands, etc.
*/
case false: // not currently doing anything in particular
$cmd = '';
echo "Was idle\n";
switch($read){
case '_': // hash for next subpage
$action = ACTION_NEXT;
break;
case '*': // start a star command!
$action = ACTION_STAR;
break;
case '0': // routing
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
if (isset($pagedata['route' . $read]) && $pagedata['route' . $read] != '*') {
$action = ACTION_GOTO;
$page = $pagedata['route' . $read];
$subpage = 'a';
break;
} else {
sendBaseline($client, $blp, ERR_ROUTE);
$mode = $action = false;
}
break;
default:
;
} // switch;
break;
/*
currently accepting baseline imput after a * was received
*/
case MODE_BL: // entering a baseline command
echo "was waiting for page number\n";
// if it's a number, continue entry
if (strpos('0123456789',$read) !== false) { // numeric
$cmd .= $read;
$client->send($read);
$blp++;
}
// if we hit a special numeric command, deal with it.
if ($cmd === '00') { // refresh page
$client->send(COFF);
$action = ACTION_RELOAD;
$cmd = '';
break;
}
if ($cmd === '09') { // reload page
$client->send(COFF);
$action = ACTION_GOTO;
$cmd = '';
break;
}
if ($cmd === '02') { // new for emulator
$client->send(COFF);
$action = ACTION_INFO;
$cmd = '';
break;
}
if (($cmd === '01')) { // new for emulator
$client->send(COFF);
$timewarp = !$timewarp;
sendBaseline($client, $blp,
( $timewarp ? MSG_TIMEWARP_ON : MSG_TIMEWARP_OFF));
$cmd = '';
$action = $mode = false;
}
// another star aborts the command.
if ($read === "*") { // abort command or reset input field.
$action = false;
sendBaseline($client, $blp, '');
$cmd = '';
if ($prevmode == MODE_FIELD) {
$mode = $prevmode;
$prevmode = false;
$client->send(outputPosition($fields[$curfield]['x'],$fields[$curfield]['y']).CON);
$client->send(str_repeat(' ',$fields[$curfield]['length']));
// tood reset stored entered text
$resetpsn = $curfield;
} else {
$mode = false;
}
break;
}
// user hit # to complete request
if ($read === '_') { // really the # key,
$client->send(COFF);
if ($cmd === '') { // nothing typed between * and #
$action = ACTION_BACKUP;
} else { // *# means go back
$page = $cmd;
$subpage = 'a';
$action = ACTION_GOTO;
}
$cmd = ''; // finished with this now
break;
}
break;
default:
echo "not sure what we were doing\n";
} // switch $mode
} // something in $read
/*
This section performs some action if it is deemed necessary
*/
if ($action) {
echo "Performing action $action\n";
}
switch($action){
case ACTION_STAR:
echo " star command started\n";
sendBaseline($client, $blp, GREEN . '*', true);
$client->send(CON);
$action = false;
$mode = MODE_BL;
break;
case ACTION_SUBMITRF:
$action = false;
sendBaseline($client, $bpl, MSG_SENDORNOT);
$mode = MODE_SUBMITRF;
break;
case ACTION_BACKUP:
// do we have anywhere to go?
if (count($history) > 1) { // because current page should always be in there.
array_pop($history); // drop current page to reveal previous
}
list($page, $subpage) = end($history); // get new last entry,
echo "Backing up to $page$subpage\n";
// drop into
case ACTION_NEXT:
if ($action == ACTION_NEXT) {
$cursub = $subpage;
$subpage = chr(ord($subpage)+1);
}
case ACTION_GOTO:
// $client->send(HOME . UP . GREEN . "Searching for page $page");
// $blp = 20 + strlenv($page);
// look for requested page
$r = $db->getFrame($service['service_id'],$varient['varient_id'],$page,$subpage);
if (empty($r) && $timewarp) {
$r = $db->getFrame($service['service_id'],null,$page,$subpage);
}
if (empty($r)) {
echo "Couldn't fetch $page$subpage\n";
if ($action == ACTION_NEXT) {
$subpage = $cursub; // put subpage back as it was
}
sendBaseline($client, $blp, ERR_PAGE);
$mode = $action = false;
break;
}
$v = array_merge($varient, array_intersect_key($r, $varient));
$m = $db->getFrameMeta($r['frameunique']);
// set some defaults in case it's an incomplete record
if (!isset($m['type']) || $m['type'] == ' ') {
$m['type'] = 'i';
}
// return array_merge($pagerecord,$pagemeta);
// validate if we have access top it
/* if (isset($m['access']) && $m['access'] == 'n') {
sendBaseline($client, $blp, ERR_PAGE);
$mode = $action = false;
break;
}
if (isset($m['cug']) && is_numeric($m['cug']) && $m['cug'] && !in_array($m['cug'],$usercugs)) {
sendBaseline($client, $blp, ERR_PRIVATE);
$mode = $action = false;
break;
}
*/
// we have access...
if ($r['varient_id'] != $varient['varient_id']) {
if (empty($v['varient_date'])) {
sendBaseline($client, $blp, sprintf(MSG_TIMEWARP_TO, 'unknown date') );
} else {
sendBaseline($client, $blp, sprintf(MSG_TIMEWARP_TO,date('j f Y',strtotime($v['varient_date']))) );
}
$varient = array_merge($varient, array_intersect_key($r, $varient));
}
$pagedata = array_merge($r, $m);
$varient = $v;
$curpage = $page;
$cursub = $subpage;
$cufield = 0;
$curfp = 0;
$pageflags = $db->getFrameTypeFlags($pagedata['type']);
if ($action == ACTION_GOTO || $action == ACTION_NEXT) { // only if new location, not going backwards
$history[] = array($page,$subpage);
}
// drop into
case ACTION_RELOAD:
//
/* if ($pageflags['clear']) {
$output = CLS;
$blp = 0;
} else {
$output = HOME;
}
*/
// print_r($pageflags); print_r($pagedata);
switch($pagedata['type']){
default:
case 'i': // standard frame
if ($timewarp && 1 < count(
$alts = $db->getAlternateFrames($service['service_id'],$varient['varient_id'],$curpage,$cursub)
)) {
$msg = MSG_TIMEWARP;
} else {
$msg = '';
}
$output = getOutput($curpage, $cursub, $pagedata, $pageflags, $msg);
$blp = strlenv($msg);
$client->send($output);
$mode = $action = false;
break;
case 'a': // active frame. Prestel uses this for Response Framea.
if ($timewarp && 1 < count(
$alts = $db->getAlternateFrames($service['service_id'],$varient['varient_id'],$curpage,$cursub)
)) {
$msg = MSG_TIMEWARP;
} else {
$msg = '';
}
// this is a glorious hack to fix three out of 30,000 pages but might
// break lots more.
$pagedata = str_replace(chr(12),chr(27),$pagedata);
// holds data entered by user.
$fielddata = array();
$fields = array();
$output = getOutput($curpage, $cursub, $pagedata, $pageflags, $msg, $user, $fields);
$blp = strlenv($msg);
$client->send($output);
if (count($fields)) {
// need t skip to first field that is..
// of a field type that is editable
// or finish.
$curfield = false;
for ($i = 0; $i < count($fields); $i++) {
if (isset($fieldoptions[$fields[$i]['type']]) &&
$fieldoptions[$fields[$i]['type']]['edit']) {
$curfield = $i;
break;
}
}
$resetpsn = $curfield;
if ($curfield !== false) {
$mode = MODE_FIELD;
} else {
// there were no editable fields.
$mode = MODE_COMPLETE;
}
$curfp = 0;
}
break;
case 't': // terminate
$output = getOutput($curpage, $cursub, $pagedata, $pageflags);
$client->send($output);
$action = ACTION_TERMINATE;
break;
} // switch
break;
case ACTION_INFO: // special emulator command
$mode = false;
$cmd='';
$action = false;
$output = outputPosition(0,0) . WHITE . NEWBG . RED . 'TIMEWARP INFO FOR Pg.' . BLUE . $curpage . $cursub . WHITE;
$output .= outputPosition(0,1) . WHITE . NEWBG . BLUE . 'Service : ' . substr($service['service_name'] . str_repeat(' ',27),0,27) ;
$output .= outputPosition(0,2) . WHITE . NEWBG . BLUE . 'Varient : ' . substr($varient['varient_name'] . str_repeat(' ',27),0,27) ;
$output .= outputPosition(0,3) . WHITE . NEWBG . BLUE . 'Dated : ' . substr(date('j F Y',strtotime($varient['varient_date'])) . str_repeat(' ',27),0,27);
$alts = $db->getAlternateFrames($service['service_id'],$varient['varient_id'],$curpage,$cursub);
if (count($alts) > 1) {
$n = 1;
$output .= outputPosition(0,4) . WHITE . NEWBG . RED . 'ALTERNATIVE VERSIONS:' . str_repeat(' ',16);
$y = 5;
foreach ($alts as $ss){
// if (is_numeric($ss['varient_date'])) {
$date = date('d M Y', strtotime($ss['varient_date']));
// } else {
// $date = 'unknown';
// }
$line = WHITE . NEWBG;
if ($timewarp) {
$line .= RED . $n;
}
$line .= BLUE . $date . ' ' . $ss['varient_name'];
$output .= outputPosition(0,$y) . $line . str_repeat(' ',40-strlenv($line));
$y++;
$n++;
}
if ($timewarp) {
$mode = MODE_WARPTO;
}
}
$client->send($output);
break;
default:
;
} // switch $action
if ($resetpsn !== false && isset($fields[$resetpsn])) {
$client->send(outputPosition($fields[$resetpsn]['x'],$fields[$resetpsn]['y']).CON);
$resetpsn = false;
}
if( $read === null || socket_last_error()) {
printf( "[%s] Disconnected\n", $client->getaddress() );
return false;
}
}
$client->close();
printf( "[%s] Disconnected\n", $client->getaddress() );
}
function strlenv($text){
return strlen($text) - substr_count($text, ESC);
}
function sendBaseline($client, &$blp, $text, $reposition = false){
$client->send(HOME . UP . $text .
( $blp > strlenv($text) ? str_repeat(' ',$blp-strlenv($text)) .
( $reposition ? HOME . UP . str_repeat(RIGHT, strlenv($text)) : '' )
: '')
);
$blp = strlenv($text);
return;
}
function outputPosition($x,$y){
if ($y < 12) {
if ($x < 21) {
return HOME . str_repeat(DOWN, $y) . str_repeat(RIGHT, $x);
} else {
return HOME . str_repeat(DOWN, $y+1) . str_repeat(LEFT, 40-$x);
}
} else {
if ($x < 21) {
return HOME . str_repeat(UP, 24-$y) . str_repeat(RIGHT, $x);
} else {
return HOME . str_repeat(UP, 24-$y) . str_repeat(LEFT, 40-$x);
}
}
}
/*
return a screen output ... $msg sent on baseline just after the cls.
remember to update $blp manually after calling this.
*/
function getOutput($page, $subpage, $pagedata, $pageflags, $msg = '', $user = array(), &$fields = null, &$frame_content = null) {
global $blp;
global $fieldmap;
$price = isset($pagerecord['price']) ? $pagerecord['price'] : 0;
// get textual content.
$text = $pagedata['frame_content'];
if ($pageflags['clear']) {
$output = CLS;
} else {
$output = HOME;
}
if ($msg) {
$output .= UP . $msg . HOME ;
}
$startline = 0;
if ($pageflags['ip']) {
// generate page header (but leave ISP as per frame)
$header = chr(7) . $page . $subpage;
$header .= str_repeat(' ', 12-strlenv($header));
$header .= ($price < 5 ? chr(3) : chr(1)) . substr(" $price",-2) . 'p';
$text = substr_replace($text,$header, 24, 16);
} else {
$startline = 1;
}
if ($startline) {
$output .= str_repeat(DOWN, $startline);
}
$infield = false;
$fieldtype = '';
$fieldlength = '';;
$fieldx = false;
$fieldy = false;
$fieldadrline = 1;
for ($y=$startline; $y<23; $y++ ) {
for ($x=0; $x<40; $x++) {
$posn = $y*40+$x;
$byte = ord($text{$posn})%128;
// check for start-of-field
if ( $byte == 27 ) { // Esc designates start of field (Esc-K is end of edit)
$infield = true;
$fieldtype = ord(substr( $text, $posn + 1, 1))%128;
$fieldlength = 0;
$byte = 32; // display a space there.
} else {
if ($infield) {
if ($byte == $fieldtype) {
$byte = 32; // blank out fields
if ($fieldx === false) {
$fieldx = $x;
$fieldy = $y;
}
$fieldlength++;
// but is it a field that needs filling in?
if (isset($fieldmap[chr($fieldtype)]) ) {
$field = $fieldmap[chr($fieldtype)];
// address field has many lines. increment when hit on first character.
if ($fieldlength == 1 && strpos($field,'#') !== false) {
$field = str_replace('#',$fieldadrline,$field);
$fieldadrline++;
}
// user data
if ($field == '%date') {
$datetime = strtoupper(date('D d M Y H:i:s'));
if ($fieldlength <= strlen($datetime)) {
$byte = ord($datetime{$fieldlength-1});
}
} else if (isset($user[$field])) {
if ($fieldlength <= strlen($user[$field])) {
$byte = ord($user[$field]{$fieldlength-1});
}
} /*else // pre-load field contents. PAM or *00 ?
if (isset($fields[what]['value'])) {
} */
}
} else {
$infield = false;
echo "Field at $fieldx, $fieldy type $fieldtype length $fieldlength \n";
if (is_array($fields)) {
$fields[] = array('type' => chr($fieldtype), 'length' => $fieldlength,
'y' => $fieldy, 'x' => $fieldx);
}
$infield = false;
$fieldx = false;
}
}
}
// truncate end of lines
if ($pageflags['tru'] && substr($text,$y*40+$x,40-$x) === str_repeat(' ',40-$x)) {
$output .= CR . LF;
break;
}
if ($byte < 32) {
$output .= ESC . chr($byte+64);
// echo '^'. chr($byte-64);
} else {
$output .= chr($byte);
//echo "($byte)".chr($byte);
}
$text{$posn} = $byte;
}
//echo "\n";
}
// if we were asked to return the frame content, do so, but modified with any fields
// that were filled in (or blanked)
if (!is_null($frame_content)) {
$frame_content = $text;
}
return $output;
}
require "sock/SocketServer.php";
$server = new \Sock\SocketServer($config['port'], "0.0.0.0");
$server->init();
$server->setConnectionHandler( 'onConnect' );
$server->listen();