Advertisement
terorama

Gbook_test

Sep 18th, 2012
96
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 45.79 KB | None | 0 0
  1. <?php
  2.  
  3.  
  4. define('NOCONNFILE_ERROR',10001);
  5. define('CONNECTION_ERROR',10002);
  6. define('NODATABASE_ERROR',10003);
  7. define('EXECQUERY_ERROR',10008);
  8. define('NOFOUND_ERROR',10009);
  9. define('NOACCESS_ERROR',10010);
  10.  
  11.  
  12. define('NO_ERROR',10004);
  13.  
  14. define('INIT_PROCEDURE',10005);
  15. define('ACTION_PROCEDURE',10006);
  16.  
  17.  
  18. //-------------------------------------------
  19. //          std input class
  20. //-------------------------------------------
  21. class stdInput {
  22.    private $type;
  23.    private $name;
  24.    private $value;
  25.    private $values=array();
  26.    private $label='';
  27.    private $labels=array();
  28.    
  29.    private $handlers;
  30.    //----------------------------
  31.    public function __construct ($type, $name, $value, $label='') {
  32.    
  33.       $this->type=$type;
  34.       $this->name=$name;
  35.       //-----------------------------values
  36.       if (is_array($value)) {
  37.      
  38.          for ($i=0; $i<count($value); $i++) {
  39.          
  40.             $el=array();
  41.             if (substr($value[$i], strlen($value[$i])-1,1)=='*') {
  42.                $el["checked"]=true;
  43.                $el["value"]=substr($value[$i],0,strlen($value[$i])-1);
  44.                }
  45.             else {
  46.                $el["checked"]=false;               
  47.                $el["value"]=$value[$i];
  48.             }
  49.            
  50.             $this->values[]=$el;
  51.          }
  52.          
  53.       } else
  54.          $this->value=$value;
  55.          
  56.       //----------------------------labels
  57.       if (is_array($label)) {
  58.          
  59.          for ($i=0;$i<count($label);$i++) {
  60.          
  61.             $this->labels[]=$label[$i];
  62.          }
  63.          
  64.       } else {   
  65.          $this->label=$label;
  66.       }
  67.    
  68.    }
  69.    
  70.    //----------------------------
  71.    public function addHandler ($handler) {
  72.    
  73.       $this->handlers[]=array('event'=>$handler[0],'handler'=>$handler[1]);
  74.    }
  75.    
  76.    //----------------------------
  77.    public function draw() {
  78.       $tmp='';
  79.       $handlers_str='';
  80.      
  81.       for ($i=0; $i<count($this->handlers); $i++) {
  82.          $handlers_str.=$this->handlers[$i]['event'].'="'.$this->handlers[$i]['handler'].'" ';
  83.       }
  84.      
  85.      
  86.       switch (strtoupper($this->type)) {
  87.          case 'TEXT':
  88.          case 'PASSWORD':
  89.          case 'SUBMIT':
  90.          case 'RESET':
  91.          case 'BUTTON':
  92.          case 'FILE':
  93.          case 'HIDDEN':
  94.          
  95.             if ($this->label)
  96.                 $tmp.="<label for=\"{$this->name}\">{$this->label}</label>";         
  97.                
  98.             $tmp.="<input $handlers_str type=\"{$this->type}\" name=\"{$this->name}\" value=\"{$this->value}\" />";
  99.             break;
  100.          //---------------------------------       
  101.          case 'TEXTAREA':
  102.          
  103.              if ($this->label)
  104.                 $tmp.="<p>{$this->label}</p>";
  105.              
  106.              $tmp.="<textarea $handlers_str name=\"{$this->name}\">{$this->value}</textarea>";
  107.              break;
  108.          //---------------------------------         
  109.          case 'RADIO':
  110.          case 'CHECKBOX':
  111.          
  112.                  
  113.                  for ($i=0; $i<count($this->values); $i++) {
  114.                  
  115.                     $checked=($this->values[$i]['checked']) ? 'checked':'';
  116.                    
  117.                     $tmp.="<p><input $handlers_str type=\"{$this->type}\" name=\"{$this->name}\"
  118.                                           value=\"{$this->values[$i]['value']}\" $checked />";
  119.                                          
  120.                     $tmp.=" {$this->labels[$i]}</p>";
  121.                  }
  122.                break;
  123.                
  124.          case 'SELECT':
  125.                  
  126.                  $tmp="<select $handlers_str name=\"{$this->name}\">";
  127.                  
  128.                  for ($i=0; $i<count($this->values); $i++) {
  129.                  
  130.                     $selected= ($this->values[$i]['checked']) ? 'selected': '';
  131.                    
  132.                     $tmp.="<option value=\"{$this->values[$i]['value']}\" $selected>{$this->labels[$i]}</option>";
  133.                  }
  134.                  $tmp.="</select>";
  135.                  break;
  136.                  
  137.            
  138.          
  139.       }
  140.       return $tmp;
  141.              
  142.    }
  143. }
  144.  
  145. //-------------------------------------------
  146. //        fieldset class
  147. //-------------------------------------------
  148. class stdFieldset {
  149.  
  150.    private $fields=array();
  151.    private $legend;
  152.    
  153.    //----------------------------
  154.    public function __construct($legend) {
  155.    
  156.       $this->legend=$legend;
  157.    }
  158.    
  159.    //----------------------------
  160.    public function addField($type, $name, $value, $label) {
  161.    
  162.       $a= new stdInput($type, $name, $value, $label);
  163.       $this->fields[]= &$a;
  164.       return $a;
  165.    }
  166.    
  167.    //----------------------------
  168.    public function draw() {
  169.       $tmp="<fieldset><legend>{$this->legend}</legend>";
  170.      
  171.       for ($i=0; $i<count($this->fields);$i++) {
  172.          $tmp.=$this->fields[$i]->draw();
  173.       }
  174.      
  175.       $tmp.='</fieldset>';
  176.       return $tmp;
  177.      
  178.    }
  179.    
  180. }
  181.  
  182.  
  183. //-------------------------------------------
  184. //            std form class
  185. //-------------------------------------------
  186. class stdForm {
  187.    
  188.    private $action;
  189.    private $scripts=array();
  190.    private $fieldsets=array();
  191.    private $hidden_fields=array();
  192.    private $buttons=array();
  193.    
  194.    //----------------------------
  195.    //      constructor
  196.    //----------------------------
  197.    public function __construct($action, $onsubmit="") {
  198.    
  199.       if (is_array($onsubmit)) {
  200.          $this->scripts['onsubmit']=array('handler'=>$onsubmit[0], 'script'=>$onsubmit[1]);
  201.       }
  202.       $this->action=$action;
  203.      
  204.    }
  205.    
  206.    //----------------------------
  207.    //    add field set
  208.    //----------------------------  
  209.    public function addFieldset($legend) {
  210.    
  211.       $a = new stdFieldset($legend);
  212.       $this->fieldsets[]= &$a;
  213.       return $a;
  214.    }
  215.    
  216.    //----------------------------
  217.    //     add hidden
  218.    //----------------------------
  219.    public function addHidden($name, $value) {
  220.       $this->hidden_fields[]= new stdInput('HIDDEN', $name, $value);
  221.    }
  222.    
  223.    //----------------------------
  224.    //    add button
  225.    //----------------------------
  226.    public function addButton($type, $name, $value, $onclick="") {
  227.    
  228.       if (is_array($onclick)) {
  229.      
  230.          $this->scripts[$name]=array('handler'=>$onclick[0], 'script'=>$onclick[1]);
  231.          $handler=$onclick[0];
  232.       }
  233.       else
  234.          $handler='';
  235.    
  236.       $a=new stdInput($type, $name, $value);
  237.      
  238.       if (is_array($onclick))
  239.          $a->addHandler(array('onclick',$onclick[0]));
  240.      
  241.       $this->buttons[]= &$a;
  242.    }
  243.    
  244.    //----------------------------
  245.    public function draw() {
  246.       $tmp='';
  247.       $tmp.=$this->drawHeader();
  248.      
  249.       for ($i=0; $i<count($this->fieldsets);$i++) {
  250.          $tmp.=$this->fieldsets[$i]->draw();
  251.       }
  252.      
  253.      
  254.       for ($i=0; $i<count($this->hidden_fields); $i++) {
  255.          $tmp.=$this->hidden_fields[$i]->draw();
  256.       }
  257.      
  258.       for ($i=0; $i<count($this->buttons); $i++) {
  259.          $tmp.=$this->buttons[$i]->draw();
  260.       }
  261.      
  262.       $tmp.=$this->drawFooter();
  263.       return $tmp;
  264.    }
  265.    
  266.    //----------------------------
  267.    private function drawHeader() {
  268.    
  269.       $tmp='';
  270.       foreach ($this->scripts as $script) {
  271.          $tmp.='<script type="text/javascript">';
  272.          $tmp.=$script['script'];
  273.          $tmp.='</script>';
  274.       }
  275.      
  276.       if (isset($this->scripts['onsubmit'])) {
  277.          $subm='onsubmit="'.$this->scripts['onsubmit']['handler'].'"';
  278.       } else
  279.          $subm='';
  280.          
  281.       $tmp.= '<div class="formblock"><form '.$subm.' action="'.
  282.                          $this->action.'" method="POST" enctype="application/x-www-form-urlencoded">';
  283.       return $tmp;
  284.    }
  285.    //----------------------------
  286.    private function drawFooter() {
  287.       return '</form><div style="clear:both"></div></div>';
  288.    }
  289.    
  290. }
  291.  
  292. //-------------------------------------------
  293. //           guestbook form
  294. //-------------------------------------------
  295. class gbForm extends stdForm {
  296.  
  297.    //-------------------------------
  298.    private $std_onsubmit=array(
  299.          'return check_form(this);',
  300.          
  301.          'function check_form(f) {
  302.             for (var i=0; i<f.elements.length; i++) {
  303.                if (f.elements[i].value=="") {
  304.                   alert(f.elements[i].name+" should be filled");
  305.                   return false;
  306.                   }
  307.                  
  308.                }
  309.              return true;
  310.          }');
  311.    //-------------------------------
  312.            
  313.    private $stdcancel_onclick=array();   
  314.    
  315.    //-------------------------------
  316.    private $buttons=array();
  317.    
  318.    //-------------------------------
  319.    //    gbForm constructor
  320.    //-------------------------------
  321.    public function __construct($action_value, $step_value, $buttons, $onsubmit="") {
  322.    
  323.       //--------------------------------------
  324.       $this->stdcancel_onclick=array(
  325.          'back_to_list();',
  326.          "function back_to_list() { window.location.assign('{$_SERVER["PHP_SELF"]}');}");  
  327.          
  328.       //-------------------------------------
  329.       $this->buttons=array (
  330.          'post'=>array('SUBMIT', ''),
  331.          'update'=>array('SUBMIT', ''),  
  332.          'reset'=>array('RESET',''),
  333.          'cancel'=>array('BUTTON',$this->stdcancel_onclick),
  334.          'yes'=>array('SUBMIT',''),
  335.          'no'=>array('BUTTON',$this->stdcancel_onclick),
  336.          'login'=>array('SUBMIT',''),
  337.          'logout'=>array('SUBMIT',''),
  338.          'register'=>array('SUBMIT',''),
  339.          'save'=>array('SUBMIT',''));
  340.       //-------------------------------------
  341.      
  342.      
  343.       if ($onsubmit=='default')
  344.          $subm = $this->std_onsubmit;
  345.       else
  346.          $subm=$onsubmit;
  347.          
  348.       parent::__construct($_SERVER["PHP_SELF"], $subm);
  349.      
  350.       $this->addHidden('action',$action_value);
  351.       $this->addHidden('step',$step_value);
  352.      
  353.       for ($i=0;$i<count($buttons); $i++) {
  354.          $this->addButton($this->buttons[$buttons[$i]][0],
  355.                          $buttons[$i], $buttons[$i], $this->buttons[$buttons[$i]][1]);
  356.       }
  357.    }
  358. }
  359.  
  360. //-------------------------------------------
  361. //     add  record form
  362. //-------------------------------------------
  363. class addrecForm extends gbForm {
  364.  
  365.    //------------------------------
  366.    public function __construct($loggedIn) {
  367.    
  368.       parent::__construct('add',2,array('post','reset','cancel'), 'default');
  369.      
  370.       $fset=$this->addFieldset('adding guestbook entry');
  371.      
  372.       if (!$loggedIn)
  373.          $fset->addField('TEXT','entry_author','anonimous','Input name');
  374.      
  375.       $fset->addField('TEXT','entry_caption','','Input title');
  376.       $fset->addField('TEXTAREA','entry_text','','Input text');
  377.    }
  378. }
  379.  
  380. //-------------------------------------------
  381. //     edit record form
  382. //-------------------------------------------
  383. class editrecForm extends gbForm {
  384.  
  385.    //------------------------------
  386.    public function __construct($inrow) {
  387.    
  388.       parent::__construct('edit',2,array('update','cancel'), 'default');
  389.      
  390.       $fset=$this->addFieldset('editing guestbook entry');
  391.      
  392.      
  393.       $fset->addField('TEXT','entry_caption',$inrow['entry_caption'],'Input title');
  394.       $fset->addField('TEXTAREA','entry_text',$inrow['entry_text'],'Input text');
  395.    }
  396. }
  397.  
  398. //-------------------------------------------
  399. //    delete form
  400. //-------------------------------------------
  401. class deleteForm extends gbForm {
  402.  
  403.    public function __construct() {
  404.    
  405.       parent::__construct('delete',2,array('yes','no'),'default');
  406.       $fset=$this->addFieldset('record will be deleted. Are you sure?');
  407.    }
  408. }
  409.  
  410. //-------------------------------------------
  411. //       login form
  412. //-------------------------------------------
  413. class loginForm extends gbForm {
  414.  
  415.    public function __construct() {
  416.    
  417.       parent::__construct('login',2, array('login','reset','cancel'),'default');
  418.       $fset=$this->addFieldset('logging in');
  419.    
  420.       $fset->addField('TEXT','username','','Input your name');
  421.       $fset->addField('PASSWORD','password','','Input password');
  422.    }
  423.    
  424. }
  425.  
  426. //-------------------------------------------
  427. //       logout form
  428. //-------------------------------------------
  429. class logoutForm extends gbForm {
  430.  
  431.    public function __construct() {
  432.    
  433.       parent::__construct('logout',2, array('yes','no'),'default');
  434.       $fset=$this->addFieldset('Are you sure you want to quit?');
  435.    
  436.    }
  437. }
  438.  
  439. //-------------------------------------------
  440. //           register form
  441. //-------------------------------------------
  442. class registerForm extends gbForm {
  443.  
  444.    public function __construct() {
  445.    
  446.       $onsubmit=array('return check_form(this);',
  447.      
  448.       ' function check_form(f) {
  449.  
  450.         var isok=true;
  451.  
  452.         if (f.username.value=="") {
  453.            isok=false;
  454.            alert("user name cannot be empty");
  455.         }
  456.  
  457.         if (f.password.value=="") {
  458.            isok=false;
  459.            alert("password cannot be empty");
  460.         }
  461.  
  462.         if (f.password.value!=f.confpass.value) {
  463.            isok=false;
  464.            alert("password confirmation doesn\'t suit");
  465.         }
  466.        
  467.         return isok;
  468.      }');
  469.    
  470.       parent::__construct('register',2, array('register','reset','cancel'),$onsubmit);
  471.      
  472.       $fset=$this->addFieldset('Registering user');
  473.      
  474.       $fset->addField('TEXT','username','','Input user name');
  475.       $fset->addField('PASSWORD','password','','Input password');
  476.       $fset->addField('PASSWORD','confpass','','Confirm password');
  477.       $fset->addField('TEXT','useremail','','Input email');
  478.      
  479.       $fset=$this->addFieldset('Input your gender');
  480.       $fset->addField('RADIO','gender',array('M*','F'), array('male','female'));
  481.      
  482.       $fset=$this->addFieldset('Input your country');
  483.       $fset->addField('SELECT','country', array('US*','UK','Russia','China'),
  484.                                 array('United States','United Kingdom', 'Russia', 'China'));
  485.                                
  486.       $fset=$this->addFieldset('Input your interests');
  487.       $fset->addField('CHECKBOX','interests[]', array('movies*','books*','art'), array('movies','books','art'));
  488.      
  489.    }
  490. }
  491.  
  492. //-------------------------------------------
  493. //        connection file form
  494. //-------------------------------------------
  495. class connectionfileForm extends gbForm {
  496.  
  497.    public function __construct($action, $inf) {
  498.    
  499.       parent::__construct($action, 2, array('save','cancel'), 'default');
  500.      
  501.       $fset=$this->addFieldset('editing connection params');
  502.       $fset->addField('TEXT','host',$inf[0],'Input database host');
  503.       $fset->addField('TEXT','username',$inf[1],'Input database username');
  504.       $fset->addField('TEXT','password',$inf[2],'Input database password');
  505.       $fset->addField('TEXT','database',$inf[3],'Input database name');
  506.    }
  507. }
  508.  
  509.  
  510. //-------------------------------------------
  511. //            GuestBook Model
  512. //-------------------------------------------
  513. class gbModel {
  514.  
  515.    const PARAM_FILE='connparams.txt';
  516.    const ENTRIES_PER_PAGE=4;
  517.  
  518.    public static $gb;
  519.    //-----------------------------------
  520.    public $loginref='';
  521.    public $registerref='';
  522.    public $conmenu;
  523.  
  524.    public $gbpage='';
  525.  
  526.    public $breadcrumbs='';
  527.    public $navigation='';
  528.    public $addeditform='';
  529.    
  530.    public $debugblock='';
  531.  
  532.    //-----------------------------------
  533.  
  534.    private $errorno=NO_ERROR;
  535.    private $error_message='';
  536.    private $error_procedure=0;
  537.    
  538.    public $logged_in=false;
  539.    public $user_id=0;
  540.  
  541.    //-----------------------------------
  542.    public $action='';
  543.    public $step=1;
  544.    public $current_element=0;
  545.    public $current_page=1;
  546.    public $got_params=false;
  547.    public $current_procedure=0;
  548.  
  549.    public $redirect_path='';
  550.    //-----------------------------------
  551.    public $conn_params = array (
  552.       'host'=>'', 'username'=>'', 'password'=>'', 'database'=>'');
  553.    
  554.    private $db;
  555.  
  556.  
  557.    //-------------------------------------------
  558.    //            constructor
  559.    //-------------------------------------------
  560.    private function __construct() {
  561.    }
  562.    
  563.    //-------------------------------------------------trass
  564.    private function trass($instr, $isvar=false) {
  565.       if ($isvar) {
  566.          $this->debugblock.='<pre>'.print_r($instr, true).'</pre><br/>';         
  567.       } else {
  568.          $this->debugblock.=$instr.'<br/>';
  569.       }
  570.    }
  571.    
  572.  
  573.    //-------------------------------------------
  574.    //      get connection parameters
  575.    //-------------------------------------------
  576.    private function getconnparams() {
  577.  
  578.       $this->trass('getting connection parameters');
  579.      
  580.       if (!file_exists(gbModel::PARAM_FILE))
  581.          throw new Exception ('params file doesn\'t exist', NOCONNFILE_ERROR);
  582.  
  583.       $tmp=file(gbModel::PARAM_FILE);
  584.  
  585.       foreach ($tmp as &$item) {
  586.  
  587.          $item=substr($item, strpos($item,':')+1);
  588.          $item=substr($item,0, strlen($item)-2);
  589.       }
  590.  
  591.       $this->conn_params['host']=      $tmp[0];
  592.       $this->conn_params['username'] = $tmp[1];
  593.       $this->conn_params['password'] = $tmp[2];
  594.       $this->conn_params['database'] = $tmp[3];
  595.    }
  596.    
  597.    //-------------------------------------------
  598.    //         connection to database
  599.    //-------------------------------------------
  600.    private function connect() {
  601.    
  602.       $this->trass('connecting');
  603.  
  604.       $this->db= @new mysqli($this->conn_params['host'],
  605.                             $this->conn_params['username'],
  606.                             $this->conn_params['password'],
  607.                             $this->conn_params['database']);
  608.                                            
  609.  
  610.       if (mysqli_connect_errno())      
  611.          throw new Exception(mysqli_connect_error(), CONNECTION_ERROR);
  612.    }
  613.  
  614.    //-------------------------------------------
  615.    //   check whether the database exists
  616.    //-------------------------------------------
  617.    private function checkDB() {
  618.    
  619.       $this->trass('check whether the database exists');
  620.  
  621.       $result=$this->db->query('select * from gb');
  622.       if ($result===FALSE)
  623.          throw new Exception ('Database doesn\'t exist', NODATABASE_ERROR);
  624.      
  625.    }
  626.  
  627.    //-------------------------------------------
  628.    //       initialize model
  629.    //-------------------------------------------
  630.    public function init() {
  631.          
  632.          $this->trass('init model');
  633.          
  634.          if (!$this->got_params)
  635.             $this->getconnparams();
  636.  
  637.          $this->connect();
  638.          
  639.          if ($this->action!='database')
  640.             $this->checkDB();  
  641.    }
  642.    
  643.  
  644.    //-------------------------------------------
  645.    //    model handler (init, actions, errors)
  646.    //-------------------------------------------
  647.    public function defaultProcess() {
  648.  
  649.       $this->trass('default model process');
  650.      
  651.       if (!in_array($this->action, array('error','connfile','editconnfile'))) {
  652.  
  653.          $current_procedure=INIT_PROCEDURE;
  654.          try {
  655.                $this->init();
  656.              }
  657.          catch (Exception $e) {
  658.                $this->handle_errors($e);
  659.                return;
  660.             }
  661.          
  662.          }
  663.  
  664.      
  665.       $current_procedure=ACTION_PROCEDURE;
  666.  
  667.       try {
  668.          $this->performAction();
  669.       }
  670.       catch (Exception $e) {
  671.  
  672.          $this->handle_errors($e);
  673.          return;
  674.       }
  675.    
  676.    }
  677.  
  678.    //-------------------------------------------
  679.    //       perform actions
  680.    //-------------------------------------------
  681.    private function performAction() {
  682.  
  683.       $this->trass('perform actions');
  684.       $this->trass("action={$this->action}");
  685.       $this->trass("step={$this->step}");
  686.       //----------------------------------------
  687.    
  688.       //-----------------------------
  689.       switch ($this->action) {
  690.  
  691.          case 'error':           
  692.              $this->showErrorPage();
  693.              break;
  694.  
  695.          case 'add':
  696.             switch ($this->step) {
  697.  
  698.                case 1: $this->drawAddForm();
  699.                        break;
  700.  
  701.                case 2: $this->addRecord();
  702.                        break;
  703.             } break;
  704.  
  705.          case 'edit':
  706.               switch ($this->step) {
  707.                  
  708.                  case 1: $this->drawAddForm(true);
  709.                          break;
  710.  
  711.                  case 2: $this->saveRecord();
  712.                          break;
  713.               } break;
  714.  
  715.  
  716.          case 'delete':
  717.               switch ($this->step) {
  718.  
  719.                   case 1: $this->drawDeleteForm();
  720.                           break;
  721.  
  722.                   case 2: $this->deleteRecord();
  723.                           break;
  724.               } break;
  725.  
  726.          case 'login':
  727.               switch ($this->step) {
  728.                  
  729.                  case 1: $this->drawLoginForm();
  730.                          break;
  731.                  
  732.                  case 2: $this->login();
  733.                          break;
  734.                  } break;
  735.                        
  736.  
  737.          case 'logout':
  738.               switch ($this->step) {
  739.                    
  740.                  case 1:   $this->drawLogoutForm();
  741.                            break;
  742.  
  743.                  case 2: $this->logout();
  744.                          break;
  745.             } break;
  746.  
  747.          case 'register':
  748.               switch ($this->step) {
  749.                    
  750.                  case 1: $this->drawRegisterForm();
  751.                          break;
  752.  
  753.                  case 2: $this->register();
  754.                          break;
  755.               } break;
  756.  
  757.          case 'connfile':
  758.               switch ($this->step) {
  759.                    
  760.                  case 1: $this->drawConnFileForm();
  761.                          break;
  762.  
  763.                  case 2: $this->saveConnection();
  764.                          break;
  765.               } break;
  766.  
  767.  
  768.          case 'editconnfile':
  769.               switch ($this->step) {
  770.                    
  771.                  case 1: $this->drawConnFileForm(true);
  772.                          break;
  773.  
  774.                  case 2: $this->saveConnection();
  775.                          break;
  776.               } break;
  777.  
  778.          case 'database':
  779.               switch ($this->step) {
  780.                    
  781.                  case 1: $this->drawCreateDatabaseForm();
  782.                          break;
  783.  
  784.                  case 2: $this->createDatabase();
  785.                          break;
  786.               } break;
  787.       }
  788.      
  789.    //-----------------------
  790.    if (!in_array($this->action, array('connfile','editconnfile','database','error'))) {
  791.       $this->drawLoginRef();
  792.       $this->drawRegisterRef();
  793.       }
  794.          
  795.    if (
  796.           (in_array($this->action, array('view','add','edit'))) ||
  797.           ( ($this->action=='error') &&
  798.              (in_array($this->errorno,array(NOFOUND_ERROR, NOACCESS_ERROR))) )  
  799.          ) {
  800.  
  801.  
  802.          $this->drawBreadCrumbs();
  803.          if ($this->action!='error')
  804.             $this->drawPage();
  805.          $this->drawNavigation();
  806.       }
  807.       //-----------------------------
  808.      
  809.      
  810.      
  811.          $this->drawConMenu(array('view','editconnfile','database'),
  812.          array('home','check conection file','recreate database'));
  813.      
  814.  
  815.    }
  816.    
  817.    //-------------------------------------------
  818.    //             execute query
  819.    //-------------------------------------------
  820.    private function execQuery($sql) {
  821.    
  822.       if (!$this->db->query($sql))
  823.          throw new Exception ('error while executing query: '.$sql.' '.$this->db->error,EXECQUERY_ERROR);
  824.    }
  825.    
  826.    //-------------------------------------------
  827.    //         get single row
  828.    //-------------------------------------------
  829.    private function getSingle($sql) {
  830.    
  831.       $result=$this->db->query($sql);
  832.       if ($result===FALSE)
  833.          throw new Exception ('error while executing query: '.$sql.' '.$this->db->error,EXECQUERY_ERROR);
  834.    
  835.       $outinf=array();
  836.      
  837.       if ($row=$result->fetch_array(MYSQLI_NUM)) {
  838.          for ($i=0; $i<$result->field_count; $i++) {
  839.          
  840.             $field_info=$result->fetch_field();        
  841.             $outinf[$field_info->name]=$row[$i];
  842.          } 
  843.       }
  844.       else
  845.          throw new Exception ('error no data found: '.$sql, NOFOUND_ERROR);
  846.          
  847.      
  848.       $result->free();   
  849.       return $outinf;
  850.    }
  851.    
  852.    //-------------------------------------------
  853.    //       exec param query
  854.    //-------------------------------------------
  855.    private function execQueryP($sql, $param) {
  856.    
  857.       $stmt=$this->db->prepare($sql);
  858.      
  859.       call_user_func_array(array($stmt,'bind_param'), $param);
  860.  
  861.       if (!$stmt->execute())
  862.          throw new Exception('error while executing query: '.$sql.' '.$stmt->error, EXECQUERY_ERROR);
  863.  
  864.       $recid=$stmt->insert_id;     
  865.       $stmt->close();
  866.      
  867.       return $recid;     
  868.    }
  869.    
  870.    //-------------------------------------------
  871.    //         draw context menu
  872.    //-------------------------------------------
  873.    private function drawConMenu($actions,$labels) {
  874.    
  875.       $tmp='<ul>';
  876.       for ($i=0; $i<count($actions);$i++) {
  877.          $tmp.='<li>'.$this->link("action={$actions[$i]}",$labels[$i]).'</li>';
  878.       }
  879.       $tmp.='</ul>';
  880.       $this->conmenu=$tmp;
  881.    }
  882.  
  883.    //-------------------------------------------
  884.    //          draw login reference
  885.    //-------------------------------------------
  886.    private function drawLoginRef() {
  887.  
  888.       $tmp='<div class="login_block">';
  889.  
  890.       if (!$this->logged_in)
  891.  
  892.          $tmp.=$this->link('action=login','LogIn');
  893.       else
  894.          {
  895.          $myname=$this->getUserName($this->user_id);               
  896.          $tmp.='Hello '.$myname.$this->link('action=logout','LogOut');
  897.          }
  898.      
  899.       $tmp.='</div>';
  900.  
  901.       $this->loginref=$tmp;
  902.    }
  903.  
  904.    //-------------------------------------------
  905.    //       get user name by id
  906.    //-------------------------------------------
  907.    private function getUserName($user_id) {
  908.    
  909.       $usr=$this->getSingle("select user_name from gbusers where id={$user_id}");
  910.       return $usr["user_name"];
  911.    }
  912.    
  913.    //-------------------------------------------
  914.    //       draw register reference
  915.    //-------------------------------------------
  916.    private function drawRegisterRef() {
  917.  
  918.       $tmp='<div class="register_block">';
  919.  
  920.       if (!$this->logged_in)
  921.  
  922.          $tmp.=$this->link('action=register','Register');
  923.      
  924.       $tmp.='</div>';
  925.  
  926.       $this->registerref=$tmp;
  927.    }
  928.    
  929.    //-------------------------------------------
  930.    //       draw guestbook page
  931.    //-------------------------------------------
  932.    public function drawPage() {
  933.  
  934.       $this->trass('draw page');
  935.      
  936.       $sql='select a.id, a.entry_author, a.entry_date, '.
  937.                       'a.entry_caption, a.entry_text, b.user_name, a.entry_author_id from gb a '.
  938.                'left join gbusers b on a.entry_author_id=b.id  ';
  939.                
  940.       $result=$this->db->query($sql);
  941.                
  942.        if ($result===FALSE)
  943.           throw new Exception ('error executing query: '.$sql, EXECQUERY_ERROR);
  944.          
  945.       $this->trass($result->num_rows);
  946.       $result->data_seek(($this->current_page-1)* gbModel::ENTRIES_PER_PAGE);
  947.  
  948.       $num=0;
  949.       $this->gbpage='';
  950.       while (($row=$result->fetch_assoc()) && ($num < gbModel::ENTRIES_PER_PAGE)) {
  951.  
  952.          $this->gbpage.= "<div class =\"gbentry\">".
  953.  
  954.          "<div class=\"gbauthor\">".
  955.          (($row['user_name']!==NULL) ? $row['user_name'] : $row['entry_author'])."</div>".
  956.  
  957.          "<div class=\"gbdate\">{$row['entry_date']}</div>".
  958.          "<div class=\"gbcaption\">{$row['entry_caption']}</div>".
  959.          "<div class=\"gbtext\">{$row['entry_text']}</div>".
  960.  
  961.          $this->get_buttons($row['entry_author_id'], $row['id']).
  962.  
  963.          "</div>";
  964.  
  965.         $num++;
  966.       }
  967.       $this->trass($num);
  968.      
  969.       $result->free();
  970.      
  971.       $this->gbpage.=$this->get_edit_panel();
  972.    }
  973.    
  974.    //-------------------------------------------
  975.    //           draw post buttons
  976.    //-------------------------------------------
  977.    private function get_buttons($author_id, $entry_id) {
  978.  
  979.       $tmp="<div class=\"entry_buttons\">";
  980.  
  981.       if ((!$this->logged_in) || ($this->user_id!=$author_id))
  982.          return $tmp.'</div>';
  983.  
  984.        $tmp.=$this->link("action=edit&element=$entry_id",'edit');
  985.        $tmp.=$this->link("action=delete&element=$entry_id",'delete');
  986.  
  987.        return $tmp.'</div>';
  988.  
  989.    }
  990.  
  991.    //---------------------------------------------
  992.    //        draw page edit panel
  993.    //---------------------------------------------
  994.    private function get_edit_panel() {
  995.      
  996.       $tmp='<div class="edit_panel">';
  997.  
  998.       $tmp.=$this->link('action=add','add record to guestbook');
  999.  
  1000.       return $tmp.'</div>';
  1001.    }
  1002.  
  1003.    //---------------------------------------------
  1004.    //         draw breadcrumbs
  1005.    //---------------------------------------------
  1006.    private function drawBreadCrumbs() {
  1007.  
  1008.       $this->breadcrumbs='<div class="breadcrumbs">You are at the page: '.
  1009.                           $this->current_page.'</div>';
  1010.    }
  1011.  
  1012.    //---------------------------------------------
  1013.    //        draw navigation block
  1014.    //---------------------------------------------
  1015.    private function drawNavigation() {
  1016.  
  1017.       $tmp="<div class=\"navigation_block\">";
  1018.  
  1019.       $n_pages=$this->num_pages();
  1020.  
  1021.       for ($i=1; $i<=$n_pages; $i++) {
  1022.  
  1023.          $tmp.='<div class="navigation_element_block">';
  1024.          
  1025.          if ($i==$this->current_page) {
  1026.             $tmp.=$i;
  1027.  
  1028.          } else {
  1029.             $tmp.=$this->link("action=view&page=$i", $i);
  1030.          }
  1031.          $tmp.='</div>';
  1032.       }
  1033.       $tmp.='</div>';
  1034.       $this->navigation=$tmp;
  1035.    }
  1036.    
  1037.    //-------------------------------------------
  1038.    //             count pages
  1039.    //-------------------------------------------
  1040.    private function num_pages() {
  1041.      
  1042.       $res=$this->getSingle('select count(*) cnt from gb');
  1043.       $this->trass($res, true);
  1044.       return ceil($res['cnt']/gbModel::ENTRIES_PER_PAGE);  
  1045.              
  1046.    }
  1047.    //-------------------------------------------
  1048.    //     add (edit) record form
  1049.    //-------------------------------------------
  1050.    private function drawAddForm($edit=false) {
  1051.  
  1052.       $title='';
  1053.       $text='';
  1054.       $this->trass('draw adding (editing) form');
  1055.  
  1056.       if ($edit)
  1057.          $this->checkPrivileges();
  1058.  
  1059.       if ($edit) {
  1060.            $row=$this->getSingle("select * from gb where id={$this->current_element}");  
  1061.            $frm= new editrecForm($row);    
  1062.       } else {
  1063.          $frm=new addrecForm($this->logged_in);
  1064.       }
  1065.  
  1066.       $tmp=$frm->draw();
  1067.  
  1068.       $this->addeditform=$tmp;
  1069.    }
  1070.  
  1071.    //-------------------------------------------
  1072.    //       add record to database
  1073.    //-------------------------------------------
  1074.    private function addRecord() {
  1075.  
  1076.       $this->trass('adding record');
  1077.      
  1078.       if ($this->logged_in) {
  1079.          
  1080.          $entry_author=$this->getUserName($this->user_id);
  1081.      
  1082.       } else {
  1083.      
  1084.          $entry_author=$this->filter($_REQUEST["entry_author"]);
  1085.       }
  1086.  
  1087.       $entry_date=date('YmdHis');
  1088.       $entry_caption=$this->filter($_REQUEST["entry_caption"]);
  1089.       $entry_text=$this->filter($_REQUEST["entry_text"]);
  1090.      
  1091.      
  1092.      
  1093.       $sql='insert into gb(entry_author_id, entry_author, entry_date, entry_caption, entry_text)'.
  1094.              ' values(?,?,?,?,?)';
  1095.              
  1096.       $num_rec = $this->execQueryP($sql, array('issss',$this->user_id,
  1097.                                     $entry_author, $entry_date, $entry_caption, $entry_text));   
  1098.              
  1099.       $stmt=$this->db->Prepare($sql);
  1100.  
  1101.        $this->addeditform.=
  1102.               'record successfully added '.
  1103.               $this->link("action=viewrecord&element=$num_rec",'View record').
  1104.               $this->link("action=edit&element=$num_rec",'Edit record');
  1105.    }
  1106.  
  1107.    //-------------------------------------------
  1108.    //       save record to database
  1109.    //-------------------------------------------
  1110.    private function saveRecord() {
  1111.  
  1112.       $this->trass('saving record');
  1113.      
  1114.       $this->checkPrivileges();
  1115.      
  1116.       if ($this->logged_in) {
  1117.      
  1118.             $entry_author=$this->getUserName($this->user_id);
  1119.            
  1120.       } else {
  1121.      
  1122.            $entry_author=$_REQUEST['entry_author'];
  1123.       }
  1124.  
  1125.       $entry_date=date('YmdHis');
  1126.       $entry_caption=$this->filter($_REQUEST["entry_caption"]);
  1127.       $entry_text=$this->filter($_REQUEST["entry_text"]);
  1128.  
  1129.       $sql='update gb set entry_author=?, entry_date=?,'.
  1130.            'entry_caption=?, entry_text=? where id=?';
  1131.                    
  1132.       $stmt=$this->execQueryP($sql, array('ssssi', $entry_author, $entry_date,
  1133.                                  $entry_caption, $entry_text,
  1134.                                  $this->current_element));
  1135.  
  1136.       $this->addeditform=
  1137.               'record successfully updated'.
  1138.               $this->link("action=viewrecord&element={$this->current_element}",'View record').
  1139.               $this->link("action=edit&element={$this->current_element}",'Edit record');
  1140.    }
  1141.  
  1142.    //-------------------------------------------
  1143.    //     draw delete record form
  1144.    //-------------------------------------------
  1145.    private function drawDeleteForm() {
  1146.  
  1147.       $this->checkPrivileges();
  1148.      
  1149.       $delform= new deleteForm();      
  1150.       $this->gbpage=$delform->draw();
  1151.    }
  1152.  
  1153.    //-------------------------------------------
  1154.    //    delete record from database
  1155.    //-------------------------------------------
  1156.    private function deleteRecord() {
  1157.  
  1158.       $this->checkPrivileges();
  1159.      
  1160.       $this->execQuery("delete from gb where id={$this->current_element}");
  1161.      
  1162.       $this->gbpage='record successfully deleted '.
  1163.                 $this->link("action=view",'back to list');
  1164.    }
  1165.  
  1166.  
  1167.    //-------------------------------------------
  1168.    //      draw login form
  1169.    //-------------------------------------------
  1170.    private function drawLoginForm() {
  1171.      
  1172.       $loginform = new loginForm();
  1173.       $this->gbpage=$loginform->draw();
  1174.    }
  1175.  
  1176.    //-------------------------------------------
  1177.    //               login
  1178.    //-------------------------------------------
  1179.    private function login() {
  1180.      
  1181.       $uname=$this->filter($_REQUEST["username"]);
  1182.      
  1183.       $sql='select user_name, user_password, id from gbusers '.
  1184.                                "where user_name='{$uname}'";  
  1185.       $isok=false;
  1186.       try {
  1187.          $row=$this->getSingle($sql);
  1188.          if ($row['user_password']==$_REQUEST["password"])
  1189.              $isok=true;
  1190.       }
  1191.       catch (Exception $e) {
  1192.       }
  1193.  
  1194.       if ($isok) {
  1195.          $this->logged_in=true;
  1196.          $this->user_id=$row['id'];
  1197.  
  1198.          $this->gbpage="Hello $uname".
  1199.                         $this->link('action=view','return to list');
  1200.       }
  1201.       else
  1202.          $this->gbpage="Error: invalid password or user doesn't exist".
  1203.                        $this->link('action=login','try again').
  1204.                        $this->link('action=view','back to list');
  1205.  
  1206.    }
  1207.  
  1208.    //-------------------------------------------
  1209.    //           draw logout form
  1210.    //-------------------------------------------
  1211.    private function drawLogoutForm() {
  1212.  
  1213.       $logoutform = new logoutForm();
  1214.       $this->gbpage=$logoutform->draw();
  1215.    }
  1216.  
  1217.    //-------------------------------------------
  1218.    //               logout
  1219.    //-------------------------------------------
  1220.    private function logout() {
  1221.  
  1222.       $this->logged_in=false;
  1223.       $this->user_id=0;
  1224.       $this->setRedirect('action=view');
  1225.    }
  1226.  
  1227.    //-------------------------------------------
  1228.    //       draw register form
  1229.    //-------------------------------------------
  1230.    private function drawRegisterForm() {
  1231.  
  1232.    $this->trass('draw register form');
  1233.    
  1234.    $regform = new registerForm();
  1235.    $this->gbpage=$regform->draw();
  1236.  
  1237. }
  1238.  
  1239.    //-------------------------------------------
  1240.    private function register() {
  1241.    
  1242.       $uname=$this->filter($_REQUEST["username"]);
  1243.       $passw=$_REQUEST["password"];
  1244.       $email=$this->filter($_REQUEST["useremail"]);
  1245.       $gender=$this->filter($_REQUEST["gender"]);
  1246.       $country=$this->filter($_REQUEST["country"]);
  1247.       $interests=$this->filter(implode(",",$_REQUEST["interests"]));
  1248.       $comments=$this->filter($_REQUEST["comments"]);
  1249.    
  1250.       $sql="select * from gbusers where user_name=\"$uname\"";
  1251.       $result=$this->db->Query($sql);
  1252.       if ($result===FALSE) {
  1253.          throw new Exception ('Error while executing query: '.$sql, EXECQUERY_ERROR);
  1254.       }
  1255.       if ($result->num_rows>0) {
  1256.  
  1257.          $this->gbpage= <<<INF
  1258.  
  1259.              Error: user already exists
  1260.              {$this->link("action=register",'try again')}
  1261.              {$this->link("action=view", 'back to list')}
  1262. INF;
  1263.  
  1264.       return;
  1265.       }
  1266.  
  1267.       $sql="insert into gbusers(user_name, user_password, user_email) ".
  1268.                    "values(?,?,?)";
  1269.                    
  1270.        
  1271.       $this->user_id=$this->execQueryP($sql, array("sss", $uname, $passw, $email));
  1272.       $this->logged_in=true;
  1273.      
  1274.       $this->gbpage="user successfully created ".
  1275.                $this->link("action=view",'back to list');
  1276.  
  1277.    }
  1278.  
  1279.  
  1280.    //-------------------------------------------
  1281.    //   draw form for connection file editing
  1282.    //-------------------------------------------
  1283.    private function drawConnFileForm($edit=false) {
  1284.  
  1285.       $this->trass('draw connection file edit form');
  1286.      
  1287.       if ($edit) {
  1288.          if (!file_exists(gbModel::PARAM_FILE))
  1289.             throw new Exception ('no connection file', NOCONNFILE_ERROR);
  1290.  
  1291.          $inf=file(gbModel::PARAM_FILE);
  1292.  
  1293.          foreach ($inf as &$item) {
  1294.             $item=substr($item, strpos($item,':')+1);
  1295.             $item=substr($item,0, strlen($item)-2);
  1296.          }
  1297.       }
  1298.      
  1299.       if (!isset($inf))
  1300.          $inf=array('','','','');
  1301.          
  1302.       $connfileForm= new connectionfileForm($this->action,$inf);
  1303.      
  1304.       $this->gbpage = $connfileForm->draw();
  1305.  
  1306.    }
  1307.  
  1308.    //-------------------------------------------
  1309.    //      save connection file
  1310.    //-------------------------------------------
  1311.    private function saveConnection() {
  1312.      
  1313.       $fh=fopen(gbModel::PARAM_FILE,'wb');
  1314.  
  1315.       fwrite($fh,'host:'.$_REQUEST["host"]."\r\n");
  1316.       fwrite($fh,'username:'.$_REQUEST["username"]."\r\n");
  1317.       fwrite($fh,'password:'.$_REQUEST["password"]."\r\n");
  1318.       fwrite($fh,'database:'.$_REQUEST["database"]."\r\n");
  1319.  
  1320.       fclose($fh);
  1321.  
  1322.       $this->gbpage= 'file successfully written'.
  1323.                       $this->link('action=editconnfile','edit connection file').
  1324.                       $this->link('action=view', 'go to guestbook');
  1325.  
  1326.    }
  1327.    
  1328.    //-------------------------------------------
  1329.    //     draw  create database form
  1330.    //-------------------------------------------
  1331.    private function drawCreateDatabaseForm() {
  1332.    
  1333.       $this->gbpage=<<<INF
  1334.        
  1335.        <script type="text/javascript">
  1336.            function back_to_list() {
  1337.               window.location.assign("{$_SERVER["PHP_SELF"]}");          
  1338.            }
  1339.        </script>
  1340.        Database will be recreated. Are you sure?
  1341.        <form action="{$_SERVER["PHP_SELF"]}" method="POST" enctype="application/x-www-form-urlencoded">
  1342.        <input type="HIDDEN" name="action" value="database" />
  1343.        <input type="HIDDEN" name="step" value=2 />
  1344.        <input type="SUBMIT" name="submit" value="ok" />
  1345.        <input type="BUTTON" value="cancel" onclick="back_to_list();" />
  1346.        </form>
  1347.      
  1348.      
  1349. INF;
  1350.    }
  1351.    //-------------------------------------------
  1352.    //           create database
  1353.    //-------------------------------------------
  1354.    private function createDatabase() {
  1355.    
  1356.       $sqls=array();
  1357.       $sqls[]='drop table if exists gb';
  1358.       $sqls[]='drop table if exists gbusers';
  1359.       $sqls[]='create table gb (id int(11) not null auto_increment,
  1360.                entry_author_id int(11),
  1361.                entry_author varchar(50),
  1362.                entry_date datetime,
  1363.                entry_caption varchar(200),
  1364.                entry_text varchar(1000),
  1365.                primary key(`id`))';    
  1366.                
  1367.       $sqls[]='create table gbusers(id int(11) not null auto_increment,
  1368.               user_name varchar(50),
  1369.               user_password varchar(50),
  1370.               user_email varchar(100),
  1371.               user_gender varchar(1),
  1372.               user_interests varchar(200),
  1373.               user_country varchar(50),
  1374.               user_picture varchar(100),
  1375.               primary key(`id`))';
  1376.      
  1377.       foreach ($sqls as $sql)
  1378.             $this->execQuery($sql);
  1379.        
  1380.       session_destroy();       
  1381.       $this->gbpage='database successfully created'.
  1382.                  $this->link('action=view','Home');  
  1383.          
  1384.      
  1385.    }
  1386.    
  1387.    //-------------------------------------------
  1388.    //          set redirect path
  1389.    //-------------------------------------------
  1390.  
  1391.    private function setRedirect($action) {
  1392.  
  1393.       $this->redirect_path=$_SERVER["PHP_SELF"]."?$action";
  1394.    }
  1395.  
  1396.  
  1397.    //-------------------------------------------
  1398.    //        filter form data
  1399.    //-------------------------------------------
  1400.    private function filter($instr) {
  1401.       return $this->db->real_escape_string(htmlentities($instr));
  1402.    }
  1403.  
  1404.    //-------------------------------------------
  1405.    //     check user privileges
  1406.    //-------------------------------------------
  1407.    private function checkPrivileges() {
  1408.  
  1409.       if ($this->user_id===0)
  1410.          throw new Exception ('data access denied', NOACCESS_ERROR);
  1411.      
  1412.       $sql="select entry_author_id from gb where id={$this->current_element}";
  1413.      
  1414.       $row=$this->getSingle($sql);
  1415.    
  1416.    }
  1417.  
  1418.    //-------------------------------------------
  1419.    //          show error page
  1420.    //-------------------------------------------
  1421.  
  1422.    private function showErrorPage() {
  1423.      
  1424.       $this->trass('show error page');
  1425.      
  1426.       $tmp='<div id="errormessage_block">';
  1427.  
  1428.       switch ($this->errorno) {
  1429.  
  1430.          case NOCONNFILE_ERROR:
  1431.             $tmp.='Connection file doesn\'t exist';
  1432.             $tmp.=$this->link('action=connfile','Create connection file?');
  1433.             break;
  1434.          
  1435.          case CONNECTION_ERROR:
  1436.             $tmp.='Connection failed';
  1437.             $tmp.=$this->link('action=editconnfile','Check connection file?');
  1438.             break;
  1439.  
  1440.          case NODATABASE_ERROR:
  1441.             $tmp.='Database doesn\'t exist';
  1442.             $tmp.=$this->link('action=database','Create database?');
  1443.             break;
  1444.  
  1445.          case NOFOUND_ERROR:
  1446.             $tmp.=$this->error_message;
  1447.             break;
  1448.  
  1449.          case NOACCESS_ERROR:
  1450.             $tmp.=$this->error_message;
  1451.             $tmp.=$this->link('action=view','back');
  1452.             break;
  1453.            
  1454.          default:
  1455.               $tmp.=$this->error_message;
  1456.               $tmp.=$this->link('action=view','back');
  1457.  
  1458.       }
  1459.       $tmp.='</div>';
  1460.  
  1461.       $this->gbpage=$tmp;
  1462.    }
  1463.    
  1464.    //-------------------------------------------
  1465.    //         draw reference link
  1466.    //-------------------------------------------
  1467.    private function link($action,$text) {
  1468.    
  1469.       return "<a href=\"{$this->getRoute($action)}\">$text</a>";
  1470.    }
  1471.  
  1472.    //-------------------------------------------
  1473.    //        get route  address
  1474.    //-------------------------------------------
  1475.    private function getRoute($action) {
  1476.       return $_SERVER["PHP_SELF"]."?$action";
  1477.    }
  1478.  
  1479.    //-------------------------------------------
  1480.    //      handle all exceptions
  1481.    //-------------------------------------------
  1482.    private function handle_errors($e) {
  1483.  
  1484.       $this->trass('handle error');
  1485.       $this->trass('error:'.$e->getMessage());
  1486.      
  1487.       if ($this->action=='error')
  1488.          die ('exception while error handling');
  1489.  
  1490.       $this->errorno=$e->getCode();  
  1491.       $this->error_message=$e->getMessage();
  1492.       $this->error_procedure=$this->current_procedure;
  1493.  
  1494.  
  1495.       $this->action='error';
  1496.       $this->defaultProcess();  
  1497.    }
  1498.  
  1499.  
  1500.    //-------------------------------------------
  1501.    //     get guestbook instance
  1502.    //-------------------------------------------
  1503.    static function getGb() {
  1504.       if (!isset(gbModel::$gb))
  1505.          gbModel::$gb = new gbModel();
  1506.  
  1507.        return gbModel::$gb;
  1508.    }
  1509.  
  1510. }
  1511.  
  1512. //-----------------------------------------------------------------------------
  1513. //                  GuestBook Controller
  1514. //-----------------------------------------------------------------------------
  1515. class gbController {
  1516.  
  1517.    public $gb;
  1518.  
  1519.    public static $controller;
  1520.    
  1521.    //-------------------------------------------
  1522.    //          constructor
  1523.    //-------------------------------------------
  1524.    private function __construct() {
  1525.  
  1526.       $this->gb= gbModel::getGb();
  1527.  
  1528.       $this->process();
  1529.      
  1530.    }
  1531.    
  1532.    //-------------------------------------------
  1533.    //       get controller instance
  1534.    //-------------------------------------------
  1535.    static function getController() {
  1536.  
  1537.       if (!isset(gbController::$controller))
  1538.          gbController::$controller= new gbController();
  1539.  
  1540.       return gbController::$controller;
  1541.    }
  1542.  
  1543.    //-------------------------------------------
  1544.    //    controller main procedure
  1545.    //-------------------------------------------
  1546.    public function process() {
  1547.  
  1548.       session_start();
  1549.       $this->restoreSession();
  1550.       $this->processInput();
  1551.  
  1552.       $this->triggerGB();
  1553.  
  1554.       $this->saveSession();
  1555.       session_commit();
  1556.  
  1557.       if ($this->gb->redirect_path)
  1558.          header("Location: {$this->gb->redirect_path}");
  1559.    }
  1560.    
  1561.    //-------------------------------------------
  1562.    //       restore session
  1563.    //-------------------------------------------
  1564.    private function restoreSession() {
  1565.  
  1566.       if (isset($_SESSION['current_page']))
  1567.          $this->gb->current_page=$_SESSION['current_page'];
  1568.  
  1569.       if (isset($_SESSION['current_element']))
  1570.          $this->gb->current_element=$_SESSION['current_element'];
  1571.  
  1572.       if (isset($_SESSION['got_params']))
  1573.          $this->gb->got_params=$_SESSION['got_params'];
  1574.  
  1575.       if (isset($_SESSION['conn_params']))
  1576.          $this->gb->conn_params=$_SESSION['conn_params'];
  1577.  
  1578.       if (isset($_SESSION['logged_in']))
  1579.          $this->gb->logged_in=$_SESSION['logged_in'];
  1580.  
  1581.       if (isset($_SESSION['user_id']))
  1582.          $this->gb->user_id=$_SESSION['user_id'];
  1583.    }
  1584.  
  1585.    //-------------------------------------------
  1586.    //          save session
  1587.    //-------------------------------------------
  1588.    private function saveSession() {
  1589.  
  1590.       $_SESSION['current_page']=$this->gb->current_page;
  1591.       $_SESSION['current_element']=$this->gb->current_element;
  1592.       $_SESSION['got_params']=$this->gb->got_params;
  1593.       $_SESSION['conn_params']=$this->gb->conn_params;
  1594.       $_SESSION['logged_in']=$this->gb->logged_in;
  1595.       $_SESSION['user_id']=$this->gb->user_id;
  1596.      
  1597.    }
  1598.  
  1599.    //-------------------------------------------
  1600.    //     process input parameters
  1601.    //-------------------------------------------
  1602.    private function processInput() {
  1603.      
  1604.      
  1605.       //--------------------------
  1606.       if (isset($_REQUEST['action'])) {
  1607.          $this->gb->action=$_REQUEST['action'];
  1608.       }
  1609.       else
  1610.          $this->gb->action='view';
  1611.  
  1612.       //--------------------------
  1613.       if (isset($_REQUEST['step'])) {
  1614.          $this->gb->step=$_REQUEST['step'];
  1615.       }
  1616.       else
  1617.          $this->gb->step=1;
  1618.       //--------------------------
  1619.       if (isset($_REQUEST['page'])) {
  1620.          $this->gb->current_page=$_REQUEST['page'];
  1621.       }
  1622.       //--------------------------
  1623.       if (isset($_REQUEST['element'])) {
  1624.          $this->gb->current_element=$_REQUEST['element'];
  1625.       }
  1626.    }
  1627.  
  1628.    //-------------------------------------------
  1629.    //    trigger guestbook main process
  1630.    //-------------------------------------------
  1631.    private function triggerGB() {
  1632.  
  1633.       $this->gb->defaultProcess();
  1634.  
  1635.    }
  1636.  
  1637.  
  1638.    
  1639. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement