Advertisement
terorama

fbn / fbbase.inc.php

Dec 22nd, 2012
67
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 14.36 KB | None | 0 0
  1. <?php
  2.  
  3.  
  4.  
  5. class Baser {
  6.  
  7.  
  8.    const DBNAME = 'fbdb8.dat';
  9.    
  10.    public static $db;
  11.    
  12.    private $sq;
  13.    private $user;
  14.    
  15.    public $debug_mode=false;
  16.    public $debug_array=array();
  17.    
  18.     //-----------------------------------------
  19.    private function declear() {
  20.       for ($i=0; $i<count($this->debug_array); $i++) {
  21.          unset($this->debug_array[$i]);
  22.       }
  23.    }
  24.    //-----------------------------------------
  25.    private function dewr($s)  {
  26.       if ($this->debug_mode)
  27.          $this->debug_array[]=$s;
  28.    }
  29.    //-----------------------------------------
  30.    public function deshow() {
  31.       $inf = '<pre>'.print_r($this->debug_array, true).'</pre>';
  32.       $this->declear();
  33.       return $inf;
  34.    }
  35.    //-----------------------------------------
  36.    public static function getInstance($user) {
  37.       if (!self::$db)
  38.          self::$db = new Baser($user);
  39.          
  40.       return self::$db;
  41.    }
  42.    
  43.    //-----------------------------------
  44.    private function __construct($user) {
  45.    
  46.       $this->user= ($user) ? $user : '0000000';
  47.       if (!$this->sq = new SQLiteDatabase(Baser::DBNAME)) {
  48.          throw new Exception('Error opening SQLite', 5006);
  49.          }
  50.          
  51.       $this->checkBase();
  52.        
  53.        
  54.    }
  55.    
  56.    //-----------------------------------
  57.    //   check if base tables exist
  58.    //-----------------------------------  
  59.    private function checkBase() {
  60.    
  61.       $rez = $this->sq->query('select * from fbs_likes_users');
  62.          
  63.       if (!$rez) {
  64.          $crtabs=array();
  65.          
  66.          $crtabs[]='CREATE TABLE fbs_likes_users ('.
  67.          'fb_base_user_id varchar(100),'.
  68.          'fb_like_id varchar(100),'.
  69.          'fb_reluser_id varchar(100))';
  70.          
  71.          $this->processSqls($crtabs);
  72.       }
  73.    }
  74.    
  75.    //------------------------------------------------------------------
  76.    //                            utils
  77.    //------------------------------------------------------------------
  78.    //-----------------------------------
  79.    //   retrieve table contents
  80.    //-----------------------------------
  81.    public function selectAll($table, $flds='', $curr_user=true) {
  82.    
  83.       $selflds='*';
  84.      
  85.       if ($flds!=='') {
  86.          if (is_array($flds)) {
  87.             $selflds=implode(',',$flds);
  88.          } else {
  89.             $selflds=$flds;
  90.          }
  91.       }
  92.       $ufilter = $curr_user ? ' where fb_base_user_id=\''.$this->user.'\'' : '';
  93.      
  94.       $rez = $this->sq->arrayQuery("select $selflds from $table".$ufilter, SQLITE_ASSOC);
  95.      
  96.       if (!$rez) {
  97.          $rez=array();
  98.          $rez['err'] = sqlite_error_string($this->sq->lastError());
  99.          }
  100.          
  101.       return $rez;
  102.    }
  103.    
  104.    //-----------------------------------
  105.    //          get Query
  106.    //-----------------------------------
  107.    public function getQuery($sql) {
  108.      
  109.       $rez = $this->sq->arrayQuery($sql, SQLITE_ASSOC);
  110.      
  111.       if (!$rez) {
  112.          $rez = array();
  113.          $rez['err'] = sqlite_error_string($this->sq->lastError());
  114.          }
  115.          
  116.       return $rez;
  117.    }
  118.    
  119.    //-----------------------------------
  120.    //          check Query
  121.    //-----------------------------------
  122.    public function checkQuery($sql) {
  123.    
  124.       $rez = $this->getQuery($sql);
  125.      
  126.       return is_array($rez) && !isset($rez['err']);
  127.    }
  128.    
  129.    //-----------------------------------
  130.    //      fetch field
  131.    //-----------------------------------
  132.    public function fetchField($table, $fld, $curr_user=true) {
  133.    
  134.       $inf = $this->selectAll($table, $fld, $curr_user);
  135.      
  136.       if (isset($inf['err'])) {
  137.          return $inf;
  138.       }
  139.      
  140.       $f = create_function('$val', 'return $val["'.$fld.'"];');
  141.       $inf4 = array_map($f,$inf);
  142.       return $inf4;
  143.    }
  144.    
  145.    //-----------------------------------
  146.    //      fetch query field
  147.    //-----------------------------------
  148.    public function fetchQueryField($sql, $fld) {
  149.    
  150.       $inf = $this->getQuery($sql);
  151.      
  152.       if (isset($inf['err'])) {
  153.          return $inf;
  154.       }
  155.      
  156.       $f = create_function('$val', 'return $val["'.$fld.'"];');
  157.       $inf4 = array_map($f,$inf);
  158.       return $inf4;
  159.    }
  160.    
  161.    
  162.    //-----------------------------------
  163.    //    get table fields
  164.    //-----------------------------------  
  165.    public function getTableFields($tabname) {
  166.      
  167.       $rez = $this->sq->query("select * from $tabname", SQLITE_ASSOC, $errstring);
  168.      
  169.       if (!$rez) {
  170.      
  171.          $s = array();
  172.          $s['err'] = 'error: '.$errstring."\r\n";
  173.          return $s;
  174.       }
  175.      
  176.       $flds = array();
  177.       for ($i=0; $i<$rez->numFields(); $i++) {
  178.      
  179.          $flds[] = $rez->fieldName($i);
  180.       }
  181.       return $flds;
  182.    }
  183.  
  184.    //-----------------------------------
  185.    //      execute query
  186.    //-----------------------------------
  187.    public function execQuery($sql) {
  188.    
  189.       $errstr = array();
  190.      
  191.       if (!$this->sq->queryExec($sql, $error)) {
  192.      
  193.          $errstr['inf'] = $error.':'.sqlite_error_string($this->sq->lastError())."\r\n".
  194.          str_repeat('=',30)."\r\n".$sql."\r\n";
  195.          
  196.          $errstr['err'] = 'error executing query';
  197.          }
  198.       else
  199.          $errstr['inf'] = "successfully executed\r\n".
  200.          "changes: ".$this->sq->changes()."\r\n".
  201.          "last insert id: ".$this->sq->lastInsertRowid()."\r\n".
  202.          str_repeat('=',30)."\r\n".$sql."\r\n";
  203.          
  204.          
  205.        return $errstr;
  206.          
  207.    }   
  208.  
  209.    //-----------------------------------
  210.    //   process sqls
  211.    //-----------------------------------
  212.    private function processSqls($sqls) {
  213.      
  214.         $errstr = array();
  215.         $errstr['inf']='';
  216.        
  217.         for ($i=0; $i<count($sqls); $i++) {
  218.           if (!$this->sq->queryExec($sqls[$i], $error)) {
  219.          
  220.              $errstr['inf'].=$error.':'.sqlite_error_string($this->sq->lastError())."\r\n".
  221.              str_repeat('=',30)."\r\n".
  222.              $sqls[$i]."\r\n";
  223.              
  224.              $errstr['err']='error executing query';
  225.              }
  226.           else
  227.              $errstr['inf'].="successfully executed, changes:\r\n ".$this->sq->changes()."\r\n".
  228.              'last insert id: '.$this->sq->lastInsertRowid()."\r\n".
  229.              str_repeat('=',30)."\r\n".
  230.              $sqls[$i]."\r\n";
  231.        }
  232.        
  233.        return $errstr;
  234.    }  
  235.    
  236.    //-----------------------------------
  237.    //   clear table
  238.    //-----------------------------------  
  239.    public function clearTable($tab) {
  240.    
  241.       $rez = $this->execQuery('delete from '.$tab);
  242.       return $rez['inf'];
  243.    }
  244.    
  245.    //-----------------------------------
  246.    //   drop table
  247.    //-----------------------------------  
  248.    public function dropTable($tab) {
  249.      
  250.       $rez = $this->execQuery('drop table '.$tab);
  251.       return $rez['inf'];
  252.    }
  253.    
  254.    
  255.    //-----------------------------------
  256.    //   draw table
  257.    //-----------------------------------
  258.    public function drawTab($tabname, $curr_user=true, $freeq=false) {
  259.    
  260.     $ufilter = $curr_user ? ' where fb_base_user_id=\''.$this->user.'\'' : '';
  261.     if (!$freeq)
  262.        $rez = $this->sq->query("select * from $tabname".$ufilter, SQLITE_BOTH, $errstring);
  263.     else
  264.        $rez = $this->sq->query($tabname, SQLITE_BOTH, $errstring); 
  265.        
  266.     if (!$rez) {
  267.        $s = "drawTab error: $errstring\r\n";
  268.        return $s;
  269.     }
  270.    
  271.     $tab =
  272.     "<table cellspacing=\"0\" cellpadding=\"3\" border=\"1\" bordercolor=\"#888\" >";
  273.      
  274.     $tab.='<tr>';
  275.       for ($i=0; $i<$rez->numFields(); $i++) {
  276.          $tab.='<td>'.$rez->fieldName($i).'</td>';
  277.       }
  278.       $tab.='</tr>';
  279.       while ($rez->valid()) {
  280.          $row = $rez->current();
  281.          $tab.='<tr>';
  282.          
  283.          for ($i=0; $i<$rez->numFields(); $i++) {
  284.             $tab.='<td>'.$row[$i].'</td>';
  285.          }
  286.          $tab.='</tr>';
  287.          $rez->next();
  288.       }
  289.       $tab.='</table>';
  290.      
  291.       return $tab;
  292.      
  293.    }
  294.    
  295.    //-----------------------------------
  296.    //   draw list
  297.    //-----------------------------------  
  298.    public function drawList($tabname, $curr_user=true) {
  299.    
  300.       $ufilter = $curr_user ? ' where fb_base_user_id=\''.$this->user.'\'' : '';
  301.    
  302.       $rez = $this->sq->query("select * from $tabname".$ufilter, SQLITE_BOTH, $errstring);
  303.       if (!$rez) {
  304.          $s = 'drawList error: '.$errstring."\r\n";
  305.          return $s;
  306.       }
  307.      
  308.       $inf="<h3>$tabname field list</h3><ul>";
  309.      
  310.       for ($i=0; $i<$rez->numFields(); $i++) {
  311.          $inf.=  '<li>'.$rez->fieldName($i).'</li>';
  312.       }
  313.       $inf.='</ul>';
  314.      
  315.       $inf.=str_repeat('-',30).'<br/>';
  316.      
  317.       while ($rez->valid()) {
  318.      
  319.          $row = $rez->current();
  320.          $inf.='<ul>';
  321.          for ($i=0; $i<$rez->numFields(); $i++) {
  322.             $inf.= '<li>'.$row[$i].'</li>';
  323.          }
  324.          $inf.='</ul>';
  325.          $inf.=str_repeat('-',30).'<br/>';
  326.          $rez->next();
  327.       }
  328.      
  329.       return $inf;
  330.      
  331.    }
  332.    
  333.    //-----------------------------------
  334.    //    show table info
  335.    //-----------------------------------
  336.    public function drawTableInfo($tabname) {
  337.    
  338.       $s = "table info:{$tabname}\r\n";
  339.      
  340.       $rez = $this->sq->query("select * from $tabname", SQLITE_BOTH, $errstring);
  341.       if (!$rez) {
  342.          $s.= "drawTableInfo error: $errstring\r\n";
  343.          return $s;
  344.          }
  345.      
  346.       $s.='number of fields: '.$rez->numFields()."\r\n";
  347.       $s.='number of rows: '.$rez->numRows()."\r\n";
  348.              
  349.       return $s;
  350.    }
  351.    
  352.    //------------------------------------------------------------------
  353.    //                      main operations
  354.    //------------------------------------------------------------------  
  355.    //-----------------------------------
  356.    //  fb record structure processing
  357.    //-----------------------------------
  358.    private function processFields($arr, $prefix, $fldtype=true, $keys=true) {
  359.        
  360.           $flds = array();
  361.    
  362.           foreach ($arr as $key=>$value) {
  363.        
  364.              //-------------multiple subentities
  365.              if (is_integer($key)) {
  366.                 /*if ($keys)
  367.                    $flds[] = $prefix.'_external '.($fldtype?'int':'')."\r\n";
  368.                 else
  369.                    $flds[] = '254'."\r\n";*/
  370.                 break;
  371.              }
  372.              $type = gettype($value);
  373.          
  374.              if (($type=='object') || ($type=='resource') || ($type=='NULL'))
  375.                 continue;
  376.            
  377.              if ($type=='array') {
  378.                 $flds = array_merge($flds, $this->processFields($value, $prefix.'_'.$key,
  379.                               $fldtype, $keys));
  380.                 continue;
  381.                 }
  382.                  
  383.              switch ($type) {
  384.                 case "boolean": $dbtype="boolean";break;
  385.                 case "integer": $dbtype="int";break;
  386.                 case "double": $dbtype="double";break;
  387.                 case "string": $dbtype="varchar(500)"; break;  
  388.              }
  389.              
  390.              if ($keys)
  391.                 $flds[]=$prefix.'_'.$key.' '.($fldtype ? $dbtype:'')."\r\n";
  392.              else
  393.                 $flds[]=(($type=='string')? '\'':'').
  394.                    ((($type=='string') || $value) ?
  395.                                    sqlite_escape_string($value) : '0').
  396.                                    
  397.                    (($type=='string')? '\'':'')."\r\n";
  398.           }
  399.          
  400.           return $flds;
  401.        }
  402.        
  403.  
  404.    //-----------------------------------
  405.    //   create fb structure table
  406.    //-----------------------------------
  407.    public function createTable($inf, $tabname, $checkifexists=false) {
  408.  
  409.        if (!is_array($inf)) {
  410.        
  411.           $z=array();
  412.           $z['err']='cannot create table. argument is empty or not array';
  413.           return $z;
  414.          }
  415.        
  416.        $flds=array();
  417.        
  418.        if ($checkifexists) {
  419.           $rez = $this->sq->query("select * from $tabname");
  420.           if ($rez) {
  421.              $z = array();
  422.              $z['inf']='table '.$tabname.' already exists';
  423.              return $z;
  424.              }
  425.        }
  426.        
  427.        if (array_key_exists('data', $inf)) {
  428.           if (isset($inf['data'][0])){
  429.          
  430.              
  431.              for ($i=0; $i<count($inf['data']);$i++) {
  432.                 $infz= $inf['data'][$i];
  433.                 $flds=array_merge($flds,
  434.                     $this->processFields($infz, 'fb'));
  435.              }
  436.              $flds = array_unique($flds);
  437.              
  438.              $inf=$inf['data'][0];
  439.              
  440.           } else {
  441.                    $z=array();
  442.                    $z['err']='fb query returns empty result';
  443.                    return $z;
  444.                
  445.              }
  446.        } else {
  447.              $flds = $this->processFields($inf, 'fb');
  448.        }
  449.                    
  450.        //---------------------------   
  451.        $dropstr = 'drop table '.$tabname;
  452.        
  453.        $tabstr = 'create table '.$tabname.'( fb_base_user_id varchar(100), '."\r\n".
  454.           implode(',',$flds).')';
  455.              
  456.        $this->execQuery($dropstr);         
  457.        $errstr = $this->execQuery($tabstr);
  458.  
  459.        return $errstr;
  460.        
  461.        
  462.    }
  463.    
  464.    //-----------------------------------
  465.    //     check if field exists
  466.    //-----------------------------------  
  467.     private function field_exists ($val) {
  468.      
  469.          $val = trim($val);
  470.          return in_array($val, $GLOBALS['gl_flds']);
  471.       }    
  472.    //-----------------------------------
  473.    //          fill fb table
  474.    //-----------------------------------
  475.  
  476.      
  477.    public function fillTable($inf, $tabname, $clear=true, $user='') {
  478.    
  479.       if (!is_array($inf)) {
  480.      
  481.          $z = array();
  482.          $z['err']='argument is empty or not array';
  483.          return $z;
  484.          }
  485.          
  486.       $rez = $this->sq->query("select * from $tabname");
  487.       if (!$rez) {
  488.          $crinf = $this->createTable($inf, $tabname);
  489.          
  490.          if (isset($crinf['err']))
  491.             return $crinf;
  492.          }
  493.    
  494.       //--------------------------------------------------
  495.       $gl_flds = $this->getTableFields($tabname);
  496.       if (isset($gl_flds['err']))
  497.          return $gl_flds;
  498.      
  499.       $GLOBALS['gl_flds'] = $gl_flds;
  500.        
  501.       //--------------------------------------------------
  502.       $sqls = array();
  503.      
  504.       if ($user=='me')
  505.          $user='';
  506.      
  507.       if ($user=='')
  508.          $user=$this->user;
  509.      
  510.       if ($clear)
  511.          $sqls[] = "delete from $tabname where fb_base_user_id='{$user}'";
  512.      
  513.       $zinf = array();
  514.      
  515.       //--------------------------- [node]->[data]->[0,1,2,3,4]
  516.       if (array_key_exists('data', $inf)) {
  517.      
  518.          for ($i=0; $i<count($inf['data']); $i++) {
  519.             $zinf[]= $inf['data'][$i];
  520.          }
  521.       } else {   
  522.          //------------------------[node]->[0,1,2,3,4]
  523.          if (isset($inf[0])) {
  524.          
  525.             for ($i=0; $i<count($inf); $i++) {
  526.                $zinf[]=$inf[$i];
  527.             }
  528.          }
  529.          else
  530.             $zinf[] = $inf;
  531.       }
  532.      
  533.       //---------------------------
  534.       for ($i=0; $i<count($zinf); $i++) {
  535.      
  536.           $f_flds = $this->processFields($zinf[$i],'fb', false);
  537.           $f_values = $this->processFields($zinf[$i],'fb', false, false);
  538.          
  539.           if ((!is_array($f_flds)) || (!is_array($f_values)))
  540.              continue;
  541.          
  542.           $f_check = array_combine($f_values, $f_flds );         
  543.           $f_check = array_flip( array_filter( $f_check, array($this,'field_exists')));
  544.      
  545.           $insstr = 'insert into '.$tabname.' (fb_base_user_id, '."\r\n".
  546.           implode(',', array_keys($f_check)).
  547.              ') values ( \''.$user.'\', '."\r\n".
  548.           implode(',', array_values($f_check)).')';
  549.          
  550.           $sqls[]= $insstr;
  551.          
  552.       }
  553.      
  554.       $errstr = $this->processSqls($sqls);
  555.      
  556.       return $errstr;
  557.  
  558.    }
  559.    
  560.    //-----------------------------------
  561.    
  562. }
  563.  
  564.  
  565.  
  566.  
  567.  
  568.  
  569.  
  570.  
  571.  
  572.  
  573. ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement