Code optimisation and minor function fixes

This commit is contained in:
Deon George 2018-12-05 21:50:38 +11:00
parent 3651a6508a
commit 9c2304869d
5 changed files with 372 additions and 239 deletions

View File

@ -17,10 +17,12 @@ use Illuminate\Support\Facades\Log;
* + Header is on line 1. * + Header is on line 1.
* + Input field is on Line 24. * + Input field is on Line 24.
* + 'i' Frames are info frames, no looking for fields. (Lines 2-23) * + '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. * + 'a' Frames have active frames with responses.
* + 't' Frames terminate the session * + 't' Frames terminate the session
* *
* + Frame types:
* + 'ip' Frames are Information Provider frames - no header added. (Lines 1-23)
*
* To Consider * To Consider
* + 'x' External frames - living in another viewdata server * + 'x' External frames - living in another viewdata server
* *
@ -38,32 +40,55 @@ class Frame
private $cost_length = 7; // 9 (prefixed with a color, suffixed with unit) private $cost_length = 7; // 9 (prefixed with a color, suffixed with unit)
private $cost_unit = 'u'; private $cost_unit = 'u';
private $fieldmap = ['s'=>'systel','n'=>'username','a'=>'address#','d'=>'%date'];
public $fields = NULL; // The fields in this frame. public $fields = NULL; // The fields in this frame.
// Magic Fields that are pre-filled
private $fieldmap = [
'a'=>'address#',
'd'=>'%date',
];
// Fields that are editable
private $fieldoptions = [
'a'=>['edit'=>TRUE], // Address
'p'=>['edit'=>TRUE], // Password
'u'=>['edit'=>TRUE], // User
];
// @todo Move this to the database // @todo Move this to the database
private $header = RED.'T'.BLUE.'E'.GREEN.'S'.YELLOW.'T'.MAGENTA.'!'; private $header = RED.'T'.BLUE.'E'.GREEN.'S'.YELLOW.'T'.MAGENTA.'!';
public function __construct(\App\Models\Frame $o,string $msg=NULL) public function __construct(\App\Models\Frame $o,string $msg=NULL)
{ {
dump(__METHOD__);
$this->frame = $o; $this->frame = $o;
$this->output = $this->hasFlag('clear') ? CLS : HOME; $this->output = $this->hasFlag('clear') ? CLS : HOME;
// If we have a message to display on the bottom line.
if ($msg) if ($msg)
$this->output .= UP.$msg.HOME; $this->output .= UP.$msg.HOME;
$startline = 0;
if (! $this->hasFlag('ip')) { if (! $this->hasFlag('ip')) {
// Set the page header: CUG/Site Name | Page # | Cost // Set the page header: CUG/Site Name | Page # | Cost
$this->output .= $this->render_header($this->header). $this->output .= $this->render_header($this->header).
$this->render_page($this->frame->frame,$this->frame->index). $this->render_page($this->frame->frame,$this->frame->index).
$this->render_cost($this->frame->cost); $this->render_cost($this->frame->cost);
$startline = 1;
} }
// Calculate fields and render output. // Calculate fields and render output.
$this->fields(); $this->fields($startline);
} }
/**
* Render the frame
*
* @return null|string
*/
public function __toString() public function __toString()
{ {
return $this->output; return $this->output;
@ -75,10 +100,12 @@ class Frame
* *
* @param int $startline * @param int $startline
*/ */
public function fields($startline=0) public function fields($startline=0,$fieldchar='.')
{ {
$infield = FALSE; $infield = FALSE; // In a field
$this->fields = collect(); $fieldtype = NULL; // Type of field
$fieldlength = 0; // Length of field
$this->fields = collect(); // Fields in this frame.
if ($startline) if ($startline)
$this->output .= str_repeat(DOWN,$startline); $this->output .= str_repeat(DOWN,$startline);
@ -88,28 +115,30 @@ class Frame
// Scan the frame for a field start // Scan the frame for a field start
for ($y=$startline;$y<=$this->frame_length;$y++) for ($y=$startline;$y<=$this->frame_length;$y++)
{ {
// Fields can only be on a single line
$fieldx = $fieldy = FALSE; $fieldx = $fieldy = FALSE;
for ($x=0;$x<$this->frame_width;$x++) for ($x=0;$x<$this->frame_width;$x++)
{ {
$posn = $y*40+$x; $posn = $y*40+$x;
// If the frame is not big enough, fill it with spaces.
$byte = ord(isset($this->frame->content{$posn}) ? $this->frame->content{$posn} : ' ')%128; $byte = ord(isset($this->frame->content{$posn}) ? $this->frame->content{$posn} : ' ')%128;
// dump(sprintf('Y: %s,X: %s, POSN: %s, BYTE: %s',$y,$x,$posn,$byte));
// Check for start-of-field // Check for start-of-field
if ($byte == ord(ESC)) { // Esc designates start of field (Esc-K is end of edit) if ($byte == ord(ESC)) { // Esc designates start of field (Esc-K is end of edit)
$infield = TRUE; $infield = TRUE;
$fieldlength = 0; $fieldlength = 1;
$fieldtype = ord(substr($this->frame->content,$posn+1,1))%128; $fieldtype = ord(substr($this->frame->content,$posn+1,1))%128;
$byte = ord(' '); // Replace ESC with space. $this->output .= $fieldchar;
} else { } else {
if ($infield) { if ($infield) {
if ($byte == $fieldtype) { if ($byte == $fieldtype) {
$fieldlength++; $fieldlength++;
$byte = ord(' '); // Replace field with space. $byte = ord($fieldchar); // Replace field with $fieldchar.
if ($fieldx === false) { if ($fieldx === FALSE) {
$fieldx = $x; $fieldx = $x;
$fieldy = $y; $fieldy = $y;
} }
@ -131,12 +160,15 @@ class Frame
// Replace field with Date // Replace field with Date
if ($field == '%date') { if ($field == '%date') {
if ($fieldlength == 1) // Drop the last dot and replace it.
if ($fieldlength == 2) {
$datetime = date('D d M H:ia'); $datetime = date('D d M H:ia');
$this->output = rtrim($this->output,$fieldchar);
$this->output .= $datetime{0};
}
if ($fieldlength <= strlen($datetime)) if ($fieldlength > 1 AND $fieldlength <= strlen($datetime))
$byte = ord($datetime{$fieldlength-1}); $byte = ord($datetime{$fieldlength-1});
} }
// @todo user data // @todo user data
@ -147,19 +179,18 @@ class Frame
} /*else // pre-load field contents. PAM or *00 ? } /*else // pre-load field contents. PAM or *00 ?
if (isset($fields[what]['value'])) { if (isset($fields[what]['value'])) {
} */ */
} }
} else { } 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(new FrameFields([
$this->fields->push([
'type'=>chr($fieldtype), 'type'=>chr($fieldtype),
'length'=>$fieldlength, 'length'=>$fieldlength,
'x'=>$fieldx, 'x'=>$fieldx-1, // Adjust for the ESC char
'y'=>$fieldy, 'y'=>$fieldy,
]); ]));
Log::debug(sprintf('Frame: %s, Field found at [%s,%s], Type: %s, Length: %s',$this->page(),$fieldx-1,$fieldy,$fieldtype,$fieldlength));
$infield = FALSE; $infield = FALSE;
$fieldx = $fieldy = FALSE; $fieldx = $fieldy = FALSE;
@ -167,23 +198,47 @@ class Frame
} }
} }
// truncate end of lines // truncate end of lines @todo havent validated this code or used it?
if (isset($pageflags['tru']) && substr($this->frame->content,$posn,40-$x) === str_repeat(' ',40-$x)) { if (isset($pageflags['tru']) && substr($this->frame->content,$posn,40-$x) === str_repeat(' ',40-$x)) {
$this->output .= CR . LF; $this->output .= CR . LF;
break; break;
} }
$this->output .= ($byte < 32) ? ESC.chr($byte+64) : chr($byte); if (! $infield OR $fieldlength > 1)
$this->output .= ($byte < 32) ? ESC.chr($byte+64) : chr($byte);
} }
} }
} }
/** /**
* Return the Frame Number * Returns the current frame.
*/ */
public function framenum() public function frame()
{ {
return $this->frame->frame.$this->frame->index; return $this->frame->frame;
}
/**
* Return the current field configuration
*/
public function getField(int $id)
{
return $this->fields->get($id);
}
/**
* Get a specific key of the field options that passes a filter test
*
* @param string $type
* @param int $after
* @return mixed
*/
public function getFieldId($type='edit',$after=0)
{
return $this->fields
->search(function($item,$key) use ($type,$after) {
return $key >= $after AND $this->isFieldEditable($item->type);
});
} }
/** /**
@ -194,11 +249,69 @@ class Frame
* @param $flag * @param $flag
* @return bool * @return bool
*/ */
private function hasFlag($flag) public function hasFlag($flag)
{ {
return $this->frame->hasFlag($flag); return $this->frame->hasFlag($flag);
} }
/**
* Return the frame DB id
*
* @return mixed
*/
public function id()
{
return $this->frame->id;
}
/**
* Current frame index
*
* @return mixed
*/
public function index()
{
return $this->frame->index;
}
/**
* Return the next index
*/
public function index_next()
{
return chr(ord($this->frame->index)+1);
}
/**
* Determine if a field is editable
*
* @param string $field
* @return mixed
*/
public function isFieldEditable(string $field)
{
return array_get(array_get($this->fieldoptions,$field),'edit',FALSE);
}
/**
* Return the Page Number
*/
public function page(bool $as_array=FALSE)
{
return $as_array ? ['frame'=>$this->frame->frame,'index'=>$this->frame->index] : $this->frame->page;
}
/**
* Return the next page number.
*
* @param bool $as_array
* @return mixed
*/
public function pagenext(bool $as_array=FALSE)
{
return $as_array ? ['frame'=>$this->frame->frame,'index'=>$this->index_next()] : $this->frame->frame.$this->index_next();
}
/** /**
* Render the cost of the frame * Render the cost of the frame
* *
@ -292,10 +405,10 @@ class Frame
R_WHITE.'999999999a'.R_RED.sprintf('%07.0f',999).'u'; R_WHITE.'999999999a'.R_RED.sprintf('%07.0f',999).'u';
$o->content .= str_repeat('+-',18).' '.R_RED.'01'; $o->content .= str_repeat('+-',18).' '.R_RED.'01';
$o->content .= 'Date: '.ESC.str_repeat('d',25).str_repeat('+-',4);
$o->content .= 'Name: '.ESC.str_repeat('u',5).str_repeat('+-',14); $o->content .= 'Name: '.ESC.str_repeat('u',5).str_repeat('+-',14);
$o->content .= 'Address: '.ESC.str_repeat('a',20).''.str_repeat('+-',5); $o->content .= 'Date: '.ESC.str_repeat('d',25).str_repeat('+-',4);
$o->content .= ' : '.ESC.str_repeat('a',20).''.str_repeat('+-',5); $o->content .= 'Address: '.ESC.str_repeat('a',19).' '.str_repeat('+-',5);
$o->content .= ' : '.ESC.str_repeat('a',19).' '.str_repeat('+-',5);
return $o; return $o;
} }

View File

@ -0,0 +1,18 @@
<?php
namespace App\Classes;
class FrameFields
{
private $fields = [];
public function __construct(array $fields)
{
$this->fields = $fields;
}
public function __get($key)
{
return array_get($this->fields,$key);
}
}

View File

@ -16,9 +16,6 @@ use Sock\{SocketClient,SocketServer,SocketException};
class Server extends Command 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. * The name and signature of the console command.
* *
@ -89,13 +86,13 @@ class Server extends Command
global $config; global $config;
include ('config/config.php'); include ('config/config.php');
$childpid = pcntl_fork(); $pid = pcntl_fork();
if ($childpid == -1) if ($pid == -1)
throw new SocketException(SocketException::CANT_ACCEPT,'Could not fork process'); throw new SocketException(SocketException::CANT_ACCEPT,'Could not fork process');
// Parent return ready for next connection // Parent return ready for next connection
elseif ($childpid) elseif ($pid)
return; return;
// We are now the child. // We are now the child.
@ -139,29 +136,29 @@ class Server extends Command
'CUGS' => array(7800, 15500), // Closed User Groups this user has access to 'CUGS' => array(7800, 15500), // Closed User Groups this user has access to
); );
$history = array(); // backup history // Setup VARS
$timewarp = FALSE; // Is timewarp active.
$history = collect(); // Page history for going backwards
$action = ACTION_GOTO; // Initial action.
$cmd = ''; // Current *command being typed in
$mode = FALSE; // Current mode.
$current = []; // Attributes about the current page
// field/fieldnum indexes are for fields on the active page
$current['fieldreset'] = FALSE; // Flag to reset position (used in fields)
$cmd = ''; // Current *command being typed in
$mode = false; // input mode.
$prevmode = false; // previous 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'])) { if (isset($config['loginpage'])) {
$page = $config['loginpage']; $page = ['frame'=>$config['loginpage'],'index'=>'a'];
$subpage = 'a';
} else if (!empty($service['start_page'])) { } else if (!empty($service['start_page'])) {
$page = $service['start_page']; $page = ['frame'=>$service['start_page'],'index'=>'a'];
$subpage = 'a';
} else { } else {
$page = '98'; // next page $page = ['frame'=>'98','index'=>'a']; // next page
$subpage = 'a';
} }
$curpage = ''; // current page
$cursub = '';
$curfield = null; // current input field
$curfp = 0; // current field, position within. $curfp = 0; // current field, position within.
$blp = 0; // botton line polluted (by this no. of characters) $blp = 0; // botton line polluted (by this no. of characters)
$resetpsn = false; // flag to reset position (used in fields)
if (!isset($config['varient_id'])) if (!isset($config['varient_id']))
$config['varient_id'] = NULL; $config['varient_id'] = NULL;
@ -176,9 +173,9 @@ class Server extends Command
$matches = array(); $matches = array();
if (preg_match('@' . $service['page_format'] . '@', $service['start_frame'], $matches)) { if (preg_match('@' . $service['page_format'] . '@', $service['start_frame'], $matches)) {
$page = $matches[1]; $page['frame'] = $matches[1];
$subpage = $matches[2]; $page['index'] = $matches[2];
echo " Using start page " . $page . $subpage . "\n"; echo " Using start page " . $page['frame'].$page['index'] . "\n";
} }
// $start = $service['start_frame']; // $start = $service['start_frame'];
// where to start from // where to start from
@ -188,7 +185,7 @@ class Server extends Command
$read = $client->read(1); $read = $client->read(1);
if ($read != '') { if ($read != '') {
dump(sprintf('Mode: [%s] CMD: [%s] frame: [%s] Received [%s (%s)]', $mode, $cmd, $page, $read, ord($read))); dump(sprintf('Mode: [%s] CMD: [%s] frame: [%s] Received [%s (%s)]', $mode, $cmd, $page['frame'].$page['index'], $read, ord($read)));
// Client initiation input // Client initiation input
// TELNET http://pcmicro.com/netfoss/telnet.html // TELNET http://pcmicro.com/netfoss/telnet.html
@ -263,7 +260,7 @@ class Server extends Command
switch ($mode) { switch ($mode) {
// Key presses during field input. // Key presses during field input.
case MODE_FIELD: case MODE_FIELD:
//dump(sprintf('** Processing Keypress in MODE_FIELD [%s (%s)]. Last POS [%s]',$read,ord($read),$curfp)); dump(sprintf('** Processing Keypress in MODE_FIELD [%s (%s)]. Last POS [%s]',$read,ord($read),$curfp));
$cmd = ''; $cmd = '';
$action = FALSE; $action = FALSE;
@ -274,26 +271,25 @@ class Server extends Command
// End of field entry. // End of field entry.
case HASH: case HASH:
// Next Field // Next Field
$curfield++; $current['fieldnum']++;
$curfp = 0;
//dump(['current'=>$curfield, 'numfields'=>count($fields)]); if ($current['fieldnum'] < $fo->fields->count()) { // skip past non-editable fields
$current['fieldnum'] = $fo->getFieldId('edit',$current['fieldnum']);
if ($curfield < count($fields)) { // skip past non-editable fields if ($current['fieldnum'] !== FALSE) {
for ($i = $curfield; $i < count($fields); $i++) { $current['field'] = $fo->getField($current['fieldnum']);
if (isset($this->fieldoptions[$fields[$i]['type']]) && $fielddata[$current['fieldnum']] = '';
$this->fieldoptions[$fields[$i]['type']]['edit']) {
$curfield = $i;
break;
}
}
if ($curfield !== false) { dump(['Working field'=>$current['field']]);
$client->send(outputPosition($fields[$curfield]['x'], $fields[$curfield]['y']) . CON);
dump(['line'=>__LINE__,'field'=>$current['field'],'x'=>$current['field']->x]);
$client->send($this->outputPosition($current['field']->x,$current['field']->y).CON);
$mode = MODE_FIELD; $mode = MODE_FIELD;
$fielddate[$curfield] = ''; $fielddate[$current['fieldnum']] = '';
// There were no (more) editable fields.
} else { } else {
// there were no (more) editable fields.
$action = ACTION_SUBMITRF; $action = ACTION_SUBMITRF;
} }
@ -306,24 +302,24 @@ class Server extends Command
case STAR: case STAR:
$prevmode = MODE_FIELD; $prevmode = MODE_FIELD;
$action = ACTION_STAR; $action = ACTION_STAR;
$curfp = 0;
$fielddata[$current['fieldnum']] = '';
break; break;
case KEY_LEFT: case KEY_LEFT:
if ($curfp) { if ($curfp--) {
$client->send(LEFT); $client->send(LEFT);
$curfp--;
}; };
break; break;
case KEY_RIGHT: case KEY_RIGHT:
if ($curfp++ < $fields[$curfield]['length']) { if ($curfp++ < $current['field']->length) {
$client->send(RIGHT); $client->send(RIGHT);
//$curfp++;
}; };
break; break;
case KEY_DOWN: case KEY_DOWN:
if ($curfp + 40 < $fields[$curfield]['length']) { if ($curfp + 40 < $current['field']->length) {
$client->send(DOWN); $client->send(DOWN);
$curfp = $curfp + 40; $curfp = $curfp + 40;
}; };
@ -337,11 +333,12 @@ class Server extends Command
break; break;
case CR: case CR:
if ($curfp + $fields[$curfield]['x'] > 40) { // on second or later line of a field if ($curfp + $current['field']->x > 40) { // on second or later line of a field
$client->send($read); $client->send($read);
$curfp = (($curfp + $fields[$curfield]['x']) % 40) * 40; $curfp = (($curfp + $current['field']->x) % 40) * 40;
} else { } else {
$client->send(outputPosition($fields[$curfield]['x'], $fields[$curfield]['y']) . CON); dump(['line'=>__LINE__,'field'=>$current['field']]);
$client->send($this->outputPosition($current['field']->x,$current['field']->y).CON);
$curfp = 0; $curfp = 0;
} }
break; break;
@ -351,8 +348,8 @@ class Server extends Command
// Record Data Entry // Record Data Entry
default: default:
if (ord($read) > 31 && $curfp < $fields[$curfield]['length']) { if (ord($read) > 31 && $curfp < $current['field']->length) {
$fielddata[$curfield]{$curfp} = $read; $fielddata[$current['fieldnum']]{$curfp} = $read;
$curfp++; $curfp++;
$client->send($read); $client->send($read);
} }
@ -374,7 +371,8 @@ class Server extends Command
switch ($read) { switch ($read) {
// @todo Input received, process it. // @todo Input received, process it.
case '1': case '1':
dump(['s' => $service, 'f' => $fielddata]); dump(['line'=>__LINE__,'s' => $service, 'f' => $fielddata]);
// @todo if send successful or not
if (TRUE) { if (TRUE) {
sendBaseline($client, $blp, MSG_SENT); sendBaseline($client, $blp, MSG_SENT);
$mode = MODE_RFSENT; $mode = MODE_RFSENT;
@ -404,24 +402,24 @@ class Server extends Command
if ($read == HASH) { if ($read == HASH) {
if (!empty($pagedata['route1'])) { if (!empty($pagedata['route1'])) {
$action = ACTION_GOTO; $action = ACTION_GOTO;
$page = $pagedata['route1']; $page['frame'] = $pagedata['route1'];
$subpage = 'a'; $page['index'] = 'a';
} else if ($r = $db->getFrame($service['service_id'], $varient['varient_id'], $page, chr(1 + ord($subpage)))) { } else if (\App\Models\Frame::where('frame',$fo->frame())->where('index',$fo->index_next())->exists()) {
$action = ACTION_GOTO; $action = ACTION_GOTO;
$page = $curpage; $page['frame'] = array_get($current,'page.frame');
$subpage = chr(1 + ord($subpage)); $page['index'] = chr(1 + ord($page['index']));
} else if (!empty($pagedata['route0'])) { } else if (!empty($pagedata['route0'])) {
$action = ACTION_GOTO; $action = ACTION_GOTO;
$page = $pagedata['route0']; $page['frame'] = $pagedata['route0'];
$subpage = 'a'; $page['index'] = 'a';
// No further routes defined, go home. // No further routes defined, go home.
} else { } else {
$action = ACTION_GOTO; $action = ACTION_GOTO;
$page = '0'; $page['frame'] = '0';
$subpage = 'a'; $page['index'] = 'a';
} }
} elseif ($read == STAR) { } elseif ($read == STAR) {
@ -443,24 +441,24 @@ class Server extends Command
if ($read == HASH) { if ($read == HASH) {
if (!empty($pagedata['route2'])) { if (!empty($pagedata['route2'])) {
$action = ACTION_GOTO; $action = ACTION_GOTO;
$page = $pagedata['route2']; $page['frame'] = $pagedata['route2'];
$subpage = 'a'; $page['index'] = 'a';
} else if ($r = $db->getFrame($service['service_id'], $varient['varient_id'], $page, chr(1 + ord($subpage)))) { } else if (\App\Models\Frame::where('frame',$fo->frame())->where('index',$fo->index_next())->exists()) {
$action = ACTION_GOTO; $action = ACTION_GOTO;
$page = $curpage; $page['frame'] = $fo->frame();
$subpage = chr(1 + ord($subpage)); $page['index'] = $fo->index_next();
} else if (!empty($pagedata['route0'])) { } else if (!empty($pagedata['route0'])) {
$action = ACTION_GOTO; $action = ACTION_GOTO;
$page = $pagedata['route0']; $page['frame'] = $pagedata['route0'];
$subpage = 'a'; $page['index'] = 'a';
// No further routes defined, go home. // No further routes defined, go home.
} else { } else {
$action = ACTION_GOTO; $action = ACTION_GOTO;
$page = '0'; $page['frame'] = '0';
$subpage = 'a'; $page['index'] = 'a';
} }
} else if ($read == STAR) { } else if ($read == STAR) {
@ -480,8 +478,7 @@ class Server extends Command
$v = $db->getAllVarients($config['service_id'], $alts[$read - 1]['varient_id']); $v = $db->getAllVarients($config['service_id'], $alts[$read - 1]['varient_id']);
if (!empty($v)) { if (!empty($v)) {
$varient = reset($v); $varient = reset($v);
$page = $curpage; $page = array_get($current,'page');
$subpage = $cursub;
$action = ACTION_GOTO; $action = ACTION_GOTO;
break; break;
} }
@ -490,9 +487,11 @@ class Server extends Command
//drop into //drop into
// Not doing anything in particular. // Not doing anything in particular.
case MODE_COMPLETE:
case FALSE: case FALSE:
Log::debug('Idle', ['pid' => $pid]);
$cmd = ''; $cmd = '';
Log::debug('Idle', ['pid' => $childpid]);
switch ($read) { switch ($read) {
case HASH: case HASH:
@ -518,6 +517,7 @@ class Server extends Command
$action = ACTION_GOTO; $action = ACTION_GOTO;
} else { } else {
dump(['line'=>__LINE__,'blp was'=>$blp]);
sendBaseline($client, $blp, ERR_ROUTE); sendBaseline($client, $blp, ERR_ROUTE);
$mode = $action = FALSE; $mode = $action = FALSE;
} }
@ -538,6 +538,7 @@ class Server extends Command
$cmd .= $read; $cmd .= $read;
$client->send($read); $client->send($read);
$blp++; $blp++;
dump(['line'=>__LINE__,'blp is now'=>$blp]);
} }
// if we hit a special numeric command, deal with it. // if we hit a special numeric command, deal with it.
if ($cmd === '00') { // refresh page if ($cmd === '00') { // refresh page
@ -571,28 +572,31 @@ class Server extends Command
if ($read === "*") { // abort command or reset input field. if ($read === "*") { // abort command or reset input field.
$action = false; $action = false;
sendBaseline($client, $blp, ''); sendBaseline($client, $blp, '');
dump(['line'=>__LINE__,'blp is now'=>$blp]);
$cmd = ''; $cmd = '';
if ($prevmode == MODE_FIELD) { if ($prevmode == MODE_FIELD) {
$mode = $prevmode; $mode = $prevmode;
$prevmode = false; $prevmode = false;
$client->send(outputPosition($fields[$curfield]['x'], $fields[$curfield]['y']) . CON); dump(['line'=>__LINE__,'field'=>$current['field']]);
$client->send(str_repeat(' ', $fields[$curfield]['length'])); $client->send($this->outputPosition($current['field']->x,$current['field']->y).CON);
$client->send(str_repeat('.', $current['field']->length));
// tood reset stored entered text // tood reset stored entered text
$resetpsn = $curfield; $current['fieldreset'] = TRUE;
} else { } else {
$mode = false; $mode = false;
} }
break; break;
} }
// user hit # to complete request // user hit # to complete request
if ($read === '_') { // really the # key, if ($read === '_') { // really the # key,
$client->send(COFF); $client->send(COFF);
if ($cmd === '') { // nothing typed between * and # if ($cmd === '') { // nothing typed between * and #
$action = ACTION_BACKUP; $action = ACTION_BACKUP;
} else { // *# means go back } else { // *# means go back
$page = $cmd; $page['frame'] = $cmd;
$subpage = 'a'; $page['index'] = 'a';
$action = ACTION_GOTO; $action = ACTION_GOTO;
} }
$cmd = ''; // finished with this now $cmd = ''; // finished with this now
@ -629,39 +633,42 @@ class Server extends Command
break; break;
// GO Backwards
case ACTION_BACKUP: case ACTION_BACKUP:
// do we have anywhere to go? // Do we have anywhere to go, drop the current page from the history.
if (count($history) > 1) { // because current page should always be in there. if ($history->count() > 1)
array_pop($history); // drop current page to reveal previous $history->pop();
}
list($page, $subpage) = end($history); // get new last entry, $page = $history->last();
echo "Backing up to $page$subpage\n";
// drop into Log::debug('Backing up to: '.$page['frame'].$page['index']);
// Go to next index frame.
case ACTION_NEXT: case ACTION_NEXT:
if ($action == ACTION_NEXT) { // We need this extra test in case we come from ACTION_BACKUP
$cursub = $subpage; if ($action == ACTION_NEXT)
$subpage = chr(ord($subpage) + 1); {
dump(['current.page.index'=>$current['page']['index'],'fo'=>$fo->index()]);
$current['page']['index'] = $fo->index();
$page['index'] = $fo->index_next();
} }
case ACTION_GOTO: case ACTION_GOTO:
// $client->send(HOME . UP . GREEN . "Searching for page $page"); // $client->send(HOME . UP . GREEN . "Searching for page $page['frame']");
// $blp = 20 + strlenv($page); // $blp = 20 + strlenv($page['frame']);
// look for requested page // look for requested page
try { try {
$fo = (new \App\Models\Frame)->fetch($page, $subpage); $fo = (new \App\Models\Frame)->fetch($page['frame'],$page['index']);
} catch (ModelNotFoundException $e) { } 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); sendBaseline($client, $blp, ERR_PAGE);
$mode = $action = FALSE; $mode = $action = FALSE;
break; break;
} }
dump(['m' => __METHOD__, 'service' => $service['service_id'], 'varient' => $varient['varient_id'], 'frame' => $fo->framenum(), 'type' => $fo->type()]); dump(['m' => __METHOD__, 'fo'=>$fo->id(),'service' => $service['service_id'], 'varient' => $varient['varient_id'], 'frame' => $fo->page(), 'type' => $fo->type()]);
// validate if we have access top it // validate if we have access top it
/* if (isset($m['access']) && $m['access'] == 'n') { /* if (isset($m['access']) && $m['access'] == 'n') {
@ -688,42 +695,43 @@ class Server extends Command
//var_dump(['B','r'=>$r,'m'=>$m]); //var_dump(['B','r'=>$r,'m'=>$m]);
//$pagedata = array_merge($r, $m); //$pagedata = array_merge($r, $m);
//$varient = $v; //$varient = $v;
$curpage = $page; $current['page'] = $fo->page(TRUE);
$cursub = $subpage;
$cufield = 0;
$curfp = 0; $curfp = 0;
//$pageflags = $db->getFrameTypeFlags($pagedata['type']); // method missing. //$pageflags = $db->getFrameTypeFlags($pagedata['type']); // method missing.
$pageflags = []; $pageflags = [];
if ($action == ACTION_GOTO || $action == ACTION_NEXT) { // only if new location, not going backwards // Only if new location, not going backwards
$history[] = array($page, $subpage); if (($history->last() != $page) AND ($action == ACTION_GOTO || $action == ACTION_NEXT)) {
$history->push($page);
} }
// drop into // drop into
case ACTION_RELOAD: case ACTION_RELOAD:
// // @todo Move the $output into the object.
/* if ($pageflags['clear']) { if ($fo->hasFlag('clear'))
$output = CLS; {
$blp = 0; $blp = 0;
} else { $output = CLS;
$output = HOME; } else {
} $output = HOME;
*/ // Clear the baseline.
// print_r($pageflags); print_r($pagedata); $blp = sendBaseline($client,$blp,'');
}
$output .= (string)$fo;
switch ($fo->type()) { switch ($fo->type()) {
default: default:
case 'i': // standard frame case 'i': // standard frame
if ($timewarp && 1 < count( if ($timewarp && 1 < count(
$alts = $db->getAlternateFrames($service['service_id'], $varient['varient_id'], $curpage, $cursub) $alts = $db->getAlternateFrames($service['service_id'], $varient['varient_id'], array_get($current,'page.frame'), array_get($current,'page.index'))
)) { )) {
$msg = MSG_TIMEWARP; $msg = MSG_TIMEWARP;
} else { } else {
$msg = ''; $msg = '';
} }
$output = getOutputx($curpage, $cursub, [], $pageflags, $msg); dump(['line'=>__LINE__,'blp was'=>$blp,'will be'=>strlenv($msg)]);
//var_dump(['output'=>$output,'curpage'=>$curpage,'cursub'=>$cursub,'pagedata'=>$pagedata,'pageflag'=>$pageflags,'m'=>$msg]);
$blp = strlenv($msg); $blp = strlenv($msg);
$client->send($output); $client->send($output);
$mode = $action = false; $mode = $action = false;
@ -732,7 +740,7 @@ class Server extends Command
case 'a': // active frame. Prestel uses this for Response Framea. case 'a': // active frame. Prestel uses this for Response Framea.
/* /*
if ($timewarp && 1 < count( if ($timewarp && 1 < count(
$alts = $db->getAlternateFrames($service['service_id'],$varient['varient_id'],$curpage,$cursub) $alts = $db->getAlternateFrames($service['service_id'],$varient['varient_id'],array_get($current,'page.frame'), array_get($current,'page.index'))
)) { )) {
$msg = MSG_TIMEWARP; $msg = MSG_TIMEWARP;
} else { } else {
@ -745,50 +753,38 @@ class Server extends Command
//$pagedata = str_replace(chr(12),chr(27),$pagedata); //$pagedata = str_replace(chr(12),chr(27),$pagedata);
// holds data entered by user. // holds data entered by user.
$fielddata = array(); $fielddata = [];
$fields = $fo->fields; //$msg = '';
$msg = '?';
$output = getOutputx($curpage, $cursub, [], $pageflags, $msg, $user, $fields); //dump(['line'=>__LINE__,'blp was'=>$blp,'will be'=>strlenv($msg)]);
$blp = strlenv($msg); //$blp = strlenv($msg);
$client->send($output); $client->send($output);
if ($fields->count()) { // dump($fo->fields,count($fo->fields));
// dump($fields,count($fields)); // @todo If there are no editable fields, it seems the frame is hung.
// need t skip to first field that is.. if (count($fo->fields)) {
// of a field type that is editable // Get our first editable field.
// or finish. $current['fieldnum'] = $fo->getFieldId('edit',0);
$curfield = FALSE; $current['field'] = $fo->getField($current['fieldnum']);
$current['fieldreset'] = TRUE;
for ($i = 0; $i < count($fields); $i++) { if ($current['fieldnum'] !== FALSE) {
//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; $mode = MODE_FIELD;
// There were no editable fields.
} else { } else {
// there were no editable fields.
$mode = MODE_COMPLETE; $mode = MODE_COMPLETE;
$client->send(COFF);
} }
$curfp = 0; $curfp = 0;
//dump(['curfield'=>$curfield,'mode'=>$mode]);
} }
break; break;
case 't': // terminate case 't': // terminate
$output = getOutputx($curpage, $cursub, [], $pageflags); //$output = getOutputx(array_get($current,'page.frame'), array_get($current,'page.index'), [], $pageflags);
$client->send($output); $client->send($output);
$action = ACTION_TERMINATE; $action = ACTION_TERMINATE;
break; break;
@ -804,15 +800,16 @@ class Server extends Command
$cmd = ''; $cmd = '';
$action = false; $action = false;
$output = outputPosition(0, 0) . WHITE . NEWBG . RED . 'TIMEWARP INFO FOR Pg.' . BLUE . $curpage . $cursub . WHITE; // @todo Can we use $fo->page() where?
$output .= outputPosition(0, 1) . WHITE . NEWBG . BLUE . 'Service : ' . substr($service['service_name'] . str_repeat(' ', 27), 0, 27); $output = $this->outputPosition(0, 0) . WHITE . NEWBG . RED . 'TIMEWARP INFO FOR Pg.' . BLUE . array_get($current,'page.frame').array_get($current,'page.index'). WHITE;
$output .= outputPosition(0, 2) . WHITE . NEWBG . BLUE . 'Varient : ' . substr($varient['varient_name'] . str_repeat(' ', 27), 0, 27); $output .= $this->outputPosition(0, 1) . WHITE . NEWBG . BLUE . 'Service : ' . substr($service['service_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); $output .= $this->outputPosition(0, 2) . WHITE . NEWBG . BLUE . 'Varient : ' . substr($varient['varient_name'] . str_repeat(' ', 27), 0, 27);
$output .= $this->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); $alts = $db->getAlternateFrames($service['service_id'], $varient['varient_id'], array_get($current,'page.frame'), array_get($current,'page.index'));
if (count($alts) > 1) { if (count($alts) > 1) {
$n = 1; $n = 1;
$output .= outputPosition(0, 4) . WHITE . NEWBG . RED . 'ALTERNATIVE VERSIONS:' . str_repeat(' ', 16); $output .= $this->outputPosition(0, 4) . WHITE . NEWBG . RED . 'ALTERNATIVE VERSIONS:' . str_repeat(' ', 16);
$y = 5; $y = 5;
foreach ($alts as $ss) { foreach ($alts as $ss) {
// if (is_numeric($ss['varient_date'])) { // if (is_numeric($ss['varient_date'])) {
@ -827,7 +824,7 @@ class Server extends Command
$line .= BLUE . $date . ' ' . $ss['varient_name']; $line .= BLUE . $date . ' ' . $ss['varient_name'];
$output .= outputPosition(0, $y) . $line . str_repeat(' ', 40 - strlenv($line)); $output .= $this->outputPosition(0, $y) . $line . str_repeat(' ', 40 - strlenv($line));
$y++; $y++;
$n++; $n++;
@ -844,26 +841,49 @@ class Server extends Command
; ;
} // switch $action } // switch $action
if ($resetpsn !== false && isset($fields[$resetpsn])) { // We need to reposition the cursor to the current field.
$client->send(outputPosition($fields[$resetpsn]['x'], $fields[$resetpsn]['y']) . CON); if ($current['fieldreset'] !== FALSE) {
$resetpsn = false; $client->send($this->outputPosition($current['field']->x,$current['field']->y).CON);
$current['fieldreset'] = FALSE;
} }
// Did the client disconnect
if ($read === NULL || socket_last_error()) {
Log::debug('Disconnected: '.$client->getaddress());
if ($read === null || socket_last_error()) { return FALSE;
printf("[%s] Disconnected\n", $client->getaddress());
return false;
} }
} }
// Something bad happened. We'll log it and then disconnect. // Something bad happened. We'll log it and then disconnect.
} catch (\Exception $e) { } catch (\Exception $e) {
Log::emergency($e->getMessage()); Log::emergency($e->getMessage());
//@todo TEMP
throw new \Exception($e);
} }
$client->close(); $client->close();
printf( "[%s] Disconnected\n", $client->getaddress() ); Log::debug('Disconnected: '.$client->getaddress());
}
/**
* Move the cursor via the shortest path.
*/
function outputPosition($x,$y) {
// Take the shortest path.
if ($y < 12) {
return HOME.
(($x < 21)
? str_repeat(DOWN,$y).str_repeat(RIGHT,$x)
: str_repeat(DOWN,$y+1).str_repeat(LEFT,40-$x));
} else {
return HOME.str_repeat(UP,24-$y).
(($x < 21)
? str_repeat(RIGHT,$x)
: str_repeat(LEFT,40-$x));
}
} }
} }
@ -872,56 +892,20 @@ class Server extends Command
} }
// @todo Not clearing to end of line. // @todo Not clearing to end of line.
function sendBaseline($client, &$blp, $text, $reposition = false){ // @todo Remove blp by reference, change return to return blp
$client->send(HOME . UP . $text . function sendBaseline($client,&$blp,$text,$reposition=FALSE) {
( $blp > strlenv($text) ? str_repeat(' ',$blp-strlenv($text)) . dump(['method'=>__METHOD__,'blp'=>$blp,'text'=>$text,'re'=>$reposition]);
( $reposition ? HOME . UP . str_repeat(RIGHT, strlenv($text)) : '' )
$client->send(HOME.UP.$text.
($blp > strlenv($text)
? str_repeat(' ',$blp-strlenv($text)).
($reposition ? HOME.UP.str_repeat(RIGHT,strlenv($text)) : '')
: '') : '')
); );
$blp = strlenv($text); $blp = strlenv($text);
return;
} dump(['metho'=>__METHOD__,'blp is now'=>$blp]);
function outputPosition($x,$y){ return $blp;
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;
} }

