]> git.nbdom.net Git - nb.git/commitdiff
move slowly out from rent
authorNicolas Boisselier <nicolas.boisselier@gmail.com>
Sun, 6 Mar 2016 04:43:24 +0000 (04:43 +0000)
committerNicolas Boisselier <nicolas.boisselier@gmail.com>
Sun, 6 Mar 2016 04:43:24 +0000 (04:43 +0000)
21 files changed:
bin/dbq
etc/dbs.yaml [new file with mode: 0644]
etc/profile
etc/profile.d/aliases
etc/profile.d/envs
etc/profile.d/functions
etc/profile.d/history.sh [new file with mode: 0644]
etc/vim/source/option.vim
etc/vim/templates/perl.tt [changed mode: 0644->0755]
etc/vim/templates/phpf.tt [new file with mode: 0644]
etc/vim/vim-shortcurts
etc/vim/vimplaterc
lib/js/nb.js
lib/perl/NB.pm
lib/php/config.php [new file with mode: 0644]
lib/php/db.php
lib/php/db/index.php [new file with mode: 0755]
lib/php/db/table.php
lib/php/functions.php
lib/php/nb.php
lib/php/page.php

diff --git a/bin/dbq b/bin/dbq
index 944fb99c9bdd98c3cb41f43916887af4b1b2bbdf..ad1f3385ac65c6b937bb5027adfb172ad6282fb0 100755 (executable)
--- 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 (file)
index 0000000..c658a5b
--- /dev/null
@@ -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: "'<a href=\"/template/'||id||'\">'||id||'</a>'"
+
+    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('<a href="template/?id='||id||'&amp;idplace='||idplace||'&amp;idtenant='||idtenant||'&amp;start='||start||'">'||substr(id,0,instr(id,'.'))||'</a>',' ') 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('<a href="template/?id='||id||'&amp;idplace='||idplace||'&amp;idtenant='||idtenant||'&amp;start='||start||'">'||substr(id,0,instr(id,'.'))||'</a>',' ') FROM template)
+# NB 10.01.16     template:
+# NB 10.01.16       View: "'<a href=\"/template/'||id||'\">'||id||'</a>'"
index 5ab1e06e028f72a85fb35a8e35a365c6a78d1732..6c04a36f544a8014ae81505567bea22667fe20dc 100644 (file)
@@ -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
index 734514a72d1595fec5bc50d987e74182b57a47e4..77f5856dcfd38c41933f59d27968ac1f91a1c6d9 100644 (file)
@@ -3,6 +3,7 @@
 # Aliases
 #
 #################################################################################
+[ -n "$MYVIMRC" ] && shopt -s expand_aliases
 
 #--------------------------------------------------------------------------------
 # Others
index 5dd0926c6cf5dc8f8876d8533ec0b0a7a09def5e..e09048f024483aec908706718ab4255d82121be5 100644 (file)
@@ -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=''
index 0cd13f1e3877b375ad3ea70dadde7e622a2b0c4f..2b9687d7173a60d56da8e871a14ff9e5baf33d2c 100644 (file)
@@ -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 (file)
index 0000000..582fc3a
--- /dev/null
@@ -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
index 866b66e39da8d9b8bace583015149300d2bc63a3..8bd930f60f3a03e7519ad2d30f84a5da29d638d5 100644 (file)
@@ -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
old mode 100644 (file)
new mode 100755 (executable)
index c6a3999..0853638
@@ -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 (file)
index 0000000..516abb8
--- /dev/null
@@ -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() {
+  }
+
index 2aa1b2f5abcb6f7a6deffc3c6676275b37945380..d8593bd7a569dd0600ce9b7b5a5a569af6d6a401 100755 (executable)
@@ -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
index 7a6106e7ce577cffbe439453719458fa53139ec5..a11e53ecdd6dae45d959245fc93f2ec387921808 100755 (executable)
@@ -5,25 +5,34 @@
 #   -user=<user> -dir=<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 = {
index 2c42bd14fc829aafb784909d1ba4462e8bf198fb..587490b6685bca27d2dfad0d2c85457a3a2a4580 100644 (file)
@@ -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<level+1;j++) level_padding += "    ";
+
+               if(typeof(arr) == 'object') { //Array/Hashes/Objects
+                       for(var item in arr) {
+                               var value = arr[item];
+
+                               if(typeof(value) == 'object') { //If it is an array,
+                                       dumped_text += level_padding + "'" + item + "' ...\n";
+                                       dumped_text += dump(value,level+1);
+                               } else {
+                                       dumped_text += level_padding + "'" + item + "' => \"" + value + "\"\n";
+                               }
+                       }
+               } else { //Stings/Chars/Numbers etc.
+                       dumped_text = "===>"+arr+"<===("+typeof(arr)+")";
+               }
+               return dumped_text;
+       }
 };
 
 //NB.prototype.your_method = function() { }
index 3826bf92b6c653f1a383cd6d811186c3f8344e15..b745708759411ea183e6196672cd73759efe68de 100644 (file)
@@ -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 (file)
index 0000000..c385af9
--- /dev/null
@@ -0,0 +1,21 @@
+<?php
+/**
+* @copyright (C) 2016 Nicolas Boisselier
+* @author Nicolas Boisselier nicolas.boisselier@gmail.com
+*
+* lib/php/config.php
+*/
+
+date_default_timezone_set('Europe/London');
+ini_set('display_errors', 'On');
+error_reporting(E_ALL | E_STRICT | E_NOTICE);
+
+# NB 05.03.16 ini_set('include_path', realpath(dirname(__FILE__).'/../lib').':'.realpath(dirname(__FILE__)).':'.ini_get('include_path'));
+ini_set('include_path',''
+       .':'.realpath(dirname(__FILE__))
+       .rtrim(':'.ini_get('include_path'),':')
+);
+
+require_once('nb.php');
+if (nb::php_cli()) argv2request();
+?>
index a30f7b92a7bcea889c311ecea6a7895da9730f01..a9c34a21c6de7c2752dd7c30c5ab7dfbddd1f602 100644 (file)
@@ -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','<a class="button" href="?" onclick="nb.form_clear(this.parentElement) ? 0: 0">Add</a>');
 #if (!defined('DB_HTML_BUTTON_ADD'))    define('DB_HTML_BUTTON_ADD','<input type="submit" class="button" value="Add" onclick="this.setAttribute(\'name\',\'edit\')?0:0"/>');
 
-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 (executable)
index 0000000..73934b4
--- /dev/null
@@ -0,0 +1,15 @@
+#!/usr/bin/env php
+<?php
+/**
+* @copyright (C) 2016 Nicolas Boisselier
+* @author Nicolas Boisselier nicolas.boisselier@gmail.com
+*
+* lib/php/db/index.php
+*/
+require_once(dirname(__FILE__).'/../config.php');
+require_once(dirname(__FILE__).'/../db.php');
+
+Db::init(array( '/etc/dbs.yaml' ));
+
+return $Db->action($Table);
+?>
index aedb37bc80c2b2e06c0be3a4cb730a0206f816e2..e6ef0bf2a712e95422c7a2580fc3218fe1e6b567 100644 (file)
@@ -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 '<div class="rows '.$this->name.'">';
+    return '<div class="rows '.$this->name.'">'.PHP_EOL;
   }
 
   function rows_rec_div(&$row) {
 
     $html = '';
 
-    $html .= '<ul class="row">';
+    $html .= '<ul class="row">'.PHP_EOL;
 
     if ($this->p('buttons')!=='0') {
-      $html .= '<li class="buttons">';
-      $html .= '<a class="edit button" href="'.$this->url_keys($row,'action=edit').'">'.DB_HTML_EDIT.'</a>';
-      $html .= '<a class="delete button" href="'.$this->url_keys($row,'action=delete').'">'.DB_HTML_DELETE.'</a>';
-      $html .= '</li>';
+      $html .= '<li class="buttons">'.PHP_EOL;
+      $html .= '<a class="edit button" href="'.$this->url_keys($row,'action=edit').'">'.DB_HTML_EDIT.'</a>'.PHP_EOL;
+      $html .= '<a class="delete button" href="'.$this->url_keys($row,'action=delete').'">'.DB_HTML_DELETE.'</a>'.PHP_EOL;
+      $html .= '</li>'.PHP_EOL;
     }
 
     foreach ($row as $k => $v) {
       $html .= '<li>'
         .( $k == '0' ? '' : '<label>'.prettyText($k).'</label>')
         .'<span class="'.$k.'">'.$v.'</span>'
-        .'</li>';
+        .'</li>'.PHP_EOL;
     }
 
     $html .= '</ul>'.PHP_EOL;
index 8dd1afc318dc95e6570870c7cf2197a03b387086..04045f0791cde19d4cdacd35761f5cd1723ce9ed 100644 (file)
@@ -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'))
     ? '<pre class="'.($preff and $preff!='err' ? 'err ': '').$preff.'">'.$msg.'</pre>'
     : 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 '<pre class="debug">'
-      .(@$_SERVER['HTTP_HOST'] ? htmlentities($msg) : $msg)
-# NB 16.12.15       .(@$_SERVER['HTTP_HOST'] ? htmlspecialchars($msg) : $msg)
+    $msg = '<pre class="debug">'
+      .(isset($_SERVER['HTTP_HOST']) ? htmlentities($msg) : $msg)
+# NB 16.12.15       .(isset($_SERVER['HTTP_HOST']) ? htmlspecialchars($msg) : $msg)
     .'</pre>'.PHP_EOL;
 
   } else {
-    echo "DEBUG: $msg\n";
+    $msg = "DEBUG: $msg\n";
 
   }
+  nb::msg($msg);
 
 }
 
index af16fead51476995977b7b8ebb1d5c2fe26753ea..3562c4ea2f1d06f5e86ebf78a2daf0d07e6f893e 100644 (file)
@@ -1,8 +1,10 @@
 <?php
+define('NB_ROOT',realpath(dirname(__FILE__).'/../..'));
 require_once(dirname(__FILE__).'/functions.php');
-#print_r(nb::p());
+#print_r(self::p());
 class nb {
 
+  public static $root_dir = NB_ROOT;
   # Sql: elect type,ext from mime_type where ext in ('json','csv','txt','yaml','xml','html','doc','xls');
   public static $content_types_aliases = array(
     'text' => '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'));
 ?>
index 27604b763b8ec8eaee58ee728820510feb3bd15a..4a356a73b957c0eb773a6914809205731cce6e11 100644 (file)
@@ -122,7 +122,7 @@ class Page extends nb {
       sprintf('%c[0m',27)    => '</span>',
     );
     return preg_replace('/<bold>(<span style=")/','\1font-weight:bold;',
-      str_replace(array_keys($html),array_values($html),Page::str2txt($v))
+      str_replace(array_keys($html),array_values($html),self::str2txt($v))
     );
   }
 
@@ -192,6 +192,7 @@ class Page extends nb {
   */
   function begin() {
 
+    if ($this->php_cli() or $this->p('txt_errors')) ini_set('html_errors', false);
     $this->headers(); 
 
     if (preg_match('/html$/',$this->content_type)) {
@@ -214,14 +215,16 @@ class Page extends nb {
       echo $this->head(); 
 
       echo '<body'
-        .(empty($this->body_class) ? '' : ' class="'.$this->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(
+    #    '<meta name="viewport" content="initial-scale=1, maximum-scale=1" />',
+    #  ),
+      '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[] = '<a href="'.$v[1].'">'.$v[0].'</a>';
+        #$title[] = $v[0];
+      } else {
+        $nav[] = '<span>'.$v.'</span>';
+        $title[] = $v;
+      }
+
+    }
+
+    #debug(array($nav,$title)); return;
+    $Page->h1 = join(' / ',$nav);
+
+    $Page->title = join(' / ',$title);
+  }
+
 } return;
 ?>