From bc64a05d4cac748aa480877d302283ff86317cd9 Mon Sep 17 00:00:00 2001 From: Nicolas Boisselier Date: Sun, 6 Mar 2016 04:43:24 +0000 Subject: [PATCH] move slowly out from rent --- bin/dbq | 8 +- etc/dbs.yaml | 98 ++++++++++++++++++++++ etc/profile | 38 +++++---- etc/profile.d/aliases | 1 + etc/profile.d/envs | 16 +++- etc/profile.d/functions | 18 +--- etc/profile.d/history.sh | 7 ++ etc/vim/source/option.vim | 10 ++- etc/vim/templates/perl.tt | 2 +- etc/vim/templates/phpf.tt | 11 +++ etc/vim/vim-shortcurts | 2 +- etc/vim/vimplaterc | 19 +++-- lib/js/nb.js | 24 ++++++ lib/perl/NB.pm | 14 +++- lib/php/config.php | 21 +++++ lib/php/db.php | 172 +++++++++++++++++++++++++++++++++----- lib/php/db/index.php | 15 ++++ lib/php/db/table.php | 16 ++-- lib/php/functions.php | 19 +++-- lib/php/nb.php | 166 +++++++++++++++++++++++++++++++----- lib/php/page.php | 76 +++++++++++++++-- 21 files changed, 642 insertions(+), 111 deletions(-) create mode 100644 etc/dbs.yaml create mode 100644 etc/profile.d/history.sh mode change 100644 => 100755 etc/vim/templates/perl.tt create mode 100644 etc/vim/templates/phpf.tt create mode 100644 lib/php/config.php create mode 100755 lib/php/db/index.php diff --git a/bin/dbq b/bin/dbq index 944fb99c..ad1f3385 100755 --- a/bin/dbq +++ b/bin/dbq @@ -4,6 +4,7 @@ use warnings; use Encode; use URI::Escape; use NB::Functions qw/html2txt/; +use NB qw/$ROOT_DIR/; ################################################################################# # # VERSION @@ -32,6 +33,7 @@ my %CMD_ALIASE = ( 'f' => 'format', 'l' => 'limit', 'a' => 'action', + 'h' => 'header', ); ## Vim: r!% --curl_help_hash | grep X @@ -76,7 +78,9 @@ get_options(\%Opt,\@CURL_OPT); # # Get URL # -my $url = ($ENV{$UC_NAME.'_URL'} ? $ENV{$UC_NAME.'_URL'} : '/opt/rent/www/index.php'); +my $url = ($ENV{$UC_NAME.'_URL'} ? $ENV{$UC_NAME.'_URL'} : + ( -e $ROOT_DIR.'/lib/php/db/index.php' ? $ROOT_DIR.'/lib/php/db/index.php' : '/opt/rent/www/index.php' ) +); if (!$Opt{ssh} and @ARGV and ($ARGV[0] =~ m|^\w+://| or -e $ARGV[0] )) { $url = shift @ARGV; @EXEC = grep {$_ ne $url} @EXEC; @@ -273,7 +277,7 @@ sub csv2txt { print $sep_line if !$noheader and !$i++; } - print $sep_line; + print $sep_line if $tot; print "$tot Records\n"; #close STDOUT; close STDERR; #close STDIN; diff --git a/etc/dbs.yaml b/etc/dbs.yaml new file mode 100644 index 00000000..c658a5b2 --- /dev/null +++ b/etc/dbs.yaml @@ -0,0 +1,98 @@ +crypt: + pdo: 'sqlite:/dev/shm/crypt.db' + +puppetdb: + pdo: 'pgsql:host=big;dbname=puppetdb;user=puppetdb;password=' + title: Puppetdb + default_table: view_hosts + tables: + hosts: + extras: + last_compile: + type: text + extra: to_char(hosts.last_compile, 'YYYY-MM-DD HH:mm:ss'::text) + last_freshcheck: + type: text + extra: to_char(hosts.last_freshcheck, 'YYYY-MM-DD HH:mm:ss'::text) + updated_at: + type: text + extra: to_char(hosts.updated_at, 'YYYY-MM-DD HH:mm:ss'::text) + created_at: + type: text + extra: to_char(hosts.created_at, 'YYYY-MM-DD HH:mm:ss'::text) + test: + type: "int" + extra: 1 +izi: + pdo: 'mysql:host=admin.izideal.com;port=3306;dbname=izi' + username: izideal + title: Mysql Izi on Admin + options: + - "PDO::MYSQL_ATTR_INIT_COMMAND: SET NAMES utf8'" + default_table: process + +izidev: + pdo: 'mysql:host=big.cascais.loc;port=3306;dbname=izi' + username: nico + title: Mysql Izi on Big + options: + - "PDO::MYSQL_ATTR_INIT_COMMAND: SET NAMES utf8'" + default_table: process + +ui: + pdo: 'sqlite:/opt/semantico/product/releases/sem_ui/db/semantico.db' + title: 'Semantico UI' + #default_table: view_puppet_error + +rt: + pdo: 'pgsql:host=db.rt.semantico.net;port=5432;dbname=rtdb;user=rtuser;password=' + title: 'RT' + +rent: + order: 1 + pdo: 'sqlite:/opt/rent/rent.db' + title: 'Rent' + notice: 'Micro foncier 4BE' + default_table: 'rent' + map: + "SELECT addr FROM addr WHERE id='@id'": ".rows.place td.id, .rows.rent td.idplace" + "SELECT name FROM tenant WHERE id='@id'": ".rows.rent td.idtenant" + +# NEW- NB 10.01.16 + tables: + + template: + View: "''||id||''" + + place: + replace: + id: addr.addr + + rent: + order_by: "start desc" + replace: + idtenant: tenant.name + idplace: addr.addr + extras: + total: + type: "float(8,2)" + extra: "ROUND(rent+charge,2)" + rent_year: + type: "float(8,2)" + extra: "rent * (1 + ( strftime('%m',end)+12*strftime('%Y',end) ) - ( strftime('%m',start)+12*strftime('%Y',start) ))" + #revision: (SELECT GROUP_CONCAT(''||substr(id,0,instr(id,'.'))||'',' ') FROM template) + +# TODEL - NB 10.01.16 +# NB 10.01.16 sort: +# NB 10.01.16 rent: start desc +# NB 10.01.16 extras: +# NB 10.01.16 rent: +# NB 10.01.16 total: +# NB 10.01.16 type: "float(8,2)" +# NB 10.01.16 extra: "ROUND(rent+charge,2)" +# NB 10.01.16 rent_year: +# NB 10.01.16 type: "float(8,2)" +# NB 10.01.16 extra: "rent * (1 + ( strftime('%m',end)+12*strftime('%Y',end) ) - ( strftime('%m',start)+12*strftime('%Y',start) ))" +# NB 10.01.16 #revision: (SELECT GROUP_CONCAT(''||substr(id,0,instr(id,'.'))||'',' ') FROM template) +# NB 10.01.16 template: +# NB 10.01.16 View: "''||id||''" diff --git a/etc/profile b/etc/profile index 5ab1e06e..6c04a36f 100644 --- a/etc/profile +++ b/etc/profile @@ -1,32 +1,42 @@ +# +# Avoid infinit loop. Eg: profile -> .bashrc -> profile +# +[ -n "$NB_LOOP" ] && return; export NB_LOOP=1 +[ "$1" = "--debug" ] && NB_DEBUG='eval echo 1>&2 "$(basename $BASH_SOURCE): "' && shift + # # ROOT PATH # +dir='.' case "$BASH_SOURCE" in */*) dir="${BASH_SOURCE%/*}";; *) - case "$ZSH_NAME" in - *zsh) - dir=${(%):-%N} - dir=${dir%/*} - ;; - *) dir='.' ;; - esac + if [ -n "$ZSH_NAME" ]; then + dir=${(%):-%N} + dir=${dir%/*} + fi ;; esac - [ -e "$dir/profile.d/functions" ] && source "$dir/profile.d/functions" NB_ROOT=$(realpath ${dir}/.. 2>/dev/null) -unset dir i +unset dir -if [ -z "$NB_ROOT" ]; then - unset NB_ROOT +# +# Profiles +# +if [ -n "$NB_ROOT" ]; then -else - for i in ${NB_ROOT}/etc/profile.d/envs ${NB_ROOT}/etc/profile.d/aliases $NB_ROOT/etc/profile.d/*.sh; do + for i in \ + ${NB_ROOT}/etc/profile.d/envs \ + ${NB_ROOT}/etc/profile.d/aliases \ + ${NB_ROOT}/etc/profile.d/*.sh \ + ${HOME}/.${SHELL_NAME}rc \ + ;do + [ -n "$NB_DEBUG" ] && $NB_DEBUG "$i" [ -r "$i" ] && source "$i" done - unset i tmp fi +unset i tmp NB_LOOP NB_DEBUG true diff --git a/etc/profile.d/aliases b/etc/profile.d/aliases index 734514a7..77f5856d 100644 --- a/etc/profile.d/aliases +++ b/etc/profile.d/aliases @@ -3,6 +3,7 @@ # Aliases # ################################################################################# +[ -n "$MYVIMRC" ] && shopt -s expand_aliases #-------------------------------------------------------------------------------- # Others diff --git a/etc/profile.d/envs b/etc/profile.d/envs index 5dd0926c..e09048f0 100644 --- a/etc/profile.d/envs +++ b/etc/profile.d/envs @@ -40,9 +40,20 @@ export PATH export IGNOREEOF=0 export LESS="-iMR" +export PAGER="less -iMRE" export EDITOR=vim case "$OSTYPE" in darwin*) export DARWIN=1;; esac +# +# SHELL +# +case "$BASH" in + */sh) SHELL_NAME=sh ;; + */bash) SHELL_NAME=bash ;; + *) [ -n "$ZSH_NAME" ] && SHELL_NAME=zsh ;; +esac +export SHELL_NAME + # # Color # @@ -57,9 +68,8 @@ esac # PS1 # -case "$SHELL" in - */zsh) ;; - *) +case "$SHELL_NAME" in + bash) h='\h' color='' diff --git a/etc/profile.d/functions b/etc/profile.d/functions index 0cd13f1e..2b9687d7 100644 --- a/etc/profile.d/functions +++ b/etc/profile.d/functions @@ -101,7 +101,7 @@ env_add_path() { } realpath() { - perl -MFile::Spec -MCwd -e 'print File::Spec->rel2abs( Cwd::abs_path($ARGV[0]) )."\n"' $1 + perl -MFile::Spec -MCwd -e 'print File::Spec->rel2abs( Cwd::abs_path($ARGV[0]) )."\n" if -e $ARGV[0]' $1 } ascii() { @@ -159,22 +159,6 @@ yaml2perl() { perl -MYAML -MData::Dumper -e 'print Dumper YAML::Load(join("",<>))' $@ } -################################################################################# -# -# CHECK SHELL -# -################################################################################# -# NB 08.07.15 case "$BASH" in -# NB 08.07.15 */bash) ;; -# NB 08.07.15 *) -# NB 08.07.15 case "$SHELL" in -# NB 08.07.15 */bash) ;; -# NB 08.07.15 */zsh) ;; -# NB 08.07.15 *) return 0 ;; -# NB 08.07.15 esac -# NB 08.07.15 ;; -# NB 08.07.15 esac - ################################################################################# # # FUNCTIONS - BASH diff --git a/etc/profile.d/history.sh b/etc/profile.d/history.sh new file mode 100644 index 00000000..582fc3a0 --- /dev/null +++ b/etc/profile.d/history.sh @@ -0,0 +1,7 @@ +case "$BASH" in */sh) shopt -s histappend ;; esac +export HISTTIMEFORMAT="%F %T " +# Max lines in ~/.*_history +export HISTFILESIZE=10000 +# Line to write when session end +export HISTSIZE=$HISTFILESIZE +export HISTCONTROL=ignoredups:ignoreboth diff --git a/etc/vim/source/option.vim b/etc/vim/source/option.vim index 866b66e3..8bd930f6 100644 --- a/etc/vim/source/option.vim +++ b/etc/vim/source/option.vim @@ -29,11 +29,17 @@ set history=1000 """""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" " Sell +" See: http://stackoverflow.com/questions/8420354/vim-run-commands-in-my-bashrc " set shellpipe= " set shellcmdflag=-ic -" set shellcmdflag=-ic -" set shell=/bin/bash\ -i +" NB 05.03.16 if !has("compatible") +" NB 05.03.16 set shellcmdflag= +" NB 05.03.16 set shell=/bin/bash\ -c +" NB 05.03.16 "set shellcmdflag=-c +" NB 05.03.16 "set shell=/bin/bash\ --rcfile\ ~/.bash_profile +" NB 05.03.16 endif let $BASH_ENV = "~/.bashrc" +" if [ -n "$BASH_ENV" ]; then . "$BASH_ENV"; fi """""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" " set nocompatible diff --git a/etc/vim/templates/perl.tt b/etc/vim/templates/perl.tt old mode 100644 new mode 100755 index c6a3999e..08536385 --- a/etc/vim/templates/perl.tt +++ b/etc/vim/templates/perl.tt @@ -8,7 +8,7 @@ use warnings; ################################################################################# my $VERSION = '0.0.1'; # [% user.me_now %] -# - create script +# - create script: [% var.basename %] ################################################################################# # diff --git a/etc/vim/templates/phpf.tt b/etc/vim/templates/phpf.tt new file mode 100644 index 00000000..516abb81 --- /dev/null +++ b/etc/vim/templates/phpf.tt @@ -0,0 +1,11 @@ + /** + * @copyright [% user.copyright %] + * @author [% user.author %] + * Does what the name says + * + * @param datatype1|datatype2 \$paramname description + * @return datatype1|datatype2 description + */ + function foo() { + } + diff --git a/etc/vim/vim-shortcurts b/etc/vim/vim-shortcurts index 2aa1b2f5..d8593bd7 100755 --- a/etc/vim/vim-shortcurts +++ b/etc/vim/vim-shortcurts @@ -498,7 +498,7 @@ function php_function_new { cat << EOF /** * @copyright $ME $NOW -* Php Function Template +* Does what it says * * @param datatype1|datatype2 \$paramname description * @return datatype1|datatype2 description diff --git a/etc/vim/vimplaterc b/etc/vim/vimplaterc index 7a6106e7..a11e53ec 100755 --- a/etc/vim/vimplaterc +++ b/etc/vim/vimplaterc @@ -5,25 +5,34 @@ # -user= -dir= #warn @ARGV; use POSIX; +use File::Basename; sub filename { my $f = $ENV{VIMFILE}; - return join(' ',@ARGV) if @ARGV and !$f; + $f = join(' ',@ARGV) if @ARGV and !$f; + #return join(' ',@ARGV) if @ARGV and !$f; return $f unless $f; - my $root = $ENV{IZI_ROOT_DIR}; - return $f unless $root; - $f =~ s,^$root,\~izideal,; + my $root; + + $f =~ s,^$root,\~izideal, if $root = $ENV{IZI_ROOT_DIR}; + $f =~ s,^$root/?,, if $root = $ENV{NB_ROOT}; + + $f =~ s,^$root/,, if $root = $ENV{HOME}; + return $f; } +$file = filename(); + $Config::var = { #yourArray => [ 'Perl', 'C', 'C++' ], time => sub{ time }, programname => 'nico', today => POSIX::strftime("%d.%m.%y", localtime), year => POSIX::strftime("%Y", localtime), - filename => filename(), + filename => $file, + basename => basename($file), }; $Config::opt = { diff --git a/lib/js/nb.js b/lib/js/nb.js index 2c42bd14..587490b6 100644 --- a/lib/js/nb.js +++ b/lib/js/nb.js @@ -273,6 +273,30 @@ function NB() { }); } + this.dump = function (arr,level) { + var dumped_text = ""; + if(!level) level = 0; + + //The padding given at the beginning of the line. + var level_padding = ""; + for(var j=0;j \"" + value + "\"\n"; + } + } + } else { //Stings/Chars/Numbers etc. + dumped_text = "===>"+arr+"<===("+typeof(arr)+")"; + } + return dumped_text; + } }; //NB.prototype.your_method = function() { } diff --git a/lib/perl/NB.pm b/lib/perl/NB.pm index 3826bf92..b7457087 100644 --- a/lib/perl/NB.pm +++ b/lib/perl/NB.pm @@ -1,7 +1,20 @@ package NB; use strict; use warnings; + use NB::Functions qw/:all/; + +use File::Spec; +use File::Basename; +use Cwd; +#print File::Spec->rel2abs( Cwd::abs_path($ARGV[0]) + +our @EXPORT_OK; + +our $ROOT_DIR = File::Spec->rel2abs( Cwd::abs_path( + File::Spec->catfile(dirname(__FILE__),('..')x2) +)); push(@EXPORT_OK,'$ROOT_DIR'); + BEGIN { use Exporter(); our ($VERSION, @ISA, @EXPORT, @EXPORT_OK, %EXPORT_TAGS); @@ -16,6 +29,5 @@ BEGIN { # your exported package globals go here, # as well as any optionally exported functions } -our @EXPORT_OK; 1; # don't forget to return a true value from the file diff --git a/lib/php/config.php b/lib/php/config.php new file mode 100644 index 00000000..c385af96 --- /dev/null +++ b/lib/php/config.php @@ -0,0 +1,21 @@ + diff --git a/lib/php/db.php b/lib/php/db.php index a30f7b92..a9c34a21 100644 --- a/lib/php/db.php +++ b/lib/php/db.php @@ -22,7 +22,7 @@ if (!defined('DB_HTML_FORM_BUTTONS')) define('DB_HTML_FORM_BUTTONS','' #if (!defined('DB_HTML_BUTTON_ADD')) define('DB_HTML_BUTTON_ADD','Add'); #if (!defined('DB_HTML_BUTTON_ADD')) define('DB_HTML_BUTTON_ADD',''); -class db extends nb { +class Db extends nb { # PDO Connection public $conn; @@ -55,41 +55,65 @@ class db extends nb { ' combine criterias with OR/AND', ); - function __construct($db) { + function __construct($db = '') { # Args $db = is_scalar($db) ? array('name' => $db) : $db; if (is_array($db)) { + +# NB 05.03.16 if (!empty($db->configs)) { +# NB 05.03.16 $this->dbs = $this->config2h($db->dbs); +# NB 05.03.16 unset($db->dbs); +# NB 05.03.16 } + foreach ($db as $k=>$v) $this->$k = $v; } # Pdo - if ($this->pdo) { - $this->type = strtolower(preg_replace('/^([^:]+):.*$/','\1',$this->pdo)); - if (!in_array($this->type,array( - 'sqlite', - 'mysql', - 'pgsql', - ))) $this->bye("unknow type = ".$this->type); - #preg_match_all('/[:;](user|username|password)=([^;]*)/',$this->pdo,$m); bye($m); - if (preg_match('/^sqlite:(.*)$/',$this->pdo,$m) and !is_readable($m[1])) - $this->bye("Can't access database ".$m[1]); - ; - $this->conn = new PDO($this->pdo,$this->username,$this->password,$this->options); - if (isset($this->pdo_error)) $this->conn->setAttribute(PDO::ATTR_ERRMODE, $this->pdo_error); - } + return $this->connect(); + + } + + function connect($pdo=null) { + + if ($pdo !== null) $this->pdo = $pdo; # Name #if (empty($this->name)) $this->name = preg_replace('/^(?:(?:sqlite:.*(.*?)(\.\w+)?)|(?:.*?dbname=([^;]+).*?))$/','\1',$this->pdo); # NB 22.12.15 if (empty($this->name) and preg_match('/(?:sqlite:|dbname=)([^;\.]+)/',$this->pdo,$m)) { - if (empty($this->name) and preg_match('/(?:sqlite:(?:.*\/)?|dbname=)([^;\.]+)/',$this->pdo,$m)) { + if (empty($this->name) and !empty($this->pdo) + and preg_match('/(?:sqlite:(?:.*\/)?|dbname=)([^;\.]+)/',$this->pdo,$m) + ) { $this->name = $m[1]; } # Title if (empty($this->title)) $this->title = prettyText($this->name); + if (empty($this->pdo)) return false; + + # Type + $this->type = strtolower(preg_replace('/^([^:]+):.*$/','\1',$this->pdo)); + if (!in_array($this->type,array( + 'sqlite', + 'mysql', + 'pgsql', + ))) $this->bye("unknow type = `".$this->type."`"); - # Types + # User + #preg_match_all('/[:;](user|username|password)=([^;]*)/',$this->pdo,$m); bye($m); + + # Connect + if (preg_match('/^sqlite:(.*)$/',$this->pdo,$m) and !is_readable($m[1])) { + $this->bye("Can't connect to database `".$m[1]."` type=$this->type",false); + + } else { + $this->conn = new PDO($this->pdo,$this->username,$this->password,$this->options); + if (isset($this->pdo_error)) $this->conn->setAttribute(PDO::ATTR_ERRMODE, $this->pdo_error); + } + + if (empty($this->conn)) return false; + + # Create functions if ($this->type == 'sqlite') { $this->conn->sqliteCreateFunction('ip2int', function ($value) { return ip2long($value); }); @@ -119,6 +143,7 @@ class db extends nb { } + return empty($this->conn) ? false : true; } /* @@ -411,8 +436,8 @@ EOF; } function action($table) { - ini_set('html_errors', false); - if ($this->p('format') == 'table') $this->pset('format',''); + #if ($this->p('format') == 'table') $this->pset('format',''); + $this->pdef('format',($this->php_cli() ? 'csv' : '')); $action = $this->p('action'); if ($action == 'tables') { @@ -434,6 +459,111 @@ EOF; return false; } -} + /** + * @copyright NB 05.03.16 + */ + static function conf ($default,$files=array()) { + } + + /** + * @copyright NB 05.03.16 + * @param [FILES] $files Files to load + * @return ARRAY the new/existing value of $this->db + */ + static function config2h ($files=array(),&$first=false) { + if (empty($files)) return array(); + + if (!empty($files)) { + + if (empty($h)) $h = array(); + + foreach ($files as $file) { + if (is_readable($file) and ($yaml = @yaml_parse_file($file))) { + #foreach ($yaml as $k=>$v) { $yaml[$k]['_config2h'] = $file; } + $h = array_replace_recursive($h,$yaml); + } + #debug($file); + #if ( ($yaml = @yaml_parse_file($file)) ) $h = array_replace_recursive($h,$yaml) + ; + unset($yaml); + #} + } + + #debug($h); + } + if (!$h) return false; + #if ($first !== false) debug ( self::ar_first($h) ); + if ($first !== false) $first = self::ar_first($h); + return $h; + } + + function Z__destruct() { + echo "__destruct\n"; + } + + public static function init($conf) { + global $Db, $Table; + if (isset($Table)) self::bye("Table.init(): GLOBALS['Table'] already exists !"); + if (isset($Db)) self::bye("Db.init(): GLOBALS['Db'] already exists !"); + + $Db = new self(); + #bye($_SERVER["PHP_SELF"]); bye($_SERVER); + if (!array_key_exists(nb::$root_dir.'/etc/dbs.yaml',$conf)) $conf[] = nb::$root_dir.'/etc/dbs.yaml'; + if (!array_key_exists('/etc/rent/db.yaml',$conf)) $conf[] = '/etc/rent/db.yaml'; + if (!array_key_exists('/etc/dbs.yaml',$conf)) $conf[] = '/etc/dbs.yaml'; + + # Load databases + if (! ($dbs = $Db->config2h($conf)) ) return false; +# NB 05.03.16 $ar = array('a'); +# NB 05.03.16 #$ar[] = 'b'; +# NB 05.03.16 array_unshift($ar,'b'); +# NB 05.03.16 bye($ar); +# NB 05.03.16 bye($dbs['puppetdb']); + + # Param - Extract dbname from table + if (preg_match('/^(\w+)\.(.*?)$/',$Db->p('table'),$m)) { + $Db->pset('db',$m[1]); + $Db->pset('table',$m[2]); + } + #die (nb::p('db')); + + # Param - Default base on order hight num value + if (!$Db->p('db')) { + $Db->hksort($dbs,'order'); + $Db->pset('db',$Db->ar_first($dbs,true)); + } + + # Param - correction / aliases + if (($format=$Db->p('format'))) { + } + + # Connection + #bye($Db->p('db')); + if (!isset($dbs[$Db->p('db')])) $Db->bye("Can't find db: `".$Db->p('db')."` in `".join(",",array_keys($dbs))."`",false); + $db = array_merge($dbs[$Db->p('db')],array('dbs'=>array_keys($dbs))); + + if (empty($db['pdo'])) $Db->bye("No pdo for db: `".$Db->p('db')."`",false); + + #bye($db['pdo']); + $Db->__construct($db); + unset($dbs); + + + /* + Table + */ + if (empty($Db)) return false; + if (!$Db->p('table') and isset($Db->default_table)) $Db->pset('table',$Db->default_table); + if (!$Db->p('table') and ($v = $Db->tables())) $Db->pset('table',$Db->ar_first($v)); + if (!$Db->p('table')) return; + + # NB 10.01.16 $Table = new table($Db->p('table'),array('db' => $Db)); + $Table = $Db->table($Db->p('table')); + + return true; + + } + +} # < Class ?> diff --git a/lib/php/db/index.php b/lib/php/db/index.php new file mode 100755 index 00000000..73934b4d --- /dev/null +++ b/lib/php/db/index.php @@ -0,0 +1,15 @@ +#!/usr/bin/env php +action($Table); +?> diff --git a/lib/php/db/table.php b/lib/php/db/table.php index aedb37bc..e6ef0bf2 100644 --- a/lib/php/db/table.php +++ b/lib/php/db/table.php @@ -637,7 +637,7 @@ FROM pg_catalog.pg_attribute a WHERE a.attrelid = (SELECT c.oid FROM pg_catalog. // Tot // if (true and !$where and !$limit) { - debug("Not using count(*)"); + debug("Table.rows(): Not using count(*)"); $query = $this->db->conn->query("SELECT $count"); } elseif ($select_count) { @@ -850,27 +850,27 @@ FROM pg_catalog.pg_attribute a WHERE a.attrelid = (SELECT c.oid FROM pg_catalog. Html Div -----------------------------------------------------------------*/ function rows_begin_div() { - return '
'; + return '
'.PHP_EOL; } function rows_rec_div(&$row) { $html = ''; - $html .= '
    '; + $html .= '
      '.PHP_EOL; if ($this->p('buttons')!=='0') { - $html .= '
    • '; - $html .= ''.DB_HTML_EDIT.''; - $html .= ''.DB_HTML_DELETE.''; - $html .= '
    • '; + $html .= '
    • '.PHP_EOL; + $html .= ''.DB_HTML_EDIT.''.PHP_EOL; + $html .= ''.DB_HTML_DELETE.''.PHP_EOL; + $html .= '
    • '.PHP_EOL; } foreach ($row as $k => $v) { $html .= '
    • ' .( $k == '0' ? '' : '') .''.$v.'' - .'
    • '; + .''.PHP_EOL; } $html .= '
    '.PHP_EOL; diff --git a/lib/php/functions.php b/lib/php/functions.php index 8dd1afc3..04045f07 100644 --- a/lib/php/functions.php +++ b/lib/php/functions.php @@ -8,7 +8,7 @@ s/array_key_exists(\([^,]\+\),\([^)]\+\))/isset(\2[\1])/g s/^define(\([^,]\+\)/if (!defined(\1)) define(\1/ */ -if (!defined('DEBUG')) define('DEBUG',(int)@$_REQUEST['debug']); +if (!defined('DEBUG')) define('DEBUG',(int)nb::p('debug')); // NB 28.06.15 require_once((dirname(__FILE__).'/default.php')); function file_write($file,$data,$mode='w') { @@ -95,7 +95,9 @@ function txt2md($txt) { } function bye($msg='',$backtrace_deep=0) { - if ($msg) err($msg,'bye',1+$backtrace_deep); + #if ($msg) err($msg,'bye',$backtrace_deep === 0 ? 1 : $backtrace_deep); + if ($msg) err($msg,'bye',( $backtrace_deep !== false ? (1+$backtrace_deep) : $backtrace_deep )); + #if ($msg) err($msg,'bye',1+$backtrace_deep); exit; } @@ -105,9 +107,9 @@ function warn ($msg) { function err($msg,$preff='err',$backtrace_deep=0) { $msg = is_scalar($msg) ? $msg : print_r($msg,true); - $msg = $msg.' '.nb::debug_backtrace_msg(1+$backtrace_deep,NULL,strtoupper($preff).": "); + if ($msg and $backtrace_deep !== false) $msg .= ' '.nb::debug_backtrace_msg(1+$backtrace_deep,NULL,strtoupper($preff).": "); - echo( preg_match('/ml/i',nb::get_header('Content-type')) + nb::msg( preg_match('/ml/i',nb::get_header('Content-type')) ? '
    '.$msg.'
    ' : strtoupper($preff).": $msg" ).PHP_EOL; @@ -120,15 +122,16 @@ function debug($msg,$level=0) { $msg = is_scalar($msg) ? $msg : print_r($msg,true); if (preg_match('/ml/i',nb::get_header('Content-type'))) { - echo '
    '
    -      .(@$_SERVER['HTTP_HOST'] ? htmlentities($msg) : $msg)
    -# NB 16.12.15       .(@$_SERVER['HTTP_HOST'] ? htmlspecialchars($msg) : $msg)
    +    $msg = '
    '
    +      .(isset($_SERVER['HTTP_HOST']) ? htmlentities($msg) : $msg)
    +# NB 16.12.15       .(isset($_SERVER['HTTP_HOST']) ? htmlspecialchars($msg) : $msg)
         .'
    '.PHP_EOL; } else { - echo "DEBUG: $msg\n"; + $msg = "DEBUG: $msg\n"; } + nb::msg($msg); } diff --git a/lib/php/nb.php b/lib/php/nb.php index af16fead..3562c4ea 100644 --- a/lib/php/nb.php +++ b/lib/php/nb.php @@ -1,8 +1,10 @@ 'txt', @@ -19,25 +21,42 @@ class nb { 'yaml' => 'text/yaml', ); + public static function zaza() { + return (is_object($this) ? 'TRUE' : 'FALSE'); + } + function __destruct() { - foreach (get_object_vars($this) as $k=>$v) { unset($this->$k); }; + #foreach (get_object_vars($this) as $k=>$v) { echo ("$k: $v\n"); } + #if (is_object($this)) + try { + foreach (get_object_vars($this) as $k=>$v) { unset($this->$k); }; + } catch(Exception $e) { + } } /* * Function: p * Return a param */ - static function p($name=null,$default=null) { + public static function p($name=null,$default=null) { if ($name === null) return isset($_REQUEST) ? $_REQUEST : array(); return isset($_REQUEST[$name]) ? $_REQUEST[$name] : $default; } + /* + * Set a default value for param, if not sent + */ + public static function pdef($name,$value) { + if (preg_match('/^\s*$/',self::p($name))) return self::pset($name,$value); + return false; + } + /* * Function: pset * Set a value for param, delete it if null */ - static function pset($name,$value) { - if ($value === null) { + public static function pset($name,$value) { + if ($value === null or $value === '') { unset ($_REQUEST[$name]); return null; } @@ -48,15 +67,15 @@ class nb { * Function: bye * Set a value for param, delete it if null */ - static function bye($msg='') { - return bye($msg); + public static function bye($msg='',$backtrace_deep=0) { + return bye($msg,$backtrace_deep); } /* * Function: debug * Does what it says */ - static function debug($msg,$level=0) { + public static function debug($msg,$level=0) { return debug($msg,$level); } @@ -64,7 +83,7 @@ class nb { * Function: ar_map * Does what it says */ - static function ar_map($text) { + public static function ar_map($text) { return ar_map($text); } @@ -72,7 +91,7 @@ class nb { * Function: prettyText * Does what it says */ - static function prettyText($text) { + public static function prettyText($text) { return prettyText($text); } @@ -80,7 +99,7 @@ class nb { * Function: prettyText * Does what it says */ - static function ext2mime($ext) { + public static function ext2mime($ext) { foreach (self::$content_types as $e => $c) { if ($ext == $e) return $c; @@ -95,7 +114,16 @@ class nb { * Function: ar_first * Does what it says */ - static function ar_first($ar) { + public static function ar_first(&$ar,$hkeys=false) { + # Strict Standards: Non-static method: if (self::is_hash($ar)) return ar_first(array_keys($ar)); + #if (self::is_hash($ar)) return ar_first(array_keys($ar)); + $is_hash = null; + foreach ($ar as $k=>$v) { + $is_hash = ($k === 0) ? false : true; + break; + } + #$is_hash = (array_values($ar) === $ar); + if ($is_hash) return ar_first($hkeys ? array_keys($ar) : array_values($ar)); return ar_first($ar); } @@ -103,7 +131,7 @@ class nb { * Function: get_header * Return a client header */ - static function get_header($name,$value=null) { + public static function get_header($name,$value=null) { foreach (headers_list() as $a) { if ( preg_match("/^$name:\s+(.*)/i",$a,$m) ) return $m[1]; } @@ -114,7 +142,7 @@ class nb { * Function: argv2request * Set $_REQUEST from argv */ - static function argv2request() { + public static function argv2request() { global $argv; @@ -154,7 +182,7 @@ class nb { * Call a function several times * Usage: benchmark("f1"); benchmark("f2"); benchmark(); */ - static function benchmark($function=null,$limit=1000000) { + public static function benchmark($function=null,$limit=1000000) { global $_benchmark; if ($_benchmark === null) { @@ -182,12 +210,12 @@ class nb { /* * Function: object2array */ - static function object2array($o) { return $array = json_decode(json_encode($o), true); } + public static function object2array($o) { return $array = json_decode(json_encode($o), true); } /* * Function: yaml_encode */ - static function yaml_encode($row) { + public static function yaml_encode($row) { #$yaml = yaml_emit(self::object2array($row)); $yaml = yaml_emit($row); $yaml = preg_replace('/^---\n/','',$yaml); @@ -204,10 +232,12 @@ class nb { * @author NB * Return backtrace message */ - static function debug_backtrace_msg($deep=NULL,$one_line=NULL,$preff='') { + public static function debug_backtrace_msg($deep=NULL,$one_line=NULL,$preff='') { $msg = ''; if (isset($_REQUEST['_debug_backtrace_msg'])) $deep = $_REQUEST['_debug_backtrace_msg']; + if ($deep < 0 or $deep === false) return $msg; + #$msg .= "[deep=$deep]"; #if ($deep===NULL or $deep===TRUE) { @@ -217,14 +247,14 @@ class nb { $tot = count($debug); foreach (array_reverse($debug) as $i=>$call_info) { - $msg .= ( $one_line ? ($preff !=='' ? $preff : ' | ') : "\n$preff " ) . nb::debug_backtrace_info($call_info); + $msg .= ( $one_line ? ($preff !=='' ? $preff : ' | ') : "\n$preff " ) . self::debug_backtrace_info($call_info); if ($deep and ($tot-$i) <= $deep+1) break; } #$msg .= ($one_line ? "" : "\n")."]"; #} elseif (isset($call_info[(int)$deep])) { - #$msg .= ' '.nb::debug_backtrace_info($call_info[(int)$deep]); + #$msg .= ' '.self::debug_backtrace_info($call_info[(int)$deep]); #} @@ -237,7 +267,7 @@ class nb { * @author NB * Return backtrace message */ - static function debug_backtrace_info($call_info) { + public static function debug_backtrace_info($call_info) { $errorType = array ( E_ERROR => 'ERROR', @@ -285,7 +315,97 @@ class nb { return join(' ',$msg); } -} -#die(nb::ext2mime('csv')); + /** + * @copyright NB 05.03.16 + * Test if an array is indexed + * See: http://stackoverflow.com/questions/173400/how-to-check-if-php-array-is-associative-or-sequential + * + * @param ARRAY $arr + * @return BOOL + */ + public static function is_hash(Array &$arr) { + //debug (array_values($arr)); + foreach ($arr as $k=>$v) { + return ($k === 0) ? false : true; + } + return null; + return (array_values($arr) === $arr); + } + + public static function hksort(&$h,$k,$get_first=false) { + uasort($h,create_function('$a,$b','$a_=isset($a["'.$k.'"])?$a["'.$k.'"]:-1;$b_=isset($b["'.$k.'"])?$b["'.$k.'"]:-1; return($b_-$a_);')); + if ($get_first) { + $first = self::ar_first($h); + if ($get_first !== true) return $first[$get_first]; + return $first; + } + return true; + } + + /** + * @copyright NB 06.03.16 + * Print message on stderr if php is in client mode + */ + public static function msg($msg) { + if (self::php_cli()) return file_write("php://stderr",$msg); + echo($msg); + } + /* + public static function ar_sort(&$ary, $clause, $ascending = true) { + $clause = str_ireplace('order by', '', $clause); + $clause = preg_replace('/\s+/', ' ', $clause); + $keys = explode(',', $clause); + $dirMap = array('desc' => 1, 'asc' => -1); + $def = $ascending ? -1 : 1; + + $keyAry = array(); + $dirAry = array(); + foreach($keys as $key) { + $key = explode(' ', trim($key)); + $keyAry[] = trim($key[0]); + if(isset($key[1])) { + $dir = strtolower(trim($key[1])); + $dirAry[] = $dirMap[$dir] ? $dirMap[$dir] : $def; + } else { + $dirAry[] = $def; + } + } + + $fnBody = ''; + for($i = count($keyAry) - 1; $i >= 0; $i--) { + $k = $keyAry[$i]; + $t = $dirAry[$i]; + $f = -1 * $t; + $aStr = '$a[\''.$k.'\']'; + $bStr = '$b[\''.$k.'\']'; + if(strpos($k, '(') !== false) { + $aStr = '$a->'.$k; + $bStr = '$b->'.$k; + } + + if($fnBody == '') { + $fnBody .= "if({$aStr} == {$bStr}) { return 0; }\n"; + $fnBody .= "return ({$aStr} < {$bStr}) ? {$t} : {$f};\n"; + } else { + $fnBody = "if({$aStr} == {$bStr}) {\n" . $fnBody; + $fnBody .= "}\n"; + $fnBody .= "return ({$aStr} < {$bStr}) ? {$t} : {$f};\n"; + } + } + + if($fnBody) { + $sortFn = create_function('$a,$b', $fnBody); + usort($ary, $sortFn); + } + } + */ + + public static function php_cli() { +# NB 05.03.16 define('NB_CLI', PHP_SAPI === 'cli'); + return (!isset($_SERVER['SERVER_SOFTWARE']) && (php_sapi_name() == 'cli' || (is_numeric($_SERVER['argc']) && $_SERVER['argc'] > 0))); + } + +} # < Class +#die(self::ext2mime('csv')); ?> diff --git a/lib/php/page.php b/lib/php/page.php index 27604b76..4a356a73 100644 --- a/lib/php/page.php +++ b/lib/php/page.php @@ -122,7 +122,7 @@ class Page extends nb { sprintf('%c[0m',27) => '', ); return preg_replace('/(body_class.'"') - .(empty($this->body_id) ? '' : ' id="'.$this->body_id.'"') + .(empty($this->body_class) ? '' : ' class="'.trim($this->body_class).'"') + .(empty($this->body_id) ? '' : ' id="'.trim($this->body_id).'"') .'>' . PHP_EOL; if ($this->h1) echo $this->tag('h1',$this->h1).PHP_EOL; elseif ($this->title) echo $this->tag('h1',$this->title).PHP_EOL; } + return true; + } function end() { @@ -329,17 +332,80 @@ class Page extends nb { return $head; } - function is($is) { + public static function is($is) { if ($is == 'xhtml') return preg_match('/xhtml$/',$this->content_type); if ($is == 'html') return preg_match('/html$/',$this->content_type); if ($is == 'xml') return preg_match('/xml$/',$this->content_type); die("Db->is(): unknow argument '$is'. Accepted values are xhtml, html, xml"); } - function path() { + public static function path() { if (empty($_SERVER['REQUEST_URI'])) return ''; return preg_replace('/\?.*$/','',$_SERVER['REQUEST_URI']); } + /** + * @copyright (C) 2016 Nicolas Boisselier + * @author Nicolas Boisselier nicolas.boisselier@gmail.com + * Does what the name says + * + * @param datatype1|datatype2 \$paramname description + * @return datatype1|datatype2 description + */ + public static function init($param) { + global $Page; + if (isset($Page)) self::bye("Page.init(): GLOBALS['Page'] already exists !"); + if (!self::is_hash($param)) $param = array('nav' => $param); + + $Page = new self(array( + + # 'head' => array( + # '', + # ), + 'body_class' => 'db', + + 'css' => false ? array() : array( + #'/jquery/jquery.mobile.css', + #'/jquery/jquery-ui.css', + '/css/reset.css', + '/css/block.css', + '/css/button.css', + '/css/db.css', + ), + + 'js' => array( + '/jquery/jquery.js', + '/jquery/jquery-ui.js', + #'/jquery/jquery.mobile.js', + '/js/nb.js', + ), + + )); + if (isset($param['js'])) foreach ($param['js'] as $v) { $Page->js[] = $v; } + if (isset($param['css'])) foreach ($param['css'] as $v) { $Page->css[] = $v; } + + $title = $nav = array(); + + if (isset($param['nav'])) foreach ($param['nav'] as $k => $v) { + if ($v === '' or $v === null or empty($v[0])) { + continue; + } + + if (is_array($v)) { + $nav[] = ''.$v[0].''; + #$title[] = $v[0]; + } else { + $nav[] = ''.$v.''; + $title[] = $v; + } + + } + + #debug(array($nav,$title)); return; + $Page->h1 = join(' / ',$nav); + + $Page->title = join(' / ',$title); + } + } return; ?> -- 2.47.3