View File

@ -2,10 +2,29 @@
namespace App\Models; namespace App\Models;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Model;
class Frame extends Model class Frame extends Model
{ {
protected static function boot() {
parent::boot();
static::addGlobalScope('order', function (Builder $builder) {
$builder->orderBy('created_at','DESC');
});
}
/**
* Return the Page Number
*
* @return string
*/
public function getPageAttribute()
{
return $this->frame.$this->index;
}
/** /**
* Fetch a specific frame from the database * Fetch a specific frame from the database
* *
@ -13,12 +32,11 @@ class Frame extends Model
* @param string $frame * @param string $frame
* @return mixed * @return mixed
*/ */
public function fetch(int $frame,string $index): \App\Classes\Frame public function fetch(int $frame,string $index='a'): \App\Classes\Frame
{ {
// Return our internal test frame.
if ($frame == '999' and $index == 'a') if ($frame == '999' and $index == 'a')
{
return new \App\Classes\Frame(\App\Classes\Frame::testFrame()); return new \App\Classes\Frame(\App\Classes\Frame::testFrame());
}
return new \App\Classes\Frame($this->where('frame',$frame)->where('index',$index)->firstOrFail()); return new \App\Classes\Frame($this->where('frame',$frame)->where('index',$index)->firstOrFail());
} }

View File

@ -77,7 +77,7 @@ define('MSG_SENDORNOT', GREEN . 'KEY 1 TO SEND, 2 NOT TO SEND');
define('MSG_SENT', GREEN . 'MESSAGE SENT - KEY _ TO CONTINUE'); define('MSG_SENT', GREEN . 'MESSAGE SENT - KEY _ TO CONTINUE');
define('MSG_NOTSENT', GREEN . 'MESSAGE NOT 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_ROUTE', WHITE . 'MISTAKE?' . GREEN . 'TRY AGAIN OR TELL US ON *08');
define('ERR_PAGE', ERR_ROUTE); define('ERR_PAGE', ERR_ROUTE);
define('ERR_PRIVATE', WHITE . 'PRIVATE PAGE' . GREEN . '- FOR EXPLANATION *37_..'); define('ERR_PRIVATE', WHITE . 'PRIVATE PAGE' . GREEN . '- FOR EXPLANATION *37_..');
define('ERR_DATABASE', RED . 'UNAVAILABLE AT PRESENT - PLSE TRY LATER'); define('ERR_DATABASE', RED . 'UNAVAILABLE AT PRESENT - PLSE TRY LATER');