Advertisement
terorama

WP / inc / base.inc.php

May 29th, 2013
60
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 38.61 KB | None | 0 0
  1. <?php
  2.  
  3. //----------------------------------------------
  4. //                interfaces
  5. //----------------------------------------------
  6. interface IInjectable {
  7.  
  8.    public function __construct($injector);
  9. }
  10.  
  11. interface IDebug {
  12.    
  13.    public function reset();
  14.    public function errorHandler($number, $message, $file, $line);
  15.    public function exceptionHandler($exception);
  16.    public function shutdownHandler();
  17.    public function writeInfo($info, $className, $method);
  18.    public function debugMode($mode);
  19. }
  20.  
  21. interface IDBConn {
  22.    
  23.    public function connect();
  24.    public function set($DB_HOST, $DB_USER, $DB_PASSWORD, $DB_NAME);
  25.    public function get();
  26. }
  27.  
  28. interface IDecorator {
  29.  
  30.     public function addEventListener($event, $obj, $proc);
  31. }
  32.  
  33. interface IForm {
  34. }
  35.  
  36. interface IDBModel {
  37.  
  38.    public function getTableName($tabname);
  39.    public function getRecordById($model, $id);
  40.    public function getNRecords($model, $start, $num);
  41.    public function getNumRecs($model);
  42.    public function insertRecord($model, $values);
  43.    public function updateRecord($model, $id, $values);
  44.    public function deleteRecord($model, $id);
  45.  
  46. }
  47.  
  48. interface IController {
  49.  
  50.    public function dispatch();
  51.    public function render($retblocks=true, $tmpl='');
  52. }
  53.  
  54. interface IModel {
  55.  
  56.    public function getSingle($record_id);
  57.    public function getPage($page_id=0);
  58.    public function getAll();
  59.    public function getNumPages();
  60.    public function insertItem();
  61.    public function updateItem($id, $vals=array());
  62.    public function deleteItem($id);
  63. }
  64.  
  65. interface IView {
  66.  
  67.    public function setup($controllerName, $action, $routes);
  68.    public function render($retblocks, $tmpl );
  69. }
  70.  
  71. //----------------------------------------------
  72. //              base classes
  73. //----------------------------------------------
  74. //                Injector
  75. //----------------------------------------------
  76. class Injector {
  77.    
  78.    private $_instances = array();
  79.    
  80.    public function set($instance) {
  81.    
  82.       array_push($this->_instances, $instance);
  83.    }
  84.    
  85.    public function get($interface) {
  86.      
  87.       foreach ($this->_instances as $instance) {
  88.          
  89.          $className = get_class($instance);
  90.          
  91.          $refl = new ReflectionClass($className);
  92.          
  93.          if ($refl->implementsInterface($interface))
  94.             return $instance;
  95.       }
  96.    }
  97.    
  98. }
  99. //----------------------------------------------
  100. //                Decorator
  101. //----------------------------------------------
  102. abstract class Decorator implements IDecorator {
  103.  
  104.    
  105.  
  106.    protected $_subscribers =array();
  107.    
  108.  
  109.    //-------------------------------
  110.    public function addEventListener($event, $obj, $proc) {
  111.    
  112.       if (!isset($this->_subscribers[$event]))
  113.          $this->_subscribers[$event]=array();
  114.          
  115.        $subscriber = array();
  116.        $subscriber['object'] = $obj;
  117.        $subscriber['procedure'] = $proc;
  118.        
  119.        $this->_subscribers[$event][] = $subscriber;
  120.    }
  121.    //-------------------------------
  122.    protected function dispatchEvent($event) {
  123.    
  124.       $args = func_get_args();
  125.       array_shift($args);
  126.      
  127.       $subscribers = $this->_subscribers[$event];
  128.      
  129.       if (!is_array($subscribers))
  130.          return;
  131.          
  132.       $s ='';
  133.       foreach ($subscribers as $subscriber) {
  134.          $s .= call_user_func_array(array($subscriber['object'], $subscriber['procedure']), $args);
  135.       }
  136.       return $s;
  137.    }
  138. }
  139.  
  140. //----------------------------------------------
  141. //              Controller
  142. //----------------------------------------------
  143. abstract class Controller implements IController {
  144.  
  145.    private $_debug;
  146.  
  147.    protected $_model;
  148.    protected $_view;
  149.    
  150.    protected $_routes;
  151.    protected $_controller_name;
  152.    protected $_action_name;
  153.    
  154.    protected $_params=array();
  155.    
  156.    //---------------------------- debug information
  157.    protected function _w($info, $method) {
  158.    
  159.       $className = get_class($this);
  160.       $this->_debug->writeInfo($info, $className, $method);
  161.    }
  162.    
  163.    //---------------------------- collect session and input parameters
  164.      
  165.    private function getSessionParams() {
  166.    
  167.       if (!isset($_SESSION))
  168.          return;
  169.          
  170.       foreach ($_SESSION as $key=>$val) {
  171.          
  172.          foreach ($this->_params as $pkey=>$pval) {
  173.          
  174.             if ($key==$pkey) {
  175.                $this->_params[$pkey]=$_SESSION[$key];
  176.             }
  177.          }
  178.       }  
  179.       $this->_w( $this->_params, __METHOD__);
  180.    }
  181.    //--------------------------------
  182.    private function getInputParams() {
  183.      
  184.       foreach ($_REQUEST as $key=>$val) {
  185.          
  186.          foreach ($this->_params as $pkey=>$pval) {
  187.            
  188.             if ($key==$pkey) {
  189.                $this->_params[$pkey]=$_REQUEST[$key];
  190.                
  191.                $_SESSION[$pkey] = $this->_params[$pkey];
  192.             }
  193.          }
  194.       }
  195.    }
  196.    
  197.    //---------------------------------- get related controllers
  198.    public function related() {
  199.       return array();
  200.    }
  201.    
  202.    //---------------------------------- declare expected GET parameters
  203.    
  204.    protected function declareParams() {
  205.    
  206.      
  207.       $this->_params[$this->_model->_idfield] = '';
  208.       $this->_params['dbkey'] = $this->_model->_idfield;
  209.       $this->_params['filter'.$this->_controller_name] = '';
  210.    }
  211.    
  212.    //--------------------------------get parameters
  213.    private function getParams() {
  214.    
  215.       $this->getSessionParams();
  216.       $this->getInputParams();
  217.      
  218.       if (preg_match('/[A-Za-z0-9_ ]*/', $this->_params['filter'.$this->_controller_name]))
  219.          $this->_model->_filterstr = $this->_params['filter'.$this->_controller_name];
  220.       else
  221.          throw new Exception('filter security violation');
  222.    }
  223.    
  224.    
  225.    //---------------------------------------init
  226.    
  227.    public function __construct($injector, $controllerName, $action) {
  228.      
  229.       $this->_debug = $injector->get('IDebug');
  230.      
  231.       $this->_controller_name = $controllerName;
  232.       $this->_action_name = $action;
  233.      
  234.       $this->_model = $injector->get('IModel');
  235.       $this->_view = $injector->get('IView');
  236.  
  237.       $func = create_function('$a',' return str_replace("[dbkey]","'.$this->_model->_idfield.'", $a);');     
  238.       $this->_routes = array_map ($func, $this->_routes );
  239.       $this->_view ->setup($controllerName, $action, $this->_routes);
  240.      
  241.       //-----------------params
  242.       $this->declareParams();
  243.       $this->getParams();
  244.    }
  245.    
  246.    //----------------------------------   properties get handler
  247.    public function __get($name) {
  248.    
  249.       if (substr($name,0,3)=='p__') {
  250.      
  251.          $paramName = substr($name,3);       
  252.          return $this->get($paramName);  
  253.       }
  254.    }
  255.    //-------------------------------- get property
  256.    public function get($name) {
  257.    
  258.       if (array_key_exists($name, $this->_params))   
  259.             return $this->_params[$name];
  260.          else
  261.             return false;
  262.    }
  263.    //----------------------------------   common dispatching operations
  264.    
  265.    abstract protected function commonDispatch();
  266.    
  267.    //---------------------------------   set view variable
  268.    protected function set($name, $value) {
  269.      
  270.       $this->_view->set($name, $value);
  271.    }
  272.    //---------------------------------   set block of view variables
  273.    protected function setAll($el) {
  274.    
  275.       foreach ($el as $key=>$value) {
  276.          $this->set($key,$value);
  277.       }
  278.    }  
  279.    
  280.    //----------------------------------   dispatch current action
  281.    public function dispatch() {
  282.    
  283.       $this->commonDispatch();
  284.      
  285.       //$this->_w($this->_action,__METHOD__);
  286.      
  287.       if ((int)method_exists($this, $this->_action_name)) {
  288.        
  289.          call_user_func (array($this, $this->_action_name));
  290.       }
  291.    }
  292.    
  293.    //--------------------------------------   render view
  294.    public function render($retblocks=true, $tmpl='') {
  295.    
  296.       return $this->_view->render($retblocks, $tmpl);
  297.    }
  298. }
  299.  
  300. //----------------------------------------------
  301. //               form input
  302. //----------------------------------------------
  303. class stdInput {
  304.    
  305.    private $_type;
  306.    public $_name;
  307.    private $_value;
  308.    private $_values = array();
  309.    private $_label = '';
  310.    private $_labels = array();
  311.    private $_group_caption;
  312.    
  313.    private $_handlers = array();
  314.    //--------------------------------   constructor
  315.    
  316.    public function __construct($type, $name, $value, $label='', $group_caption='') {
  317.      
  318.       $this->_type = $type;
  319.       $this->_name = $name;
  320.       $this->_group_caption = $group_caption;
  321.      
  322.       //------------------------- values
  323.       $this->setValue($value);
  324.      
  325.       //------------------------- labels
  326.       if (is_array($label)) {
  327.          for ($i=0; $i<count($label); $i++) {
  328.             $this->_labels[] = $label[$i];
  329.          }
  330.       } else {
  331.          $this->_label = $label;
  332.       }
  333.    }  
  334.    //------------------------------------------- set field values
  335.    
  336.    public function setValue($value) {
  337.    
  338.       //-------------------- checkboxes and radiogroups
  339.       if (is_array($value)) {
  340.      
  341.          $this->_values = array();
  342.          
  343.          for ($i=0; $i<count($value); $i++) {
  344.            
  345.             $el = array();
  346.             if (substr($value[$i], strlen($value[$i])-1,1)=='*') {
  347.            
  348.                $el['checked']=true;
  349.                $el['value'] = substr($value[$i],0,strlen($value[$i])-1);
  350.             } else {
  351.            
  352.                $el['checked']=false;
  353.                $el['value'] = $value[$i];
  354.             }
  355.             $this->_values[] = $el;        
  356.          }       
  357.       } //------- single components ( text / password / button / submit /reset )     
  358.       else {
  359.          $this->_value = $value;
  360.       }
  361.    }
  362.    //-------------------------------------------   add handler
  363.    public function addHandler ($handler) {
  364.      
  365.       $this->_handlers[] = array ('event'=>$handler[0], 'handler'=>$handler[1]);
  366.    }
  367.    //------------------------------   draw input
  368.    public function draw() {
  369.    
  370.       $s = '';
  371.       $handlers_str = '';
  372.      
  373.       for ($i=0; $i<count($this->_handlers); $i++) {
  374.      
  375.          $handlers_str .= $this->_handlers[$i]['event'].'="'.$this->_handlers[$i]['handler'].'" ';
  376.       }
  377.      
  378.       switch (strtolower($this->_type)) {
  379.          //--------------------------
  380.          case 'text': case 'password': case 'submit':
  381.          case 'reset': case 'button': case 'file': case 'hidden':
  382.          
  383.             if ($this->_label) {
  384.                $s .= "<label for=\"{$this->_name}\">{$this->_label}</label>";            
  385.             }
  386.            
  387.             $s .= "<input $handlers_str type=\"{$this->_type}\" ".
  388.                   "name=\"{$this->_name}\" value=\"{$this->_value}\" />";
  389.             break;
  390.          //--------------------------
  391.          case 'textarea':
  392.             if ($this->_label)
  393.                $s .= "<p>{$this->_label}</p>";
  394.            
  395.             $s .= "<textarea $handlers_str rows=\"10\" cols=\"90\" name=\"{$this->_name}\">{$this->_value}</textarea><br/>";
  396.             break;
  397.            
  398.          //--------------------------
  399.          case 'radio': case 'checkbox':
  400.          
  401.             $s .= "<label for=\"{$this->_name}\">{$this->_group_caption}</label>";
  402.            
  403.             for ($i=0; $i<count($this->_values); $i++) {
  404.            
  405.                //$checked = ($this->_values[$i]['checked']) ? 'checked' : '';
  406.                $checked = ($this->_values[$i]['value']==$this->_value) ? 'checked' : '';
  407.                
  408.                $s .= "<p><input $handlers_str type=\"{$this->_type}\" ".
  409.                      " name=\"{$this->_name}\" value=\"{$this->_values[$i]['value']}\" $checked />";
  410.                      
  411.                $s .= $this->_labels[$i].'</p>';  
  412.             }
  413.             break;
  414.            
  415.          //--------------------------
  416.          case 'select':
  417.          
  418.             $s .= "<label for=\"{$this->_name}\">{$this->_group_caption}</label>";
  419.            
  420.             $s .= "<select $handlers_str name=\"{$this->_name}\">";
  421.             for ($i=0; $i<count($this->_values); $i++) {
  422.                
  423.                $selected = ($this->_values[$i]['value']==$this->_value) ? 'selected' : '';
  424.                $s .= "<option value=\"{$this->_values[$i]['value']}\" $selected >";
  425.                $s .= $this->_labels[$i].'</option>';
  426.             }
  427.             $s .= '</select><br/>';
  428.             break;
  429.       }
  430.      
  431.       return $s;
  432.    }
  433. }
  434.  
  435. //----------------------------------------------
  436. //               form fieldset
  437. //----------------------------------------------
  438. class stdFieldset {
  439.    
  440.    public $fields = array();
  441.    private $legend;
  442.    
  443.    //------------------------------------ constructor
  444.    public function __construct($legend) {
  445.      
  446.       $this->legend = $legend;
  447.    }
  448.    
  449.    //------------------------------      
  450.    public function hasField($name) {
  451.    
  452.       for ($i=0; $i<count($this->fields); $i++) {
  453.          if ($this->fields[$i]->_name == $name)
  454.             return true;
  455.       }
  456.       return false;
  457.    }
  458.    
  459.      //------------------------------      
  460.    public function getField($name) {
  461.    
  462.       for ($i=0; $i<count($this->fields); $i++) {
  463.          if ($this->fields[$i]->_name == $name)
  464.             return $this->fields[$i];
  465.       }
  466.       return false;
  467.    }
  468.    
  469.    //------------------------------   add field
  470.    
  471.    public function addField($type, $name, $value, $label, $group_caption='') {
  472.      
  473.       $a = new stdInput ($type, $name, $value, $label, $group_caption);
  474.       $this->fields[] = & $a;
  475.      
  476.    }
  477.    //------------------------------   draw field
  478.    
  479.    public function draw() {
  480.      
  481.       $s = "<fieldset><legend>{$this->legend}</legend>";
  482.      
  483.       for ($i=0; $i<count($this->fields); $i++)
  484.          $s .= $this->fields[$i]->draw();
  485.          
  486.       $s .= '</fieldset>';
  487.       return $s;
  488.    }
  489.    
  490. }
  491.  
  492. //----------------------------------------------
  493. //                  Form
  494. //----------------------------------------------
  495. class stdForm implements IForm {
  496.    
  497.     private $_debug;
  498.    
  499.     public $_model;
  500.     protected $_id;
  501.     private $_action_route;
  502.    
  503.     protected $scripts = array();
  504.     private $fieldsets = array();
  505.     private $hidden_fields = array();
  506.     private $buttons = array();
  507.    
  508.     //-------------------------   debug information
  509.    
  510.     protected function _w($info, $method) {
  511.    
  512.       $className = get_class($this);
  513.       $this->_debug->writeInfo($info, $className, $method);
  514.     }  
  515.     //-------------------------   check if empty
  516.    
  517.     public function nzz($var, $default) {
  518.        return (isset($var)) ? $var : $default;
  519.     }
  520.     //-------------------------   constructor
  521.    
  522.     public function __construct($injector ) {
  523.        
  524.        $this->_debug = $injector->get('IDebug');
  525.        $this->_model = $injector->get('IModel');
  526.        $this->_id = 'form_'.rand(10,5000);
  527.     }  
  528.    
  529.     //--------------------------  setup field values
  530.    
  531.     public function set_field_values($flds) {
  532.    
  533.        foreach ($flds as $name=>$value) {
  534.           foreach ($this->fieldsets as $key=>$fieldset) {
  535.              if ($fieldset->hasField($name))
  536.                 $this->fieldsets[$key]->getField($name)->setValue($value);
  537.           }
  538.          
  539.           for ($i=0; $i<count($this->hidden_fields); $i++) {
  540.              if ($this->hidden_fields[$i]->_name == $name)
  541.                 $this->hidden_fields[$i]->setValue($value);
  542.           }
  543.          
  544.           for ($i=0; $i<count($this->buttons); $i++) {
  545.              if ($this->buttons[$i]->_name == $name)
  546.                 $this->buttons[$i]->setValue($value);
  547.           }
  548.        }
  549.     }
  550.    
  551.     //-------------------------- set form action route
  552.    
  553.     public function set_action_route ($action_route) {
  554.    
  555.        $this->_action_route = $action_route;
  556.     }
  557.  
  558.     //--------------------------   add fieldset
  559.    
  560.     public function addFieldset ($legend) {
  561.        
  562.        $a = new stdFieldset($legend);
  563.        $this->fieldsets[] = & $a;
  564.        return $a;
  565.     }  
  566.     //--------------------------   add hidden field
  567.    
  568.     public function addHidden ($name, $value) {
  569.    
  570.        $this->hidden_fields[] = new stdInput ('HIDDEN', $name, $value);
  571.     }  
  572.     //--------------------------   add button
  573.    
  574.     public function addButton ($type, $name, $value, $onclick='') {
  575.        
  576.        if (is_array($onclick)) {       
  577.           $this->scripts[$name] = array ('handler'=>$onclick[0], 'script'=>$onclick[1]);  
  578.        }
  579.        
  580.        $a = new stdInput ($type, $name, $value);
  581.        
  582.        if (is_array($onclick))
  583.           $a->addHandler(array('onclick', $onclick[0]));
  584.          
  585.        $this->buttons[] = & $a;
  586.     }  
  587.     //---------------------------   draw header
  588.    
  589.     private function drawHeader() {
  590.        
  591.        $s = '';//<script type="text/javascript">';
  592.        foreach ($this->scripts as $script) {
  593.        
  594.           $s .= $script['script'];
  595.        }
  596.        //$s .= '</script>';
  597.        
  598.        $subm = (isset($this->scripts['onsubmit'])) ?
  599.                          'onsubmit="'.$this->scripts['onsubmit']['handler'].'"':'';
  600.                          
  601.        $s .= '<form '.$subm.' id="'.$this->_id.'" action="'.$this->_action_route.'" method="post" '.
  602.              ' enctype="application/x-www-form-urlencoded" >'; 
  603.  
  604.        return $s;            
  605.     }  
  606.     //---------------------------   draw footer
  607.    
  608.     private function drawFooter() {
  609.        
  610.        return '</form>';
  611.     }  
  612.     //---------------------------   draw form
  613.     public function draw() {
  614.    
  615.        $s = '';
  616.        $s .= $this->drawHeader();
  617.        
  618.        $func = create_function('$a',' echo $a->draw();');
  619.        
  620.        ob_start();     
  621.        array_walk($this->fieldsets, $func);
  622.        array_walk($this->hidden_fields, $func);
  623.        array_walk($this->buttons, $func);      
  624.        $s .= ob_get_contents();
  625.        ob_end_clean();
  626.        
  627.        $s .= $this->drawFooter();
  628.        return $s;
  629.     }
  630.    
  631.    
  632.    
  633. }
  634.  
  635.  
  636. //----------------------------------------------
  637. //                   View
  638. //----------------------------------------------
  639. abstract class View implements IView, IInjectable {
  640.    
  641.    private $_debug;
  642.    
  643.    protected   $_decorator;
  644.    public      $_form;
  645.    
  646.    protected $variables = array();
  647.    
  648.    protected $_controller_name;
  649.    protected $_action_name;
  650.    protected $_routes;
  651.    
  652.    protected $_blocks =array('header'=>'','content'=>'','sidebar'=>'','footer'=>'');
  653.    
  654.    protected $_stdtemplate = '<div id="%viewid%">
  655.       <div class="header">%header%</div>
  656.       <div class="content">%content%</div>
  657.       <div class="sidebar">%sidebar%</div>
  658.       <div class="footer">%footer%</div></div>';
  659.  
  660.    //---------------------------- debug information
  661.    protected function _w($info, $method) {
  662.    
  663.       $className = get_class($this);
  664.       $this->_debug->writeInfo($info, $className, $method);
  665.    }  
  666.    
  667.    //-------------------------   constructor
  668.    
  669.    public function __construct($injector) {
  670.    
  671.       $this->_debug = $injector->get('IDebug');
  672.       $this->_decorator = $injector->get('IDecorator');  
  673.      
  674.       $this->_form = $injector->get('IForm');
  675.      
  676.    }
  677.    
  678.    //-------------------------  transfer information from controller
  679.    
  680.    public function setup($controllerName, $action, $routes) {
  681.    
  682.       $this->_controller_name = $controllerName;
  683.       $this->_action_name = $action;
  684.       $this->_routes = $routes;
  685.    }
  686.    
  687.    //-------------------------   func calls handler
  688.    public function __call($name, $arguments) {
  689.    
  690.       //$this->_w(array('name'=>$name, 'args'=>$arguments),__METHOD__);
  691.      
  692.       if (substr($name, 0, 6 )=='route_') {
  693.      
  694.          $routeName = substr ($name, 6);
  695.          
  696.          return $this->getRoute($routeName, isset($arguments[0]) ? $arguments[0] :'');
  697.       }
  698.    }
  699.    
  700.    //-----------------------------------   properties get handler
  701.    public function __get($name) {
  702.      
  703.       if (substr($name,0,2)=='v_') {
  704.          
  705.          $varName = substr($name, 2);
  706.          return $this->get($varName);
  707.       }
  708.    }
  709.    
  710.    //-------------------------   build routes
  711.    
  712.    protected function getRoute($s, $param='') {
  713.    
  714.       $route = $this->_routes[$s];
  715.      
  716.       //$this->_w(array('routeName'=>$s, 'route'=>$route),__METHOD__);
  717.      
  718.       if (is_array($param)) {
  719.      
  720.          $zpar = array();
  721.          foreach ($param as $key=>$value) {
  722.          
  723.             $zpar[] = & $param[$key];
  724.          }
  725.          array_unshift($zpar, $route);
  726.          
  727.          $route = call_user_func_array('sprintf', $zpar);
  728.          }
  729.       else
  730.          $route = sprintf($route, $param);
  731.      
  732.       return $_SERVER["PHP_SELF"].'?controller='.$this->_controller_name.'&'.$route;
  733.    }
  734.    
  735.    //-------------------------   set variables
  736.    
  737.    public function set($name, $value) {
  738.      
  739.       $this->variables[$name] = $value;
  740.    }
  741.    
  742.    //-------------------------   get variables
  743.    
  744.    public function get($name) {
  745.    
  746.       if (array_key_exists($name, $this->variables))
  747.      
  748.          return $this->variables[$name];
  749.       else
  750.          return false;
  751.    }
  752.    
  753.    //--------------   common rendering operations and filling blocks
  754.    
  755.     abstract protected function renderBlocks();
  756.    
  757.    //-------------------------   output view to template
  758.    
  759.    private function output($tmpl) {
  760.      
  761.       if ($tmpl=='')
  762.          $tmpl= $this->_stdtemplate;
  763.    
  764.       $c = get_class($this);
  765.       $c = strtolower(substr($c, 0, strpos($c,'View')));
  766.      
  767.       $blocks = array_values($this->_blocks);
  768.       array_unshift($blocks , $c);
  769.      
  770.       $s = str_replace (array('%viewid%','%header%','%content%','%sidebar%','%footer%'), $blocks, $tmpl);
  771.      
  772.       return $s;     
  773.    }
  774.    
  775.    //-------------------------   render view
  776.    
  777.    public function render($retblocks, $tmpl ) {
  778.    
  779.    
  780.       if (method_exists($this, $this->_action_name))
  781.          call_user_func(array($this, $this->_action_name));
  782.          
  783.       $this->renderBlocks();
  784.      
  785.    
  786.       if ($retblocks)   {
  787.      
  788.          $c = get_class($this);
  789.          $pref = substr($c,0, strpos($c,'View'));
  790.          $prefixf = create_function('$a', 'return "'.$pref.'_".$a;');
  791.          return
  792.             array_combine(
  793.                    array_map($prefixf, array_keys($this->_blocks)),
  794.                    array_values($this->_blocks));
  795.          }       
  796.       else
  797.          return $this->output($tmpl);    
  798.    }
  799. }
  800.  
  801.  
  802.  
  803. //----------------------------------------------
  804. //                  Model
  805. //----------------------------------------------
  806. abstract class Model implements IModel, IInjectable {
  807.    
  808.    private $_db_model;
  809.    
  810.    public $_table='';
  811.    public $_idfield='';
  812.    public $_orderstr='';
  813.    public $_filterstr='';
  814.    public $fields = array(); // fn, ft, fc
  815.    
  816.    public $_postvars = array();
  817.    public $_mandatory = array();
  818.    private $_autovars = array();
  819.    
  820.    protected $_injector;
  821.    
  822.    public $rec_per_page=50;
  823.    
  824.    //--------------------------------   get post vars
  825.    private function getPostVars() {
  826.      
  827.       foreach ($_POST as $key=>$val) {
  828.          foreach ($this->_postvars as $pkey=>$pval) {
  829.          
  830.             if ($key==$pkey) {
  831.                $this->_postvars[$pkey] = $val;
  832.             }
  833.          }
  834.       }
  835.    }  
  836.    //--------------------------------   set auto vars
  837.    
  838.    abstract protected function setAutoVars();
  839.    
  840.    //--------------------------------   prepare to write to database
  841.    private function prepareInfo() {
  842.      
  843.       $this->getPostVars();
  844.      
  845.       //$this->_w($this->_postvars,__METHOD__);
  846.       $this->setAutoVars();
  847.      
  848.      
  849.      
  850.       $zff = create_function ('$a','return $a[\'fn\'];');
  851.       $zfn = create_function ('$a','return is_array($a[\'fc\']) ? $a[\'fs\'] : $a[\'fc\'];');
  852.       $titles = array_combine(array_map($zff, $this->fields), array_map($zfn, $this->fields));
  853.      
  854.       $errs = array();
  855.       foreach ($this->_postvars as $key=>$value) {
  856.          if (isset($this->_mandatory[$key])) {
  857.          
  858.             $z = $this->_mandatory[$key];
  859.             if (isset($z['funcs'])) {
  860.                foreach ($z['funcs'] as $func) {
  861.                   $fn = create_function('$a',$func);
  862.                   $value = call_user_func($fn, $value);
  863.                }
  864.             }
  865.             if (isset($z['checks'])) {
  866.                foreach ($z['checks'] as $check) {
  867.                
  868.                   $fn = create_function('$a', $check['func']);
  869.                   if (call_user_func($fn, $value)==false) {
  870.                  
  871.                      $errs[] = sprintf( $check['message'], $titles[$key]);
  872.                   }
  873.                }
  874.             }
  875.             $this->_postvars[$key] = $value;
  876.          }
  877.       }
  878.       if (count($errs)>0)
  879.          return implode('<br/', $errs);
  880.      
  881.       return  array_merge($this->_postvars, $this->_autovars);
  882.    }
  883.    
  884.    //--------------------------------   constructor
  885.    public function __construct($injector) {
  886.    
  887.       $this->_injector = $injector;
  888.       $this->_db_model = $injector->get('IDBModel');
  889.       $this->_table = $this->_db_model->getTableName($this->_table);
  890.      
  891.    }  
  892.    //--------------------------------   set properties handler
  893.    public function __set($name, $value) {
  894.      
  895.       if (substr($name,0,3)==='a__') {
  896.      
  897.          $varName = substr($name,3);
  898.          $this->_autovars[$varName] = $value;
  899.       }
  900.    }      
  901.    //--------------------------------   get single item
  902.    
  903.    public function getSingle($record_id) {
  904.    
  905.       $el = $this->_db_model->getRecordById($this, $record_id);
  906.      
  907.       $out = array();
  908.       foreach ($el as $key=>$val) {
  909.          //--------------------------------
  910.          foreach ($this->fields as $fld) {
  911.             if ($fld['fn']==$key) {
  912.                if (array_key_exists($fld['fn'], $this->_postvars)) {
  913.                   $out[$key] = $val;         
  914.                }
  915.                break;
  916.             }
  917.         }
  918.         //--------------------------------
  919.         if ($key==$this->_idfield) {
  920.            $out['idfield'] = $val;
  921.         }
  922.      }
  923.      return $out;    
  924.      
  925.    }
  926.    //--------------------------------   get page
  927.    
  928.    public function getPage($page_id=0) {
  929.  
  930.       if (!is_numeric($page_id))
  931.          $page_id = 0;
  932.        
  933.       $els = $this->_db_model->getNRecords($this, $page_id * $this->rec_per_page, $this->rec_per_page);
  934.      
  935.       $out = array();
  936.       foreach ($els as $el) {
  937.      
  938.          $out_row = array();
  939.          foreach ($el as $key=>$val) {
  940.              //-------------------------         
  941.              foreach ($this->fields as $fld) {
  942.          
  943.                 if ($fld['fn']==$key) {
  944.                    //-------------------------
  945.                    if (array_key_exists($key, $this->_listvars)) {
  946.              
  947.                       $outel = array();
  948.                      
  949.                
  950.                       if (isset($fld['fl'])) {
  951.                           $pos = array_search($val, $fld['fl']);
  952.                          
  953.                           if ($pos===false)
  954.                              $outel['value'] = $val;
  955.                           else
  956.                              $outel['value'] = $fld['fc'][$pos];
  957.                              
  958.                           $outel['caption'] = $fld['fs'];
  959.                          
  960.                       } else {
  961.                           $outel['value'] = $val;
  962.                           $outel['caption'] = $fld['fc'];
  963.                           }
  964.                        
  965.                       $out_row[$key] = $outel;
  966.                    }
  967.                  
  968.                    //-------------------------           
  969.                  break;
  970.                }
  971.            }
  972.            //-------------------------
  973.            if ($key==$this->_idfield) {
  974.            
  975.               $out_row['idfield']=$val;  
  976.              
  977.            }
  978.            //------------------------
  979.        }
  980.        $out[] = $out_row;
  981.     }
  982.     return $out;
  983.    }
  984.    
  985.     //--------------------------------   get all
  986.    
  987.    public function getAll() {
  988.    
  989.       return $this->_db_model->getNRecords($this, 0, 1000);
  990.    }
  991.    //--------------------------------   get number of pages
  992.    public function getNumPages() {
  993.      
  994.       $nrecs = $this->_db_model->getNumRecs($this);
  995.      
  996.       return (ceil($nrecs/$this->rec_per_page));
  997.    }  
  998.    //--------------------------------   insert item
  999.    public function insertItem() {
  1000.    
  1001.       $inf =  $this->prepareInfo();  
  1002.       if (is_string($inf))
  1003.           return $inf;
  1004.          
  1005.       return $this->_db_model->insertRecord($this, $inf );
  1006.    }
  1007.    //--------------------------------   update item
  1008.    public function updateItem($id, $vals=array()) {
  1009.    
  1010.       if (count($vals)>0)
  1011.          foreach ($vals as $key=>$val) {
  1012.             $inf[$key] = $val;
  1013.          
  1014.          } else
  1015.          $inf = $this->prepareInfo();
  1016.          
  1017.       if (is_string($inf))
  1018.           return $inf;
  1019.              
  1020.       return $this->_db_model->updateRecord($this, $id, $inf );
  1021.    }
  1022.    //--------------------------------   delete item
  1023.    public function deleteItem($id) {
  1024.    
  1025.       return $this->_db_model->deleteRecord($this, $id);
  1026.    }
  1027. }    
  1028.  
  1029. //----------------------------------------------
  1030. //           Form connected to model
  1031. //----------------------------------------------
  1032. class ModelForm extends stdForm {
  1033.  
  1034.   protected $_mandatory_fields;
  1035.   protected $_field_hints;
  1036.  
  1037.   public function __construct($injector) {
  1038.    
  1039.      
  1040.           parent::__construct( $injector);
  1041.          
  1042.           $fset = $this->addFieldset('');
  1043.          
  1044.           foreach ($this->_model->fields as $fld) {
  1045.              
  1046.              if (array_key_exists($fld['fn'], $this->_model->_postvars)) {
  1047.              
  1048.                 if (isset($fld['fh'])) {
  1049.                    $this->_field_hints[$fld['fn']] = $fld['fh'];
  1050.                 }
  1051.                 if (array_key_exists($fld['fn'], $this->_model->_mandatory)) {
  1052.                
  1053.                    $this->_mandatory_fields[$fld['fn']] = $this->_model->_mandatory[$fld['fn']];
  1054.                 }
  1055.                
  1056.                 if (isset($fld['fl'])) {
  1057.                    $fset->addField('SELECT',$fld['fn'],$fld['fl'],$fld['fc'], $fld['fs']);
  1058.                 } else
  1059.                      if ($fld['fc']=='hidden')
  1060.                         $this->addHidden($fld['fn'],'');
  1061.                      else
  1062.                         if ((isset($fld['fs'])) && ($fld['fs']=='textarea'))                   
  1063.                            $fset->addField('TEXTAREA', $fld['fn'],'', $fld['fc']);
  1064.                         else
  1065.                            $fset->addField('TEXT', $fld['fn'], '', $fld['fc']);
  1066.              }
  1067.           }
  1068.    }
  1069. }
  1070.  
  1071. //----------------------------------------------
  1072. //            Easy form draft
  1073. //----------------------------------------------
  1074. class EasyForm extends ModelForm {
  1075.    
  1076.    public function __construct($injector) {
  1077.    
  1078.         parent::__construct( $injector);
  1079.    
  1080.         $fn = create_function('$a,$key','echo "\'".$key."\' : \'".$a."\',";');
  1081.         $fn4 = create_function('$a,$key',
  1082.               ' if (isset($a["jcheck"])) echo "\'".$key."\' : {
  1083.                \'jfunc\' : \'".$a["jcheck"]["func"]."\',
  1084.                \'jmessage\' : \'".$a["jcheck"]["message"]."\'
  1085.               },";');
  1086.              
  1087.         ob_start();
  1088.        
  1089.         ?>
  1090.         <style type="text/css">
  1091.            .tooltip {
  1092.               position:absolute;
  1093.               padding:10px;
  1094.               border-radius: 5px;
  1095.               -moz-border-radius: 5px;
  1096.               -webkit-border-radius: 5px;
  1097.               -o-border-radius: 5px;
  1098.               font-size:12px;
  1099.               border: solid 1px #999;
  1100.               background: #fffff9;
  1101.            }
  1102.            
  1103.            .errorhint {
  1104.               text-align: center;
  1105.               color: red;
  1106.            }
  1107.         </style>
  1108.         <script type="text/javascript">
  1109.        
  1110.            var data_%id% = {
  1111.               'hints':{
  1112.            <?php
  1113.               array_walk($this->_field_hints, $fn);
  1114.            ?> 'inf': 4},
  1115.              'mandatory':{
  1116.            <?php
  1117.               array_walk($this->_mandatory_fields, $fn4);
  1118.            ?> 'inf': 4},
  1119.            }
  1120.            //-----------------------------
  1121.            var funcs_%id% = {
  1122.            
  1123.            //-----------------------------
  1124.            init : function () {
  1125.              
  1126.               var frm = jQuery('#%id%');
  1127.               frm.bind ('submit',
  1128.                  funcs_%id%.submit
  1129.               );
  1130.              
  1131.               var hints = data_%id%.hints;
  1132.               for (var key in hints) {
  1133.              
  1134.                   if (key=='inf')
  1135.                      continue;
  1136.                  
  1137.                   el = jQuery('input[name="'+key+
  1138.                   '"],select[name="'+key+'"],textarea[name="'+key+'"]',frm);
  1139.                  
  1140.                   el.each (function() {
  1141.                      jQuery(this).hover(funcs_%id%.hover_in(hints[key]),funcs_%id%.hover_out);
  1142.                      jQuery(this).bind('click',funcs_%id%.hover_out);
  1143.                      jQuery(this).bind('click',funcs_%id%.clear_errors);
  1144.                   })
  1145.               }
  1146.            },
  1147.            //-----------------------------
  1148.            clear_errors : function () {
  1149.            
  1150.               var frm = jQuery('#%id%');
  1151.               jQuery('.errorhint',frm).remove();
  1152.            },
  1153.            //-----------------------------
  1154.            submit : function() {
  1155.            
  1156.               funcs_%id%.clear_errors();
  1157.              
  1158.               var correct = true;
  1159.               var mandatory = data_%id%.mandatory;
  1160.              
  1161.               for (var key in mandatory) {
  1162.                  
  1163.                   if (key=='inf')
  1164.                      continue;
  1165.                      
  1166.                   var el = jQuery('input[name="'+key+
  1167.                   '"],select[name="'+key+'"],textarea[name="'+key+'"]',jQuery(this));
  1168.                  
  1169.                   var func = mandatory[key].jfunc;
  1170.                  
  1171.                   el.each ( function() {
  1172.                    
  1173.                   var zval = jQuery(this).val();
  1174.                   var fn4 ='('+func+')(\''+zval.replace(/'/g, "\\'")+'\')';
  1175.                   console.log(fn4);
  1176.                   var tezz = eval(fn4);
  1177.                
  1178.                   if (tezz==false) {
  1179.                    
  1180.                      jQuery(this).after(jQuery('<div/>',{'class':'errorhint'}).html(mandatory[key].jmessage));
  1181.                      correct = false;
  1182.                   }});
  1183.                  
  1184.               }
  1185.              
  1186.               return correct;
  1187.            },
  1188.            //-----------------------------
  1189.            hover_in: function(hint) {
  1190.            
  1191.               return function() {
  1192.                  funcs_%id%.show_hint(this, hint);
  1193.               }
  1194.            },  
  1195.            //-----------------------------
  1196.            hover_out: function() {
  1197.            
  1198.               if (this.tmin) {
  1199.                  clearTimeout(this.tmin);    
  1200.               }
  1201.            },
  1202.            //-----------------------------
  1203.            show_hint: function(el, hint) {
  1204.               if (!el.hintdiv) {
  1205.                  el.hintdiv = jQuery('<div/>',{'class':'tooltip'}).css('display','none').html(hint);
  1206.                  jQuery(document.body).append(el.hintdiv); 
  1207.                  el.hintdiv.css('top', jQuery(el).offset().top - 20);  
  1208.                  el.hintdiv.css('left', jQuery(el).offset().left + 400);                     
  1209.               }
  1210.               if (el.vis==true) {
  1211.                  return;
  1212.               }  
  1213.               el.tmin = setTimeout (function () {
  1214.              
  1215.                  el.vis = true;
  1216.                  el.hintdiv.fadeIn('slow');  
  1217.  
  1218.                  el.tmout = setTimeout( function() {
  1219.                     el.hintdiv.fadeOut('slow');
  1220.                     el.vis = false;
  1221.                  }, 3000);  
  1222.                  
  1223.                }, 1000);
  1224.                
  1225.            
  1226.            }
  1227.            //-----------------------------
  1228.            }
  1229.            //-----------------------------
  1230.            jQuery(document).ready (
  1231.               funcs_%id%.init
  1232.            )
  1233.         </script>
  1234.         <?php
  1235.        
  1236.         $base_action = ob_get_clean();
  1237.         $base_action = str_replace(array('%id%'),array($this->_id), $base_action);
  1238.        
  1239.         $this->scripts['base'] = array ('handler'=>'base', 'script'=>$base_action);
  1240.        
  1241.  
  1242.           $this->addButton('SUBMIT','submit', 'post');
  1243.           $this->addButton('BUTTON','cancel', 'cancel');
  1244.    }
  1245.    
  1246.    //------------------------------
  1247.    public function setCancelRoute($route) {
  1248.    
  1249.      
  1250.       $this->addHidden('cancelroute',$route);
  1251.      
  1252.    }
  1253.    
  1254. }
  1255.  
  1256. //-------------------------------------------------
  1257. //            Easy controller draft
  1258. //-------------------------------------------------
  1259. class EasyController extends Controller {
  1260.  
  1261.  
  1262.    protected $_routes = array (
  1263.                        
  1264.                                                 'add_form'     => 'action4=add_form',
  1265.                                                 'insert'       => 'action4=insert',
  1266.                                                 'edit_form'    => 'action4=edit_form&[dbkey]=%d',
  1267.                                                 'update'       => 'action4=update&[dbkey]=%d',
  1268.                                                 'delete_form'  => 'action4=delete_form&[dbkey]=%d',
  1269.                                                 'delete'       => 'action4=delete&[dbkey]=%d',
  1270.                                                 'view_single'  => 'action4=view_single&[dbkey]=%d',
  1271.                                                 'view_page'    => 'action4=view_page&pageid=%d');
  1272.                              
  1273.    //----------------------------------- declare params
  1274.    protected function declareParams() {
  1275.    
  1276.       parent::declareParams();
  1277.       $this->_params['pageid']='';
  1278.    }
  1279.    
  1280.    //----------------------------------- common dispatch
  1281.    protected function commonDispatch() {
  1282.    
  1283.           $this->set('nav_numpages', $this->_model->getNumPages());
  1284.          
  1285.           $this->set('nav_pageid', $this->p__pageid);
  1286.           $this->set('nav_id', $this->get($this->p__dbkey));
  1287.  
  1288.    }
  1289.    
  1290.    //--------------------------------------------
  1291.    protected function set_current_page() {
  1292.        
  1293.          $els = $this->_model->getPage($this->p__pageid);
  1294.          
  1295.          $this->set('items',$els);
  1296.    }
  1297.    //--------------------------------------------
  1298.    protected function set_single_page() {
  1299.    
  1300.       $el = $this->_model->getSingle($this->get($this->p__dbkey));   
  1301.       $this->set('item', $el);
  1302.    }
  1303.    
  1304.    //---------------------------------  draw single record  
  1305.    public function view_single() {
  1306.    
  1307.       $this->set_single_page();  
  1308.    }
  1309.    //--------------------------------  draw page
  1310.    public function view_page() {
  1311.    
  1312.       $this->set_current_page();
  1313.    }
  1314.  
  1315.    //--------------------------------  insert record
  1316.    public function insert() {
  1317.    
  1318.       $inf = $this->_model->insertItem();
  1319.      
  1320.       if (is_array($inf)) {
  1321.           $this->set('message', $inf['message']);
  1322.           $this->set('newrecord_id', $inf['rid']);
  1323.       } else
  1324.          $this->set('message', $inf);
  1325.          
  1326.       $this->set('nav_numpages', $this->_model->getNumPages());      
  1327.       $this->set_current_page();
  1328.    }
  1329.    //--------------------------------  draw edit form
  1330.    public function edit_form() {
  1331.    
  1332.       $this->set_single_page();      
  1333.    }
  1334.    //--------------------------------  update record
  1335.    public function update() {
  1336.    
  1337.       $this->set('message',$this->_model->updateItem($this->get($this->p__dbkey)));
  1338.          
  1339.           $this->set_current_page();
  1340.    }
  1341.    //--------------------------------  delete form
  1342.    public function delete_form() {
  1343.      
  1344.           $this->set('message', 'really delete record ?');//.$this->get($this->p__dbkey).' ?');
  1345.    }
  1346.    //--------------------------------  delete record
  1347.    public function delete() {
  1348.      
  1349.           $this->set('message',$this->_model->deleteItem($this->get($this->p__dbkey)));
  1350.           $this->set('nav_numpages', $this->_model->getNumPages());
  1351.          
  1352.           $this->set_current_page();
  1353.    }
  1354. }
  1355.  
  1356. //----------------------------------------------
  1357. //           Easy view draft
  1358. //----------------------------------------------
  1359.  
  1360. class EasyView extends View {
  1361.  
  1362.    //----------------------------   put content into blocks
  1363.    
  1364.    protected function renderBlocks() {
  1365.      
  1366.           $this->_blocks['header'] = $this->_decorator->getHeader();
  1367.           $this->_blocks['content'] = $this->_decorator->getContent();      
  1368.           $this->_blocks['footer'] =  $this->_decorator->getFooter();
  1369.    }
  1370.    
  1371.    //-------------------------------------------
  1372.    //                action handlers
  1373.    //-------------------------------------------
  1374.    
  1375.    //---------------------------   show single record
  1376.    public function view_single() {
  1377.        
  1378.           $this->_decorator->_drawSingle($this);    
  1379.           $this->_decorator->_drawEditPanel($this);
  1380.    }
  1381.    
  1382.     //---------------------------   show page      
  1383.     public function view_page() {
  1384.        
  1385.            $this->_decorator->_drawPageEditNav($this);
  1386.         }
  1387.  
  1388.    //----------------------------   show add form  
  1389.    public function add_form() {
  1390.    
  1391.       $this->_decorator->_drawForm(&$this, 'add');
  1392.    }
  1393.    //----------------------------   show insert record result
  1394.    
  1395.    public function insert() {
  1396.    
  1397.       /*$this->_decorator->setMessage( $this->v_message.
  1398.              '<br/><a href="'.$this->route_view_single($this->v_newrecord_id).'">view record</a>');*/
  1399.              
  1400.       $this->_decorator->setMessage( $this->v_message);          
  1401.       $this->_decorator->_drawPageEditNav($this);
  1402.    }
  1403.    
  1404.    //----------------------------   show edit form
  1405.    
  1406.    public function edit_form() {
  1407.          
  1408.       $this->_decorator->_drawForm(&$this, 'edit');
  1409.    }
  1410.    
  1411.    //----------------------------   show update record result
  1412.    public function update() {
  1413.    
  1414.       $this->_decorator->setMessage($this->v_message);        
  1415.       $this->_decorator->_drawPageEditNav($this);
  1416.    }
  1417.    
  1418.    //----------------------------   show delete form
  1419.    
  1420.    public function delete_form() {
  1421.    
  1422.       $this->_decorator->setMessage($this->v_message.'<br/>'.
  1423.              '<a href="'.$this->route_delete($this->v_nav_id).'">delete</a><br/>'.
  1424.                  '<a href="'.$this->route_view_page($this->v_nav_pageid).'">cancel</a>');
  1425.              
  1426.    }
  1427.    
  1428.    //----------------------------   show delete record result
  1429.    public function delete() {
  1430.    
  1431.       /*$this->_decorator->setMessage($this->v_message);*/
  1432.      
  1433.        $this->_decorator->_drawPageEditNav($this);
  1434.    }
  1435. }
  1436.  
  1437.  
  1438.  
  1439.  
  1440. ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement