use Encode;
use URI::Escape;
use NB::Functions qw/html2txt/;
+use NB qw/$ROOT_DIR/;
#################################################################################
#
# VERSION
'f' => 'format',
'l' => 'limit',
'a' => 'action',
+ 'h' => 'header',
);
## Vim: r!% --curl_help_hash | grep X
#
# 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;
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;
--- /dev/null
+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||'&idplace='||idplace||'&idtenant='||idtenant||'&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||'&idplace='||idplace||'&idtenant='||idtenant||'&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>'"
+#
+# 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
# Aliases
#
#################################################################################
+[ -n "$MYVIMRC" ] && shopt -s expand_aliases
#--------------------------------------------------------------------------------
# Others
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
#
# PS1
#
-case "$SHELL" in
- */zsh) ;;
- *)
+case "$SHELL_NAME" in
+ bash)
h='\h'
color=''
}
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() {
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
--- /dev/null
+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
""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" 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
#################################################################################
my $VERSION = '0.0.1';
# [% user.me_now %]
-# - create script
+# - create script: [% var.basename %]
#################################################################################
#
--- /dev/null
+ /**
+ * @copyright [% user.copyright %]
+ * @author [% user.author %]
+ * Does what the name says
+ *
+ * @param datatype1|datatype2 \$paramname description
+ * @return datatype1|datatype2 description
+ */
+ function foo() {
+ }
+
cat << EOF
/**
* @copyright $ME $NOW
-* Php Function Template
+* Does what it says
*
* @param datatype1|datatype2 \$paramname description
* @return datatype1|datatype2 description
# -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 = {
});
}
+ 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() { }
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);
# 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
--- /dev/null
+<?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();
+?>
#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;
' 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); });
}
+ return empty($this->conn) ? false : true;
}
/*
}
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') {
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
?>
--- /dev/null
+#!/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);
+?>
// 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) {
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;
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') {
}
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;
}
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;
$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);
}
<?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',
'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;
}
* 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);
}
* Function: ar_map
* Does what it says
*/
- static function ar_map($text) {
+ public static function ar_map($text) {
return ar_map($text);
}
* Function: prettyText
* Does what it says
*/
- static function prettyText($text) {
+ public static function prettyText($text) {
return prettyText($text);
}
* 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;
* 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);
}
* 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];
}
* Function: argv2request
* Set $_REQUEST from argv
*/
- static function argv2request() {
+ public static function argv2request() {
global $argv;
* 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) {
/*
* 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);
* @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) {
$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]);
#}
* @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',
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'));
?>
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))
);
}
*/
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)) {
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() {
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;
?>