Advertisement
terorama

fb / fbbase.inc.php

Nov 5th, 2012
64
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 13.70 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.    //   draw table
  238.    //-----------------------------------
  239.    public function drawTab($tabname, $curr_user=true) {
  240.    
  241.     $ufilter = $curr_user ? ' where fb_base_user_id=\''.$this->user.'\'' : '';
  242.      
  243.     $rez = $this->sq->query("select * from $tabname".$ufilter, SQLITE_BOTH, $errstring);   
  244.     if (!$rez) {
  245.        $s = "drawTab error: $errstring\r\n";
  246.        return $s;
  247.     }
  248.    
  249.     $tab =
  250.     "<table cellspacing=\"0\" cellpadding=\"3\" border=\"1\" bordercolor=\"#888\" >";
  251.      
  252.     $tab.='<tr>';
  253.       for ($i=0; $i<$rez->numFields(); $i++) {
  254.          $tab.='<td>'.$rez->fieldName($i).'</td>';
  255.       }
  256.       $tab.='</tr>';
  257.       while ($rez->valid()) {
  258.          $row = $rez->current();
  259.          $tab.='<tr>';
  260.          
  261.          for ($i=0; $i<$rez->numFields(); $i++) {
  262.             $tab.='<td>'.$row[$i].'</td>';
  263.          }
  264.          $tab.='</tr>';
  265.          $rez->next();
  266.       }
  267.       $tab.='</table>';
  268.      
  269.       return $tab;
  270.      
  271.    }
  272.    
  273.    //-----------------------------------
  274.    //   draw list
  275.    //-----------------------------------  
  276.    public function drawList($tabname, $curr_user=true) {
  277.    
  278.       $ufilter = $curr_user ? ' where fb_base_user_id=\''.$this->user.'\'' : '';
  279.    
  280.       $rez = $this->sq->query("select * from $tabname".$ufilter, SQLITE_BOTH, $errstring);
  281.       if (!$rez) {
  282.          $s = 'drawList error: '.$errstring."\r\n";
  283.          return $s;
  284.       }
  285.      
  286.       $inf="<h3>$tabname field list</h3><ul>";
  287.      
  288.       for ($i=0; $i<$rez->numFields(); $i++) {
  289.          $inf.=  '<li>'.$rez->fieldName($i).'</li>';
  290.       }
  291.       $inf.='</ul>';
  292.      
  293.       $inf.=str_repeat('-',30).'<br/>';
  294.      
  295.       while ($rez->valid()) {
  296.      
  297.          $row = $rez->current();
  298.          $inf.='<ul>';
  299.          for ($i=0; $i<$rez->numFields(); $i++) {
  300.             $inf.= '<li>'.$row[$i].'</li>';
  301.          }
  302.          $inf.='</ul>';
  303.          $inf.=str_repeat('-',30).'<br/>';
  304.          $rez->next();
  305.       }
  306.      
  307.       return $inf;
  308.      
  309.    }
  310.    
  311.    //-----------------------------------
  312.    //    show table info
  313.    //-----------------------------------
  314.    public function drawTableInfo($tabname) {
  315.    
  316.       $s = "table info:{$tabname}\r\n";
  317.      
  318.       $rez = $this->sq->query("select * from $tabname", SQLITE_BOTH, $errstring);
  319.       if (!$rez) {
  320.          $s.= "drawTableInfo error: $errstring\r\n";
  321.          return $s;
  322.          }
  323.      
  324.       $s.='number of fields: '.$rez->numFields()."\r\n";
  325.       $s.='number of rows: '.$rez->numRows()."\r\n";
  326.              
  327.       return $s;
  328.    }
  329.    
  330.    //------------------------------------------------------------------
  331.    //                      main operations
  332.    //------------------------------------------------------------------  
  333.    //-----------------------------------
  334.    //  fb record structure processing
  335.    //-----------------------------------
  336.    private function processFields($arr, $prefix, $fldtype=true, $keys=true) {
  337.        
  338.           $flds = array();
  339.    
  340.           foreach ($arr as $key=>$value) {
  341.        
  342.              //-------------multiple subentities
  343.              if (is_integer($key)) {
  344.                 /*if ($keys)
  345.                    $flds[] = $prefix.'_external '.($fldtype?'int':'')."\r\n";
  346.                 else
  347.                    $flds[] = '254'."\r\n";*/
  348.                 break;
  349.              }
  350.              $type = gettype($value);
  351.          
  352.              if (($type=='object') || ($type=='resource') || ($type=='NULL'))
  353.                 continue;
  354.            
  355.              if ($type=='array') {
  356.                 $flds = array_merge($flds, $this->processFields($value, $prefix.'_'.$key,
  357.                               $fldtype, $keys));
  358.                 continue;
  359.                 }
  360.                  
  361.              switch ($type) {
  362.                 case "boolean": $dbtype="boolean";break;
  363.                 case "integer": $dbtype="int";break;
  364.                 case "double": $dbtype="double";break;
  365.                 case "string": $dbtype="varchar(500)"; break;  
  366.              }
  367.              
  368.              if ($keys)
  369.                 $flds[]=$prefix.'_'.$key.' '.($fldtype ? $dbtype:'')."\r\n";
  370.              else
  371.                 $flds[]=(($type=='string')? '\'':'').
  372.                    ((($type=='string') || $value) ?
  373.                                    sqlite_escape_string($value) : '0').
  374.                                    
  375.                    (($type=='string')? '\'':'')."\r\n";
  376.           }
  377.          
  378.           return $flds;
  379.        }
  380.        
  381.  
  382.    //-----------------------------------
  383.    //   create fb structure table
  384.    //-----------------------------------
  385.    public function createTable($inf, $tabname, $checkifexists=false) {
  386.  
  387.        if (!is_array($inf)) {
  388.        
  389.           $z=array();
  390.           $z['err']='cannot create table. argument is empty or not array';
  391.           return $z;
  392.          }
  393.        
  394.        $flds=array();
  395.        
  396.        if ($checkifexists) {
  397.           $rez = $this->sq->query("select * from $tabname");
  398.           if ($rez) {
  399.              $z = array();
  400.              $z['inf']='table '.$tabname.' already exists';
  401.              return $z;
  402.              }
  403.        }
  404.        
  405.        if (array_key_exists('data', $inf)) {
  406.           if (isset($inf['data'][0])){
  407.          
  408.              
  409.              for ($i=0; $i<count($inf['data']);$i++) {
  410.                 $infz= $inf['data'][$i];
  411.                 $flds=array_merge($flds,
  412.                     $this->processFields($infz, 'fb'));
  413.              }
  414.              $flds = array_unique($flds);
  415.              
  416.              $inf=$inf['data'][0];
  417.              
  418.           } else {
  419.                    $z=array();
  420.                    $z['err']='fb query returns empty result';
  421.                    return $z;
  422.                
  423.              }
  424.        } else {
  425.              $flds = $this->processFields($inf, 'fb');
  426.        }
  427.                    
  428.        //---------------------------   
  429.        $dropstr = 'drop table '.$tabname;
  430.        
  431.        $tabstr = 'create table '.$tabname.'( fb_base_user_id varchar(100), '."\r\n".
  432.           implode(',',$flds).')';
  433.              
  434.        $this->execQuery($dropstr);         
  435.        $errstr = $this->execQuery($tabstr);
  436.  
  437.        return $errstr;
  438.        
  439.        
  440.    }
  441.    
  442.    //-----------------------------------
  443.    //     check if field exists
  444.    //-----------------------------------  
  445.     private function field_exists ($val) {
  446.      
  447.          $val = trim($val);
  448.          return in_array($val, $GLOBALS['gl_flds']);
  449.       }    
  450.    //-----------------------------------
  451.    //          fill fb table
  452.    //-----------------------------------
  453.  
  454.      
  455.    public function fillTable($inf, $tabname, $clear=true) {
  456.    
  457.  
  458.       if (!is_array($inf)) {
  459.      
  460.          $z = array();
  461.          $z['err']='argument is empty or not array';
  462.          return $z;
  463.          }
  464.          
  465.          
  466.       $rez = $this->sq->query("select * from $tabname");
  467.       if (!$rez) {
  468.          $crinf = $this->createTable($inf, $tabname);
  469.          
  470.          if (isset($crinf['err']))
  471.             return $crinf;
  472.          }
  473.    
  474.       //--------------------------------------------------
  475.       $gl_flds = $this->getTableFields($tabname);
  476.       if (isset($gl_flds['err']))
  477.          return $gl_flds;
  478.      
  479.       $GLOBALS['gl_flds'] = $gl_flds;
  480.        
  481.       //--------------------------------------------------
  482.       $sqls = array();
  483.      
  484.       if ($clear)
  485.          $sqls[] = "delete from $tabname where fb_base_user_id='{$this->user}'";
  486.      
  487.       $zinf = array();
  488.      
  489.       //--------------------------- [node]->[data]->[0,1,2,3,4]
  490.       if (array_key_exists('data', $inf)) {
  491.      
  492.          for ($i=0; $i<count($inf['data']); $i++) {
  493.             $zinf[]= $inf['data'][$i];
  494.          }
  495.       } else {   
  496.          //------------------------[node]->[0,1,2,3,4]
  497.          if (isset($inf[0])) {
  498.          
  499.             for ($i=0; $i<count($inf); $i++) {
  500.                $zinf[]=$inf[$i];
  501.             }
  502.          }
  503.          else
  504.             $zinf[] = $inf;
  505.       }
  506.      
  507.       //---------------------------
  508.       for ($i=0; $i<count($zinf); $i++) {
  509.      
  510.           $f_flds = $this->processFields($zinf[$i],'fb', false);
  511.           $f_values = $this->processFields($zinf[$i],'fb', false, false);
  512.          
  513.           if ((!is_array($f_flds)) || (!is_array($f_values)))
  514.              continue;
  515.          
  516.           $f_check = array_combine($f_values, $f_flds );         
  517.           $f_check = array_flip( array_filter( $f_check, array($this,'field_exists')));
  518.      
  519.           $insstr = 'insert into '.$tabname.' (fb_base_user_id, '."\r\n".
  520.           implode(',', array_keys($f_check)).
  521.              ') values ( \''.$this->user.'\', '."\r\n".
  522.           implode(',', array_values($f_check)).')';
  523.          
  524.           $sqls[]= $insstr;
  525.          
  526.       }
  527.      
  528.       $errstr = $this->processSqls($sqls);
  529.      
  530.       return $errstr;
  531.  
  532.    }
  533.    
  534.    //-----------------------------------
  535.    
  536. }
  537.  
  538.  
  539.  
  540.  
  541.  
  542.  
  543.  
  544.  
  545.  
  546.  
  547. ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement