From 17eee9529f7f4acadbf21cb8dfbb21e4e49189c1 Mon Sep 17 00:00:00 2001 From: Tamer Zorba Date: Mon, 23 Nov 2015 10:46:35 +0200 Subject: [PATCH 001/114] fix upload remove user not logged error with force --- system/module/Upload.php | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/system/module/Upload.php b/system/module/Upload.php index f80108a..b53da12 100644 --- a/system/module/Upload.php +++ b/system/module/Upload.php @@ -466,10 +466,11 @@ public static function remove($ids,$force=false){ $ids = implode(",", $ids); Module::import("Query"); - Module::import("User"); - $user = User::info(); - if(!$user->status)return $user; - + if(!$force){ + Module::import("User"); + $user = User::info(); + if(!$user->status)return $user; + } $where = array("id"=>":in:{$ids}"); if(!$force)$where['author'] = $user->data[0]['id']; From caadfea0e93297189fbab1da591a4a428719e60c Mon Sep 17 00:00:00 2001 From: Tamer Zorba Date: Tue, 24 Nov 2015 00:48:54 +0200 Subject: [PATCH 002/114] define vendor assets function --- system/core/Assets.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/system/core/Assets.php b/system/core/Assets.php index 3863484..13cffba 100644 --- a/system/core/Assets.php +++ b/system/core/Assets.php @@ -159,6 +159,6 @@ public static function element($src,$folder="vendor",$listener='element'){ public static function vendor($src=''){ global $config; - return Request::base("{$config['app']}/vendor"); + return Request::base("{$config['app']}/vendor{$src}"); } } \ No newline at end of file From 0ba0e1dd80e31b53768712bd817d9db12f7b1f8a Mon Sep 17 00:00:00 2001 From: Tamer Zorba Date: Tue, 24 Nov 2015 00:49:32 +0200 Subject: [PATCH 003/114] add index for each loop directive by varIndex or __index --- system/module/Directives.php | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/system/module/Directives.php b/system/module/Directives.php index 6d87a20..5e1d3c7 100644 --- a/system/module/Directives.php +++ b/system/module/Directives.php @@ -48,8 +48,12 @@ public static function __bootstrap(){ 'callback' => function($match){ $str = ""; $ex = explode(' in ',trim($match[1])); - foreach(Controller::$scope->$ex[1] as $file){ + foreach(Controller::$scope->$ex[1] as $k => $file){ Controller::$scope->$ex[0] = $file; + $index = "{$ex[0]}Index"; + echo $index; + Controller::$scope->$index = $k; + Controller::$scope->__index = $k; $str .= Shortcode::trigger($match[2]); } return $str; From dee9c8c29bf76f4a80f67fcea71b005e18a3a2e5 Mon Sep 17 00:00:00 2001 From: Tamer Zorba Date: Tue, 24 Nov 2015 00:50:11 +0200 Subject: [PATCH 004/114] getting started with Object module and adding get and fetch functions --- system/module/Object.php | 54 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 54 insertions(+) create mode 100644 system/module/Object.php diff --git a/system/module/Object.php b/system/module/Object.php new file mode 100644 index 0000000..07828a8 --- /dev/null +++ b/system/module/Object.php @@ -0,0 +1,54 @@ +$data, "where"=>$where]); + } + + +} + +/* End of file Object.php */ +/* Location: ./system/module/Object.php */ \ No newline at end of file From 44bd536822aa2983b1cb04b80164a8effeb0488d Mon Sep 17 00:00:00 2001 From: Tamer Zorba Date: Tue, 24 Nov 2015 00:54:16 +0200 Subject: [PATCH 005/114] remove echo for debugging --- system/module/Directives.php | 1 - 1 file changed, 1 deletion(-) diff --git a/system/module/Directives.php b/system/module/Directives.php index 5e1d3c7..1515180 100644 --- a/system/module/Directives.php +++ b/system/module/Directives.php @@ -51,7 +51,6 @@ public static function __bootstrap(){ foreach(Controller::$scope->$ex[1] as $k => $file){ Controller::$scope->$ex[0] = $file; $index = "{$ex[0]}Index"; - echo $index; Controller::$scope->$index = $k; Controller::$scope->__index = $k; $str .= Shortcode::trigger($match[2]); From e258dc509eda9ebfdd4087fe2e5742b731c38228 Mon Sep 17 00:00:00 2001 From: Tamer Zorba Date: Fri, 27 Nov 2015 21:46:54 +0200 Subject: [PATCH 006/114] fixed #7 --- system/module/Upload.php | 1 + 1 file changed, 1 insertion(+) diff --git a/system/module/Upload.php b/system/module/Upload.php index b53da12..4ba9ae8 100644 --- a/system/module/Upload.php +++ b/system/module/Upload.php @@ -301,6 +301,7 @@ public static function push($arr=array()){ if($q->status){ $cls->status = true; $cls->file = $file; + $cls->path = json_encode($file); }else{ $cls = $q; } From 980cf8c61e93cab0d3cda0f94ed84f8570fea72a Mon Sep 17 00:00:00 2001 From: Tamer Zorba Date: Fri, 27 Nov 2015 22:11:35 +0200 Subject: [PATCH 007/114] update on issue #7 --- system/module/Upload.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/system/module/Upload.php b/system/module/Upload.php index 4ba9ae8..4780a13 100644 --- a/system/module/Upload.php +++ b/system/module/Upload.php @@ -305,7 +305,7 @@ public static function push($arr=array()){ }else{ $cls = $q; } - return $q; + return $cls; } /* From 844d1960561903f3b76e8807ba1806225219a7c7 Mon Sep 17 00:00:00 2001 From: Tamer Zorba Date: Wed, 2 Dec 2015 14:52:07 +0200 Subject: [PATCH 008/114] fixes #9 --- system/module/Query.php | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/system/module/Query.php b/system/module/Query.php index d2f0cbe..7ec5730 100644 --- a/system/module/Query.php +++ b/system/module/Query.php @@ -524,12 +524,21 @@ private static function parse_eq($key,$value,$table){ }else if(strpos($value, ":inset:") !== false){ $value = stripslashes($value); $value = str_replace(":inset:", "", $value); + + $separator = "and"; + if(strpos($value, "and:") !== false){ + $value = str_replace("and:", "", $value); + } + if(strpos($value, "or:") !== false){ + $separator = "or"; + $value = str_replace("or:", "", $value); + } $ex = explode(",",$value); $temp = array(); foreach($ex as $v){ array_push($temp,"FIND_IN_SET ({$v},`{$key}`)"); } - return "(".implode(" or ", $temp).")"; + return "(".implode(" {$separator} ", $temp).")"; }else if(strpos($value, ":in:") !== false){ $value = stripslashes($value); From dcde6aa071b71aab87b12d43860abd5986402989 Mon Sep 17 00:00:00 2001 From: Tamer Zorba Date: Wed, 2 Dec 2015 14:59:51 +0200 Subject: [PATCH 009/114] now where can be string --- system/module/Query.php | 83 ++++++++++++++++++++++------------------- 1 file changed, 45 insertions(+), 38 deletions(-) diff --git a/system/module/Query.php b/system/module/Query.php index 7ec5730..b1bc9c8 100644 --- a/system/module/Query.php +++ b/system/module/Query.php @@ -215,39 +215,41 @@ public static function execute($arr){ } if(isset($arr['where'])){ - if(!isset($arr['join']))$arr['join'] = array(); - foreach($arr['where'] as $k => $v){ - //fix value - // if array then put or between them - if(is_array($v))continue; - if(strpos($v, "~") === 0){ - - $v = str_replace("~", "", $v); - if(!strpos($v, ".")){ - if(!self::inStructure($v, $table)){ - $arr['join']["meta as `{$k}`"] = "`{$k}`.`oid` = `{$table}`.`id` and `{$k}`.`key`='{$k}' and `{$k}`.`table` = '{$table}'"; - $v = "`{$k}`.`{$v}`"; + if(is_array($arr['where'])){ + if(!isset($arr['join']))$arr['join'] = array(); + foreach($arr['where'] as $k => $v){ + //fix value + // if array then put or between them + if(is_array($v))continue; + if(strpos($v, "~") === 0){ + + $v = str_replace("~", "", $v); + if(!strpos($v, ".")){ + if(!self::inStructure($v, $table)){ + $arr['join']["meta as `{$k}`"] = "`{$k}`.`oid` = `{$table}`.`id` and `{$k}`.`key`='{$k}' and `{$k}`.`table` = '{$table}'"; + $v = "`{$k}`.`{$v}`"; + }else{ + $v = "`{$table}`.`{$v}`"; + } }else{ - $v = "`{$table}`.`{$v}`"; + $v = str_replace(".", "`.`", $v); + $v = "`{$v}`"; } - }else{ - $v = str_replace(".", "`.`", $v); - $v = "`{$v}`"; } - } - - //fix key - if(!self::inStructure($k, $table)){ - $k = trim($k); - if(!strpos($k, ".")){ - $arr['join']["meta as `{$k}`"] = "`{$k}`.`oid` = `{$table}`.`id` and `{$k}`.`key`='{$k}' and `{$k}`.`table` = '{$table}'"; - unset($arr['where'][$k]); - $arr['where']["{$k}.value"] = $v; - } - }else{ - if(!strpos($k, ".")){ - unset($arr['where'][$k]); - $arr['where']["{$table}.{$k}"] = $v; + + //fix key + if(!self::inStructure($k, $table)){ + $k = trim($k); + if(!strpos($k, ".")){ + $arr['join']["meta as `{$k}`"] = "`{$k}`.`oid` = `{$table}`.`id` and `{$k}`.`key`='{$k}' and `{$k}`.`table` = '{$table}'"; + unset($arr['where'][$k]); + $arr['where']["{$k}.value"] = $v; + } + }else{ + if(!strpos($k, ".")){ + unset($arr['where'][$k]); + $arr['where']["{$table}.{$k}"] = $v; + } } } } @@ -329,15 +331,20 @@ public static function execute($arr){ array_push($sql, implode($j, " ")); } if(isset($arr['where'])){ - if(sizeof($arr['where']) > 0){ - $wh = array(); - array_push($sql, 'where'); - foreach ($arr['where'] as $key => $value) { - array_push($wh, self::parse_eq($key, $value, $table)); + if(is_array($arr['where'])){ + if(sizeof($arr['where']) > 0){ + $wh = array(); + array_push($sql, 'where'); + foreach ($arr['where'] as $key => $value) { + array_push($wh, self::parse_eq($key, $value, $table)); + } + $seperate = isset($arr['whereSeperator'])?$arr['whereSeperator']:'and'; + $where = implode($wh, " {$seperate} "); + array_push($sql, $where); } - $seperate = isset($arr['whereSeperator'])?$arr['whereSeperator']:'and'; - $where = implode($wh, " {$seperate} "); - array_push($sql, $where); + }else if(is_string($arr['where'])){ + array_push($sql, 'where'); + array_push($sql, $arr['where']); } } if(isset($arr['groupby'])){ From 98486a17ced18ff9773cc5640245cc8367eeff88 Mon Sep 17 00:00:00 2001 From: Tamer Zorba Date: Wed, 2 Dec 2015 15:01:41 +0200 Subject: [PATCH 010/114] fixes #9 set or as default --- system/module/Query.php | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/system/module/Query.php b/system/module/Query.php index b1bc9c8..3ee016d 100644 --- a/system/module/Query.php +++ b/system/module/Query.php @@ -532,14 +532,14 @@ private static function parse_eq($key,$value,$table){ $value = stripslashes($value); $value = str_replace(":inset:", "", $value); - $separator = "and"; - if(strpos($value, "and:") !== false){ - $value = str_replace("and:", "", $value); - } + $separator = "or"; if(strpos($value, "or:") !== false){ - $separator = "or"; $value = str_replace("or:", "", $value); } + if(strpos($value, "and:") !== false){ + $separator = "and"; + $value = str_replace("and:", "", $value); + } $ex = explode(",",$value); $temp = array(); foreach($ex as $v){ From bdca6f56dbfe148f4f8420e2ac80fd248defbca5 Mon Sep 17 00:00:00 2001 From: Tamer Zorba Date: Mon, 28 Dec 2015 12:11:15 +0200 Subject: [PATCH 011/114] return upload file name and last --- system/module/Upload.php | 2 ++ 1 file changed, 2 insertions(+) diff --git a/system/module/Upload.php b/system/module/Upload.php index 4780a13..cbd605c 100644 --- a/system/module/Upload.php +++ b/system/module/Upload.php @@ -302,6 +302,8 @@ public static function push($arr=array()){ $cls->status = true; $cls->file = $file; $cls->path = json_encode($file); + $cls->name = $filename; + $cls->last = $q->last; }else{ $cls = $q; } From aac150fee56ff8caa10e59c17677779e048bd7bf Mon Sep 17 00:00:00 2001 From: Tamer Zorba Date: Sat, 16 Jan 2016 01:01:51 +0200 Subject: [PATCH 012/114] parse elements with objects and spaces --- system/core/String.php | 38 +++++++++++++++++++++++++++++++++++++- 1 file changed, 37 insertions(+), 1 deletion(-) diff --git a/system/core/String.php b/system/core/String.php index 604e99f..7f27040 100644 --- a/system/core/String.php +++ b/system/core/String.php @@ -288,7 +288,43 @@ public static function approxlen($str,$len=200,$append='...') { * @param string attribute string ex (name='abc' value='def') * @return array */ - public static function parse_attr($att){ + public static function parse_attr($att,$removeQ=false){ + $pattern = '/(\\w+)\s*=\\s*("[^"]*"|\'[^\']*\'|[^"\'\\s>]*)/'; + preg_match_all($pattern, $att, $matches, PREG_SET_ORDER); + $attrs = array(); + foreach ($matches as $match) { + if (($match[2][0] == '"' || $match[2][0] == "'") && $match[2][0] == $match[2][strlen($match[2])-1] && $removeQ) { + $match[2] = substr($match[2], 1, -1); + } + $name = strtolower($match[1]); + $value = html_entity_decode($match[2]); + switch ($name) { + case 'class': + $attrs[$name] = preg_split('/\s+/', trim($value)); + break; + case 'style': + // parse CSS property declarations + $attrs[$name] = $value; + break; + default: + $attrs[$name] = $value; + } + } + return $attrs; + } + + // -------------------------------------------------------------------- + + /** + * Parse Attr + * + * Parse XML, Shortcode Attributes + * + * @access public + * @param string attribute string ex (name='abc' value='def') + * @return array + */ + public static function xml_parse_attr($att){ $att = self::decode($att,true); $x = new SimpleXMLElement(""); $attr = array(); From 154841bb8c57eccae81dcf9057f94431742be6dc Mon Sep 17 00:00:00 2001 From: Tamer Zorba Date: Sat, 16 Jan 2016 01:02:04 +0200 Subject: [PATCH 013/114] register element directive --- system/module/Directives.php | 39 ++++++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) diff --git a/system/module/Directives.php b/system/module/Directives.php index 1515180..fa10c4a 100644 --- a/system/module/Directives.php +++ b/system/module/Directives.php @@ -251,6 +251,45 @@ private static function scope($v){ } return stripcslashes($val); } + + public static function register($element, $cb){ + Shortcode::register(array( + 'code' => "element_{$element}", + 'pattern' => "%\<{$element} (\b[^<\>]*+)\>((?:(?:(?!\)%six", + 'callback' => function($match) use ($cb, $element){ + $cls = new stdClass(); + $cls->content = $match[2]; + $el = "element_content"; + Controller::$scope->$el = $match[2]; + if(!empty($match[1])){ + $atts = String::parse_attr($match[1]); + foreach ($atts as $k => $v) { + if((strpos($v, "'") !== false || strpos($v, '"') !== false)){ // string here + $v = substr($v, 1, -1); // right left + }else{ + $v = self::scope($v);//Controller::$scope->$v; + } + $cls->$k = $v; + $el = "element_{$k}"; + Controller::$scope->$el = $v; + } + } + if(is_callable($cb)){ + $call = call_user_func_array($cb, array($cls, $match[2])); + }else{ + //echo $match[2]; + $call = Shortcode::trigger($match[2]); + } + return Shortcode::trigger($call); + // trim($match[1]); // the args inside + //Controller::$scope->__index = $k; // loop on variables and set them in scope + //$str = Shortcode::trigger($match[2]);// run the match 2 + //return $str; + } + )); + + + } } /* End of file Query.php */ From 6b8ff8295d7b3f0b495dddc124902aa79ed9e4cc Mon Sep 17 00:00:00 2001 From: Tamer Zorba Date: Mon, 18 Jan 2016 00:10:53 +0200 Subject: [PATCH 014/114] speed up the text search engine with non essential mode --- system/sql/purecis-v1.0.0.sql | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/system/sql/purecis-v1.0.0.sql b/system/sql/purecis-v1.0.0.sql index 162ba23..0211238 100644 --- a/system/sql/purecis-v1.0.0.sql +++ b/system/sql/purecis-v1.0.0.sql @@ -54,7 +54,8 @@ CREATE TABLE `meta` ( `autoload` tinyint(1) NOT NULL DEFAULT '0', PRIMARY KEY (`meta_id`), UNIQUE KEY `oid` (`oid`,`key`,`table`), - KEY `key` (`key`) + KEY `key` (`key`), + KEY `value` (`value`(255)) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; From 9d202303146b607ae8dbb8131f8295d1c5468ebb Mon Sep 17 00:00:00 2001 From: Tamer Zorba Date: Mon, 18 Jan 2016 15:09:30 +0200 Subject: [PATCH 015/114] fix variable on translation --- system/module/Directives.php | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/system/module/Directives.php b/system/module/Directives.php index fa10c4a..bfb66b0 100644 --- a/system/module/Directives.php +++ b/system/module/Directives.php @@ -203,8 +203,7 @@ public static function __bootstrap(){ if(isset($ex[1])){ $ex2 = explode("@", $ex[1]); - // - $a = explode(",", rtrim(ltrim(trim($ex2[0]),"{"),"}")); + $a = explode(",",substr(trim($ex2[0]), 1, -1)); foreach($a as $v){ $vv = explode(":", $v); $ar[$vv[0]] = $vv[1]; From 005401f897f70bd48abe2ec7002033ce975ee512 Mon Sep 17 00:00:00 2001 From: Tamer Zorba Date: Sun, 24 Jan 2016 00:13:24 +0200 Subject: [PATCH 016/114] object additionals --- system/module/Object.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/system/module/Object.php b/system/module/Object.php index 07828a8..0a70f90 100644 --- a/system/module/Object.php +++ b/system/module/Object.php @@ -42,9 +42,9 @@ public static function get( $taxonomy, $arr=array() ){ * @param array data array * @return void */ - public static function fetch( $taxonomy, $data=array(), $where=array() ){ + public static function fetch( $taxonomy, $data=array(), $where=array(), $additional=array() ){ - return self::get($taxonomy,["data"=>$data, "where"=>$where]); + return self::get($taxonomy, array_merge(["data"=>$data, "where"=>$where],$additional)); } From a28fff9197c572053574c86b1dc6fa436c733b67 Mon Sep 17 00:00:00 2001 From: Tamer Zorba Date: Sun, 24 Jan 2016 00:14:41 +0200 Subject: [PATCH 017/114] fix array in scope, custom element now can scope --- system/module/Directives.php | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/system/module/Directives.php b/system/module/Directives.php index bfb66b0..fe27bfc 100644 --- a/system/module/Directives.php +++ b/system/module/Directives.php @@ -248,7 +248,7 @@ private static function scope($v){ if($val == null)break; } } - return stripcslashes($val); + return is_string($val)?stripcslashes($val):$val; } public static function register($element, $cb){ @@ -274,7 +274,10 @@ public static function register($element, $cb){ } } if(is_callable($cb)){ - $call = call_user_func_array($cb, array($cls, $match[2])); + $call = call_user_func_array($cb, array($cls, &Controller::$scope)); + + }else if(is_string($cb)){ + $call = View::load($cb); }else{ //echo $match[2]; $call = Shortcode::trigger($match[2]); From e0121ac2fa9ab8efc46003a6adaa38062091c65f Mon Sep 17 00:00:00 2001 From: Tamer Zorba Date: Sun, 24 Jan 2016 00:15:01 +0200 Subject: [PATCH 018/114] fix library get --- system/module/Upload.php | 16 ++++++---------- 1 file changed, 6 insertions(+), 10 deletions(-) diff --git a/system/module/Upload.php b/system/module/Upload.php index cbd605c..ccce643 100644 --- a/system/module/Upload.php +++ b/system/module/Upload.php @@ -412,23 +412,19 @@ public static function get($arr=array()){ // if(isset($arr['library']) || isset($arr['author'])){ - $data = array( + $sql = array( "where" => array() ); if(isset($arr['library'])){ if(is_array($arr['library']))$arr['library'] = implode(",",$arr['library']); - $data['where']['id'] = ":in:".$arr['library']; + $sql['where']['id'] = ":in:".$arr['library']; } if(isset($arr['author'])){ if(is_array($arr['author']))$arr['author'] = implode(",",$arr['author']); - $data['where']['author'] = ":in:".$arr['author']; + $sql['where']['author'] = ":in:".$arr['author']; } - - - return Query::get("library",$data); - } - - if(isset($arr['objects'])){ + + }else if(isset($arr['objects'])){ if(is_array($arr['objects']))$arr['objects'] = implode(",",$arr['objects']); $sql = array( "join" => array( @@ -442,9 +438,9 @@ public static function get($arr=array()){ $sql['join']['relations'] .= " AND relations.taxonomy = '{$arr['taxonomy']}'"; } //if(isset($arr['taxonomy']))$sql['where']['taxonomy'] = $arr['taxonomy']; - return Query::get("library",$sql); } + return Query::get("library",$sql); } // -------------------------------------------------------------------- From 9629dc0cbc4a22eac9d0735209c2aac17ccdd31f Mon Sep 17 00:00:00 2001 From: Tamer Zorba Date: Sat, 6 Feb 2016 04:19:10 +0200 Subject: [PATCH 019/114] whether, neither, repeat, approxlen on Directives --- system/module/Directives.php | 88 ++++++++++++++++++++++++++++++++---- 1 file changed, 79 insertions(+), 9 deletions(-) diff --git a/system/module/Directives.php b/system/module/Directives.php index fe27bfc..5539138 100644 --- a/system/module/Directives.php +++ b/system/module/Directives.php @@ -2,7 +2,7 @@ /** * Purecis Directives Module * - * Append Special Shortcodes to the core + * Append Special Shortcodes to the core * * @package codeHive * @subpackage Module @@ -10,7 +10,7 @@ * @author Tamer Zorba * @link http://purecis.com/ * - * + * * For Nasted directives * Spacial Thanx to http://stackoverflow.com/questions/5438133/how-to-remove-improper-nesting-bbcode-tags-using-php * and http://www.amazon.com/Mastering-Regular-Expressions-Jeffrey-Friedl/dp/0596528124 @@ -24,7 +24,7 @@ * ) # End $2: Contents of URL tag. * (\[/URL\s*+\]) # $3: Outermost closing [/URL] * %six'; - * + * */ class Directives{ @@ -37,6 +37,31 @@ class Directives{ */ public static function __bootstrap(){ + /** + * directive repeat + * Description : repeat data + */ + self::register("repeat", function($args, &$scope) { // TODO : filter by ( like weither) + //print_r($args); + $str = ""; + + foreach(Controller::$scope->{$args->items} as $k => $v){ + Controller::$scope->{$args->as} = $v; + if(is_null($args->{"index"}))Controller::$scope->{"{$ex[0]}Index"} = $k; + else Controller::$scope->{$args->{"index"}} = $k; + Controller::$scope->__index = $k; + $str .= Shortcode::trigger($args->content); + } + print_r($args); + + return $str; + + if($args->items){ + + //if($args->match == $args->equal)return Shortcode::trigger($args->content); + } + + }); /** * directive Each @@ -102,8 +127,6 @@ public static function __bootstrap(){ $v = rtrim($v,"'"); $v = ltrim($v,"'"); return $v; - }else if(is_numeric(trim($v))){ - return $v; }else if(trim($v) == "true"){ return true; }else if(trim($v) == "false"){ @@ -125,6 +148,18 @@ public static function __bootstrap(){ $ex = explode("!=",trim($match[1])); if($parse($ex[0]) != $parse($ex[1]))return Shortcode::trigger($match[2]); + }else if(strpos($match[1], "isset") !== false){ + if(strpos(trim($match[1]),"!") === 0)$not = 1; + else $not = 0; + + $ex = substr(trim($match[1]), 6+$not, -1);//explode("isset",trim()); + + if($not){ + if(is_null($parse($ex)))return Shortcode::trigger($match[2]); + }else{ + if(!is_null($parse($ex)))return Shortcode::trigger($match[2]); + } + } return ; @@ -211,7 +246,7 @@ public static function __bootstrap(){ // if(isset($ex2[1]))$at = $ex2[1]; } - + return Internationalization::translate(trim($ex[0]),$ar,$at); } )); @@ -234,9 +269,34 @@ public static function __bootstrap(){ )); */ + + /** + * directive approxlen + * Description : shorten the text + */ + self::register("approxlen", function($args, &$scope) { + if(!$args->length)$args->length = 200; + if(!$args->append)$args->append = '...'; + return String::approxlen($args->content,$args->length,$args->append); + }); + + /** + * directive whether + * Description : check data + */ + self::register("whether", function($args, &$scope) { //neither // repeat + //print_r($args); + if($args->match){ + if($args->match == $args->equal)return Shortcode::trigger($args->content); + } + // TODO : lt, gt, gte, lte, eq, // extract variable by eval if needed + }); + + } private static function scope($v){ + if(is_numeric(trim($v)))return $v; $val = Controller::$scope; $ex = explode(".", $v); $val = isset($val->$ex[0])?$val->$ex[0]:null; @@ -258,7 +318,7 @@ public static function register($element, $cb){ 'callback' => function($match) use ($cb, $element){ $cls = new stdClass(); $cls->content = $match[2]; - $el = "element_content"; + $el = "{$element}-content"; Controller::$scope->$el = $match[2]; if(!empty($match[1])){ $atts = String::parse_attr($match[1]); @@ -269,10 +329,19 @@ public static function register($element, $cb){ $v = self::scope($v);//Controller::$scope->$v; } $cls->$k = $v; - $el = "element_{$k}"; + $el = "{$element}-{$k}"; Controller::$scope->$el = $v; } } + // whether + if(!is_null($cls->whether)){ + if(!eval("return {$cls->whether};"))return; + } + // neither + if(!is_null($cls->neither)){ + if(eval("return {$cls->neither};"))return; + } + if(is_callable($cb)){ $call = call_user_func_array($cb, array($cls, &Controller::$scope)); @@ -292,7 +361,8 @@ public static function register($element, $cb){ } + } /* End of file Query.php */ -/* Location: ./system/module/Query.php */ \ No newline at end of file +/* Location: ./system/module/Query.php */ From 612bcffb956f2e2209f6e6d51df7772dbf437747 Mon Sep 17 00:00:00 2001 From: Tamer Zorba Date: Sat, 6 Feb 2016 04:21:16 +0200 Subject: [PATCH 020/114] remove logging, forget my mistake --- system/module/Directives.php | 2 -- 1 file changed, 2 deletions(-) diff --git a/system/module/Directives.php b/system/module/Directives.php index 5539138..28671de 100644 --- a/system/module/Directives.php +++ b/system/module/Directives.php @@ -52,8 +52,6 @@ public static function __bootstrap(){ Controller::$scope->__index = $k; $str .= Shortcode::trigger($args->content); } - print_r($args); - return $str; if($args->items){ From 87bcbd6d41caf3db304310a1f30cf86b162f2d05 Mon Sep 17 00:00:00 2001 From: Tamer Zorba Date: Sun, 21 Feb 2016 19:49:19 +0200 Subject: [PATCH 021/114] wheather directive actions --- system/module/Directives.php | 18 +++++++++++++----- 1 file changed, 13 insertions(+), 5 deletions(-) diff --git a/system/module/Directives.php b/system/module/Directives.php index 28671de..d1542f2 100644 --- a/system/module/Directives.php +++ b/system/module/Directives.php @@ -216,7 +216,10 @@ public static function __bootstrap(){ 'code' => 'event', 'pattern' => '#\@event\((.+)\)#Usi', 'callback' => function($match){ - return Event::trigger($match[1]); + $ex = explode(",",$match[1]); + $event = $ex[0]; + array_shift($ex); + return Event::trigger($event,$ex); } )); @@ -283,11 +286,16 @@ public static function __bootstrap(){ * Description : check data */ self::register("whether", function($args, &$scope) { //neither // repeat - //print_r($args); - if($args->match){ - if($args->match == $args->equal)return Shortcode::trigger($args->content); + + if($args->is){ + if($args->eq)if($args->is == $args->eq)return Shortcode::trigger($args->content); + if($args->lt)if($args->is < $args->lt)return Shortcode::trigger($args->content); + if($args->gt)if($args->is > $args->gt)return Shortcode::trigger($args->content); + if($args->lte)if($args->is <= $args->lte)return Shortcode::trigger($args->content); + if($args->gte)if($args->is >= $args->gte)return Shortcode::trigger($args->content); } - // TODO : lt, gt, gte, lte, eq, // extract variable by eval if needed + if($args->exist)return Shortcode::trigger($args->content); + }); From 9fc57fa975d86084b22621f33d70619e674f8232 Mon Sep 17 00:00:00 2001 From: Tamer Zorba Date: Sun, 21 Feb 2016 19:49:55 +0200 Subject: [PATCH 022/114] time support on non essential mode --- system/module/Query.php | 47 +++++++++++++++++++++-------------------- 1 file changed, 24 insertions(+), 23 deletions(-) diff --git a/system/module/Query.php b/system/module/Query.php index 3ee016d..ead5993 100644 --- a/system/module/Query.php +++ b/system/module/Query.php @@ -2,7 +2,7 @@ /** * Purecis Query Module * - * control URL Parameters + * control URL Parameters * * @package codeHive * @subpackage Module @@ -76,6 +76,7 @@ public static function __structure($table=false){ "status" => "varchar(20) NOT NULL DEFAULT ''", "permalink" => "varchar(250) NOT NULL DEFAULT ''", "parent" => "bigint(20) NOT NULL DEFAULT 0", + "time" => "timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP", "taxonomy" => "varchar(50) NOT NULL DEFAULT ''", "rel" => "varchar(50) NOT NULL DEFAULT ''", ], @@ -98,7 +99,7 @@ public static function __structure($table=false){ } // -------------------------------------------------------------------- - + public static function inStructure($col,$table){ global $config; if(isset($config['database']['essential'])){ @@ -113,13 +114,13 @@ public static function inStructure($col,$table){ * Query execute * * @access public - * @param array sql array + * @param array sql array * @return void */ public static function execute($arr){ // todo // terms and library with better join like - // (:term:termname, :library:libname => "data2get,As,Arr,internalMeta") + // (:term:termname, :library:libname => "data2get,As,Arr,internalMeta") global $config; @@ -129,7 +130,7 @@ public static function execute($arr){ } //type, table, data, where, whereSeperator, order, limit if(!isset($arr['type']))$arr['type'] = 'select'; - + $table = $arr['table']; if($arr['type'] == 'select'){ @@ -219,7 +220,7 @@ public static function execute($arr){ if(!isset($arr['join']))$arr['join'] = array(); foreach($arr['where'] as $k => $v){ //fix value - // if array then put or between them + // if array then put or between them if(is_array($v))continue; if(strpos($v, "~") === 0){ @@ -236,7 +237,7 @@ public static function execute($arr){ $v = "`{$v}`"; } } - + //fix key if(!self::inStructure($k, $table)){ $k = trim($k); @@ -254,7 +255,7 @@ public static function execute($arr){ } } } - + switch ( $arr['type'] ) { case 'sql': @@ -309,18 +310,18 @@ public static function execute($arr){ } array_push($sql, implode(", ", $values)); break; - + default://select # code... array_push($sql, "select"); if(isset($arr['data'])){ if(is_array($arr['data']))$arr['data'] = implode(", ", $arr['data']); - array_push($sql, $arr['data']); + array_push($sql, $arr['data']); }else{ array_push($sql, '*'); } - + array_push($sql, "from"); array_push($sql, $arr['table']); break; @@ -371,7 +372,7 @@ public static function execute($arr){ array_push($a,$key." ".$value); } array_push($sql,implode($a,", ")); - + }else{ if(strpos($or, "(")){ array_push($sql, "{$or}"); @@ -389,7 +390,7 @@ public static function execute($arr){ array_push($sql, $limit); } } - + $sql = implode($sql, ' ').";"; // Extra SQL @@ -421,7 +422,7 @@ public static function execute($arr){ } } - if($meta_size > 0){// to get id's + if($meta_size > 0){// to get id's $sid_q = self::execute(array( "table" => $arr['table'], "data" => array('id'), @@ -444,7 +445,7 @@ public static function execute($arr){ $extra = "INSERT INTO meta (`oid`,`key`,`value`,`table`) VALUES "; $extra .= implode(", ",$values); $extra .= "ON DUPLICATE KEY UPDATE `value` = VALUES(`value`);"; - + if($schema_size > 0)$sql .= $extra; else $sql = $extra; } @@ -473,9 +474,9 @@ public static function execute($arr){ } // delete from meta where `oid` = OLD.id and `table` = 'terms'; // as trigger } - + //echo $sql; - + //return array(); return Database::query($sql); } @@ -546,7 +547,7 @@ private static function parse_eq($key,$value,$table){ array_push($temp,"FIND_IN_SET ({$v},`{$key}`)"); } return "(".implode(" {$separator} ", $temp).")"; - + }else if(strpos($value, ":in:") !== false){ $value = stripslashes($value); $value = str_replace(":in:", "", $value); @@ -598,7 +599,7 @@ private static function parse_eq($key,$value,$table){ * Fetching Data from table * * @access public - * @param array sql array + * @param array sql array * @return void */ public static function get($table,$arr=array()){ @@ -637,7 +638,7 @@ public static function get($table,$arr=array()){ * Insert or Update Database table based on where is set * * @access public - * @param array sql array + * @param array sql array * @return void */ public static function set($table,$arr=array()){ @@ -655,7 +656,7 @@ public static function set($table,$arr=array()){ * Delete rows from Table * * @access public - * @param array sql array + * @param array sql array * @return void */ public static function remove($table,$arr=array()){ @@ -670,7 +671,7 @@ public static function remove($table,$arr=array()){ * Query on * * @access public - * @param array sql array + * @param array sql array * @return void */ public static function on($table){ @@ -690,4 +691,4 @@ public static function on($table){ } /* End of file Query.php */ -/* Location: ./system/module/Query.php */ \ No newline at end of file +/* Location: ./system/module/Query.php */ From 6cc0a1c5ce547529fed64fb4f1e78f9a6c040c62 Mon Sep 17 00:00:00 2001 From: Tamer Zorba Date: Sun, 21 Feb 2016 19:50:24 +0200 Subject: [PATCH 023/114] fix event class --- system/core/Event.php | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/system/core/Event.php b/system/core/Event.php index 0956eaf..f7e4cb1 100644 --- a/system/core/Event.php +++ b/system/core/Event.php @@ -44,9 +44,9 @@ public static function addListener($event,$callback){ * * @return function */ - public static function trigger($event){ + public static function trigger($event, $args=false){ $r = ""; - if(isset(self::$events[$event]))foreach(self::$events[$event] as $c)$r .= call_user_func($c); + if(isset(self::$events[$event]))foreach(self::$events[$event] as $c)$r .= call_user_func_array($c, array(&Controller::$scope,$args)); return $r; } -} \ No newline at end of file +} From a8ea12f6f077a31b9a1d478d16d8fdf958707ff6 Mon Sep 17 00:00:00 2001 From: Tamer Zorba Date: Sun, 21 Feb 2016 19:58:56 +0200 Subject: [PATCH 024/114] adding .gitignore --- .gitignore | 71 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 71 insertions(+) create mode 100644 .gitignore diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..1a8cc82 --- /dev/null +++ b/.gitignore @@ -0,0 +1,71 @@ +# exclude everything except directory foo/bar +/* +!/system +!/docs + +!/assets +!/assets/library +/assets/library/* +!/assets/extensions +/assets/extensions/* +/assets/extras +!/assets/cache +/assets/cache/* + +!/apps +/apps/* +!/apps/sample + +!LICENSE.md +!README.md +!robots.txt + +# remove ! if you want to use your own path and project +!index.php +!.htaccess + + +# global files to ignore from https://github.com/github/gitignore/tree/master/Global + +# OSX Git Agnore +.DS_Store +.AppleDouble +.LSOverride + +# Thumbnails +._* + +# Files that might appear in the root of a volume +.DocumentRevisions-V100 +.fseventsd +.Spotlight-V100 +.TemporaryItems +.Trashes +.VolumeIcon.icns + +# Directories potentially created on remote AFP share +.AppleDB +.AppleDesktop +Network Trash Folder +Temporary Items +.apdisk + +# +# Windows image file caches +Thumbs.db +ehthumbs.db + +# Folder config file +Desktop.ini + +# Recycle Bin used on file shares +$RECYCLE.BIN/ + +# Windows Installer files +*.cab +*.msi +*.msm +*.msp + +# Windows shortcuts +*.lnk \ No newline at end of file From e247fb8ba37f29d60c30481679803fbefe9c5d62 Mon Sep 17 00:00:00 2001 From: Tamer Zorba Date: Sun, 21 Feb 2016 23:09:50 +0200 Subject: [PATCH 025/114] sql time update --- system/sql/purecis-v1.0.0.sql | 1 + 1 file changed, 1 insertion(+) diff --git a/system/sql/purecis-v1.0.0.sql b/system/sql/purecis-v1.0.0.sql index 0211238..04b8704 100644 --- a/system/sql/purecis-v1.0.0.sql +++ b/system/sql/purecis-v1.0.0.sql @@ -72,6 +72,7 @@ CREATE TABLE `objects` ( `status` varchar(20) NOT NULL DEFAULT '', `parent` bigint(20) NOT NULL, `taxonomy` varchar(50) NOT NULL DEFAULT '', + `time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, `rel` varchar(50) NOT NULL, PRIMARY KEY (`id`), KEY `author` (`author`), From 64f28c0516a4b380ac9932a690fc8cb546fc2f76 Mon Sep 17 00:00:00 2001 From: Tamer Zorba Date: Mon, 22 Feb 2016 19:30:09 +0200 Subject: [PATCH 026/114] new function src2base --- system/core/Image.php | 19 +++++++++++++++++-- 1 file changed, 17 insertions(+), 2 deletions(-) diff --git a/system/core/Image.php b/system/core/Image.php index e7e5a4c..ce00786 100644 --- a/system/core/Image.php +++ b/system/core/Image.php @@ -2,7 +2,7 @@ /** * Purecis Module Class * - * This class has image parsing controle + * This class has image parsing controle * * @package codeHive * @subpackage Core @@ -91,7 +91,22 @@ public static function watermark($watermark='logo.png',$srcImage='',$target=fals imagedestroy($im); } + // -------------------------------------------------------------------- + /** + * src2base + * + * fix images inside text add base to src + * + * @access public + * @param string contents + * @return string + */ + public static function src2base($html) { + global $config; + $base = Request::base(); + return str_replace("{$config['assets']}/", "{$base}{$config['assets']}/",$html); + } } -?> \ No newline at end of file +?> From 10c9ccd8116573de61f7da837d1d0a5b25d01a9f Mon Sep 17 00:00:00 2001 From: Tamer Zorba Date: Tue, 23 Feb 2016 00:05:27 +0200 Subject: [PATCH 027/114] add ontime function to make date human readable making directive for it --- system/core/String.php | 60 +++++++++++++++++++++++++++++++++++++++--- 1 file changed, 57 insertions(+), 3 deletions(-) diff --git a/system/core/String.php b/system/core/String.php index 7f27040..9f74d13 100644 --- a/system/core/String.php +++ b/system/core/String.php @@ -246,7 +246,7 @@ public static function randomId($len = 8,$characters = false){ if($characters === false)$characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'; $randomString = ''; for($i=0; $i<$len; $i++)$randomString .= $characters[rand(0, strlen($characters) - 1)]; - return $randomString; + return $randomString; } } @@ -329,10 +329,64 @@ public static function xml_parse_attr($att){ $x = new SimpleXMLElement(""); $attr = array(); foreach($x->attributes() as $a => $b)$attr[$a] = trim($b); - + return $attr; } + + // -------------------------------------------------------------------- + + /** + * ontime + * + * diffrent between 2 times + * + * @access public + * @param mixen datetime or unix time ex: (2016-02-22 22:25:43) + * @return array + */ + public static function ontime($bef, $aft=false){ + if(!is_numeric($bef))$bef = strtotime($bef); + if($aft == false)$aft = time(); + if(!is_numeric($aft))$aft = strtotime($aft); + + $timing = $aft-$bef; + + if(($timing/3600)<24){ + $h = floor($timing/3600); + $i = floor(($timing-($h*3600))/60); + + if($i == 0){ + return __("Today")." ".__("A little while ago"); + }else{ + return __("Today")." ".__(":h Hour and :m Minute ago",['h'=>$h,'m'=>$i]); + } + + }else if($timing <= 172800){ + $h = date("h",$bef); + $i = date("i",$bef); + $a = date('a',$bef); + + return __("Yesterday on :h::m :a",['h'=>$h,'m'=>$i,"a"=>$a]); + + }else{ + $days = array( + __('Sunday'), + __('Monday'), + __('Tuesday'), + __('Wednesday'), + __('Thursday'), + __('Friday'), + __('Saturday') + ); + $day = $days[date('w',$bef)]; + $date = date("d/m/Y"); + $time = date("h:i:s"); + $a = date('a',$bef); + return __(":day :date on :time :a",["day"=>$day,"date"=>$date,"time"=>$time,"a"=>$a]); + } + } + } /* End of file String.php */ -/* Location: ./system/core/String.php */ \ No newline at end of file +/* Location: ./system/core/String.php */ From 294f88fd01af7a495e1e0f3341903cb7d95a6d4f Mon Sep 17 00:00:00 2001 From: Tamer Zorba Date: Tue, 23 Feb 2016 00:12:55 +0200 Subject: [PATCH 028/114] ontime directive --- system/module/Directives.php | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/system/module/Directives.php b/system/module/Directives.php index d1542f2..3cf97ba 100644 --- a/system/module/Directives.php +++ b/system/module/Directives.php @@ -281,6 +281,14 @@ public static function __bootstrap(){ return String::approxlen($args->content,$args->length,$args->append); }); + /** + * directive ontime + * Description : date to human readable date + */ + self::register("ontime", function($args, &$scope) { + return String::ontime($args->content); + }); + /** * directive whether * Description : check data From 9a944c8ed97a8ffe151e270d8a872ccc974641d5 Mon Sep 17 00:00:00 2001 From: Tamer Zorba Date: Tue, 23 Feb 2016 00:32:06 +0200 Subject: [PATCH 029/114] update whether to use in --- system/module/Directives.php | 2 ++ 1 file changed, 2 insertions(+) diff --git a/system/module/Directives.php b/system/module/Directives.php index 3cf97ba..300442a 100644 --- a/system/module/Directives.php +++ b/system/module/Directives.php @@ -301,6 +301,8 @@ public static function __bootstrap(){ if($args->gt)if($args->is > $args->gt)return Shortcode::trigger($args->content); if($args->lte)if($args->is <= $args->lte)return Shortcode::trigger($args->content); if($args->gte)if($args->is >= $args->gte)return Shortcode::trigger($args->content); + if($args->in)if(strpos($args->is, $args->in) !== false)return Shortcode::trigger($args->content); + // TODO : inset, } if($args->exist)return Shortcode::trigger($args->content); From 52aef9f887f5624f0d6ede78cca3f4c787b72f52 Mon Sep 17 00:00:00 2001 From: Tamer Zorba Date: Fri, 11 Mar 2016 00:28:03 +0200 Subject: [PATCH 030/114] support timezone --- system/core/codeHive.php | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/system/core/codeHive.php b/system/core/codeHive.php index 104684e..41c9c52 100644 --- a/system/core/codeHive.php +++ b/system/core/codeHive.php @@ -2,7 +2,7 @@ /** * Purecis codeHive Class * - * bootstrap class + * bootstrap class * * @package codeHive * @subpackage Core @@ -57,15 +57,15 @@ public static function start($start = array('app'=>'app')){ if (version_compare(PHP_VERSION, '5.3.0', '<')) { throw new Exception('The codeHive Framework v2 requires PHP version 5.3 or higher, (5.4) is Recomonded.'); } - + define(VersionMajor,"2"); define(VersionMinor,"0"); define(VersionPatch,"00"); define(VersionCode,"Alpha"); define(VersionBuild,"2096"); - + define(VERSION,"v.".VersionMajor.".".VersionMinor.".".VersionPatch." ".VersionCode.", Build ".VersionBuild); - + $config = array(); $config['app'] = $start['app']?:"app"; $config['assets'] = $start['assets']?:"assets"; @@ -79,6 +79,7 @@ public static function start($start = array('app'=>'app')){ define(INDEX_FILE, $config['index']?:'index.php'); define(SESSION_PERFIX, $config['session']?:''); if($config['license'])define(SECURITY_HASH, $config['license']['hash']); + if($config['timezone'])date_default_timezone_set($config['timezone']); // env if ($config['ENVIRONMENT']){ @@ -120,4 +121,4 @@ private static function config($app){ } /* End of file codeHive.php */ -/* Location: ./system/core/codeHive.php */ \ No newline at end of file +/* Location: ./system/core/codeHive.php */ From 9c559255b7e817358227476b3179be6d4270b07f Mon Sep 17 00:00:00 2001 From: Tamer Zorba Date: Fri, 11 Mar 2016 00:37:10 +0200 Subject: [PATCH 031/114] New Query Builder first init and complete select --- system/module/QueryBuilder.php | 292 +++++++++++++++++++++++++++++++++ 1 file changed, 292 insertions(+) create mode 100644 system/module/QueryBuilder.php diff --git a/system/module/QueryBuilder.php b/system/module/QueryBuilder.php new file mode 100644 index 0000000..72ac1a9 --- /dev/null +++ b/system/module/QueryBuilder.php @@ -0,0 +1,292 @@ +table = $table; + return $this; + } + + /** + * set data to query + * @param String $args Mix of data to get + * @return Object QueryBuilder + */ + public function data() + { + $this->data = array_merge($this->data, func_get_args()); + return $this; + } + + public function where() + { + if (strlen($this->where)) { + $this->where .= " AND "; + } + + $args = func_get_args(); + $this->where .= $this->_whereParse($args); + return $this; + } + + public function orWhere() + { + if (strlen($this->where)) { + $this->where .= " OR "; + } + + $args = func_get_args(); + $this->where .= $this->_whereParse($args); + return $this; + } + + /** + * Builder : join + * @return Object QueryBuilder + */ + public function join() + { + $args = func_get_args(); + $this->join .= $this->_joinParse($args); + return $this; + } + + /** + * Builder : group + * @return Object QueryBuilder + */ + public function group() + { + $args = func_get_args(); + $this->group = " GROUP BY " . $this->_col($args[0]); + return $this; + } + + /** + * Builder : order + * @return Object QueryBuilder + */ + public function order() + { + $args = func_get_args(); + if (sizeof($args) == 2) { + $this->order = " ORDER BY " . $this->_col($args[0]) . " {$args[1]}"; + + } else if (sizeof($args) == 1) { + $this->order = " ORDER BY " . $this->_col($args[0]) . " DESC"; + + } else { + $this->order = " ORDER BY " . $this->_col("id") . " DESC"; + + } + return $this; + } + + public function limit() + { + $args = func_get_args(); + if (sizeof($args) == 2) { + $this->limit = " LIMIT {$args[0]}, {$args[1]}"; + } else { + $this->limit = " LIMIT {$args[0]}"; + } + return $this; + } + + /** + * generate select statement + * @return Object SQL Query + */ + private function _get() + { + $args = func_get_args(); + + $this->query = "SELECT "; + $this->query .= $this->_data(); + $this->query .= " FROM "; + $this->query .= $this->_table($this->table); + $this->query .= $this->join; + $this->query .= $this->_where(); + $this->query .= $this->group; + $this->query .= $this->order; + $this->query .= $this->limit; + if(!$args[0])$this->query .= ";"; + return $this->query; + } + + public function get() + { + $this->_get(); + // TODO : make query run here + return $this->query; + } + + private function _table() + { + $args = func_get_args(); + return "`{$args[0]}`"; + } + + private function _col() + { + $args = func_get_args(); + + if (is_callable($args[0])) { + $q = new QueryBuilder(); + call_user_func($args[0], $q); + return "( {$q->_get(true)} )"; + } + + if(strpos($args[0],'~') === 0){ + return $this->_col(substr($args[0],1)); + + }else if(substr_count($args[0],'.') == 1 && !$args[1]){ + $exp = explode(".",$args[0]); + return "`{$exp[0]}`.`{$exp[1]}`"; + + }else if($args[1]){ + if(is_array($args[0]))return "('".implode("', '", $args[0])."')"; + else return "'{$args[0]}'"; + + }else{ + return "`{$this->table}`.`{$args[0]}`"; + + } + } + + private function _data() + { + if (!sizeof($this->data)) { + return "*"; + } + + // else + $arr = array(); + foreach ($this->data as $data) { + array_push($arr, $this->_col($data)); + } + + return implode(", ", $arr); + } + + public function _where() + { + if (!strlen($this->where)) { + return ""; + } + + //else + return " WHERE {$this->where}"; + } + + private function _joinParse($args) + { + if (is_callable($args[0])) { + $q = new QueryBuilder(); + $q->table($this->table); + call_user_func($args[0], $q); + return "( {$q->where} )"; + } + + // TODO : check is function and send the table to create inline where + $str = ""; + + $str .= " JOIN "; + $str .= $this->_table($args[0]); + $str .= " ON "; + array_shift($args); + $str .= call_user_func_array(array($this, "_parseOperators"), $args); + // $str .= $this->_col($args[1]); + // if (!$args[3]) { + // $str .= " = "; + // $str .= $this->_col($args[2]); + // } else { + // $str .= " {$args[2]} "; + // $str .= $this->_col($args[3]); + // } + + return $str; + } + + private function _whereParse($args) + { + if (is_callable($args[0])) { + $q = new QueryBuilder(); + $q->table($this->table); + call_user_func($args[0], $q); + // TODO : check if in to return full query in or it seems next args to check; + return "( {$q->where} )"; + } + + return call_user_func_array(array($this, "_parseOperators"), $args); + } + + private function _parseOperators() + { + $args = func_get_args(); + + $str = ""; + $str .= $this->_col($args[0]); + + switch ($args[1]) { + case '=': + $str .= " = ".$this->_col($args[2],true); + break; + + case '!=': + $str .= " <> ".$this->_col($args[2],true); + break; + + case '<>': + $str .= " <> ".$this->_col($args[2],true); + break; + + case 'in': + $str .= " IN ".$this->_col($args[2],true); + break; + + default: + $str .= " = ".$this->_col($args[1],true); + break; + } + + return $str; + } +} From 54092f1ca97753026c870ec2cb7095f5cdd37ff8 Mon Sep 17 00:00:00 2001 From: Tamer Zorba Date: Fri, 11 Mar 2016 08:44:09 +0200 Subject: [PATCH 032/114] query builder change data to param support as in col support records --- system/module/QueryBuilder.php | 42 +++++++++++++++++++--------- system/module/QueryRecord.php | 50 ++++++++++++++++++++++++++++++++++ 2 files changed, 79 insertions(+), 13 deletions(-) create mode 100644 system/module/QueryRecord.php diff --git a/system/module/QueryBuilder.php b/system/module/QueryBuilder.php index 72ac1a9..2ccc53c 100644 --- a/system/module/QueryBuilder.php +++ b/system/module/QueryBuilder.php @@ -23,16 +23,20 @@ class QueryBuilder * @access protected */ private $table; - private $data = array(); + private $param = array(); public $where = ""; private $join = ""; private $group = ""; private $order = ""; private $limit = ""; private $query; + private $records; // -------------------------------------------------------------------- - + public function __get($property) { + echo "Getting '$property'\n"; + return 123; + } /** * ajax table * @@ -45,13 +49,13 @@ public function table($table) } /** - * set data to query + * set params to query * @param String $args Mix of data to get * @return Object QueryBuilder */ - public function data() + public function param() { - $this->data = array_merge($this->data, func_get_args()); + $this->param = array_merge($this->param, func_get_args()); return $this; } @@ -139,7 +143,7 @@ private function _get() $args = func_get_args(); $this->query = "SELECT "; - $this->query .= $this->_data(); + $this->query .= $this->_param(); $this->query .= " FROM "; $this->query .= $this->_table($this->table); $this->query .= $this->join; @@ -154,8 +158,14 @@ private function _get() public function get() { $this->_get(); - // TODO : make query run here - return $this->query; + return $this->records = Database::query($this->query); + } + + public function record() + { + $this->get(); + Module::import("QueryRecord"); + return new QueryRecord($this->records); } private function _table() @@ -174,9 +184,16 @@ private function _col() return "( {$q->_get(true)} )"; } + $args[0] = trim($args[0]); + if(strpos($args[0],'~') === 0){ return $this->_col(substr($args[0],1)); + }else if(substr_count($args[0],' as ') == 1 && !$args[1]){ + $exp = explode(" as ",$args[0]); + print_r($exp); + return $this->_col($exp[0]). " AS `{$exp[1]}`"; + }else if(substr_count($args[0],'.') == 1 && !$args[1]){ $exp = explode(".",$args[0]); return "`{$exp[0]}`.`{$exp[1]}`"; @@ -187,20 +204,19 @@ private function _col() }else{ return "`{$this->table}`.`{$args[0]}`"; - } } - private function _data() + private function _param() { - if (!sizeof($this->data)) { + if (!sizeof($this->param)) { return "*"; } // else $arr = array(); - foreach ($this->data as $data) { - array_push($arr, $this->_col($data)); + foreach ($this->param as $param) { + array_push($arr, $this->_col($param)); } return implode(", ", $arr); diff --git a/system/module/QueryRecord.php b/system/module/QueryRecord.php new file mode 100644 index 0000000..fa8609b --- /dev/null +++ b/system/module/QueryRecord.php @@ -0,0 +1,50 @@ +records = $records; + return $this; + } + + public function all() + { + return $this->records->data; + } + + public function index($i) + { + return $this->records->data[$i]; + } + + public function first() + { + $this->current = 0; + return $this->records->data[$this->current]; + } + + public function next() + { + $this->current += 1; + return $this->records->data[$this->current]; + } + +} From f738902854187b6561c36428a674afc01744ef9f Mon Sep 17 00:00:00 2001 From: Tamer Zorba Date: Fri, 11 Mar 2016 08:45:25 +0200 Subject: [PATCH 033/114] database connection support object fetching --- system/core/Database.php | 24 ++++++++++++------------ 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/system/core/Database.php b/system/core/Database.php index d1058a2..0a6f505 100644 --- a/system/core/Database.php +++ b/system/core/Database.php @@ -2,7 +2,7 @@ /** * Purecis Database Class * - * This class Manage Database Connections & Queries + * This class Manage Database Connections & Queries * * @package codeHive * @subpackage Core @@ -52,7 +52,7 @@ public static function connect($db_name=null,$db_host=null,$db_user=null,$db_pas $user = $config['database']['user']; $pass = $config['database']['pass']; $port = $config['database']['port']; - + try{ // Checking Database Type… if($type == 'sqlite') self::$db = new PDO("sqlite:{$name}"); @@ -63,12 +63,12 @@ public static function connect($db_name=null,$db_host=null,$db_user=null,$db_pas if($type == 'infomix') self::$db = new PDO("informix:DSN={$name}", $user, $pass); if($type == 'dblib') self::$db = new PDO ("dblib:host={$host}:{$port};dbname={$name}",$user,$pass); if($type == 'odbc') self::$db = new PDO("odbc:Driver={Microsoft Access Driver (*.mdb)};Dbq={$name}"); - + self::$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);//set character set utf8 - + }catch(PDOException $e){ //if($config['ENVIRONMENT'] == 'debug')debug::error("Database Error",$e->getMessage()); - //else + //else die("Database Error :".$e->getMessage()); } } @@ -90,10 +90,10 @@ public static function query($sql){ self::connect(); $return = new stdClass(); try{ - $query = self::$db->query($sql); + $query = self::$db->query($sql); //$query = $link->prepare('SELECT * FROM users WHERE username = :name LIMIT 1;'); //$query->execute([':name' => $username]); # No need to escape it! - + $temp_sql = strtolower($sql); $s = strpos($temp_sql,'select'); $i = strpos($temp_sql,'insert'); @@ -104,25 +104,25 @@ public static function query($sql){ if($u < 10 && $u !== false)$type = 'update'; if($d < 10 && $d !== false)$type = 'delete'; - + $fetch = $config['database']['fetch']=="array"?PDO::FETCH_ASSOC:PDO::FETCH_CLASS; if(in_array($type, array('select','update','delete')))$return->count = $query->rowCount(); - if($type == 'select')$return->data = @$query->fetchAll(PDO::FETCH_ASSOC); + if($type == 'select')$return->data = @$query->fetchAll($fetch); if($type == 'insert')$return->last = self::$db->lastInsertId(); $return->status = true; if($config['ENVIRONMENT'] == 'debug')debug::count('Database Queries'); - + }catch(PDOException $e){ if($config['ENVIRONMENT'] == 'debug')debug::error("Database Error",$e->getMessage()); $return->status = false; $return->error = $e->getMessage(); } - + if(in_array($config['ENVIRONMENT'], array('debug','development')))$return->sql = $sql; return $return; } } /* End of file Database.php */ -/* Location: ./system/core/Database.php */ \ No newline at end of file +/* Location: ./system/core/Database.php */ From da210c29d8b6331f4942044c6b2c597bbbc36626 Mon Sep 17 00:00:00 2001 From: Tamer Zorba Date: Mon, 14 Mar 2016 22:02:57 +0200 Subject: [PATCH 034/114] query builder working on --- system/module/QueryBuilder.php | 284 ++++++++++++++++++++++++++++----- 1 file changed, 242 insertions(+), 42 deletions(-) diff --git a/system/module/QueryBuilder.php b/system/module/QueryBuilder.php index 2ccc53c..09d0bd2 100644 --- a/system/module/QueryBuilder.php +++ b/system/module/QueryBuilder.php @@ -12,6 +12,7 @@ * @category Libraries * @author Tamer Zorba * @link http://purecis.com/ + * @todo shared lock, lock for update */ class QueryBuilder @@ -24,13 +25,16 @@ class QueryBuilder */ private $table; private $param = array(); + // private $ascol = array(); public $where = ""; private $join = ""; - private $group = ""; - private $order = ""; + private $group = array(); + private $order = array(); private $limit = ""; private $query; private $records; + private $union = ""; + public $join_on = ""; // -------------------------------------------------------------------- public function __get($property) { @@ -92,14 +96,39 @@ public function join() return $this; } + public function on() + { + $args = func_get_args(); + if (!strlen($this->join_on)) $str = " ON "; + else $str = " AND "; + + $str .= call_user_func_array(array($this, "_parseOperators"), $args); + + $this->join_on .= $str; + + return $this; + } + + public function orOn() + { + $args = func_get_args(); + if (!strlen($this->join_on)) $str = " ON "; + else $str = " OR "; + + $str .= call_user_func_array(array($this, "_parseOperators"), $args); + + $this->join_on .= $str; + + return $this; + } + /** * Builder : group * @return Object QueryBuilder */ public function group() { - $args = func_get_args(); - $this->group = " GROUP BY " . $this->_col($args[0]); + $this->group = array_merge($this->group, func_get_args()); return $this; } @@ -111,15 +140,16 @@ public function order() { $args = func_get_args(); if (sizeof($args) == 2) { - $this->order = " ORDER BY " . $this->_col($args[0]) . " {$args[1]}"; + array_push($this->order, array($args[0], strtoupper($args[1]))); } else if (sizeof($args) == 1) { - $this->order = " ORDER BY " . $this->_col($args[0]) . " DESC"; + array_push($this->order, [$args[0], "DESC"]); } else { - $this->order = " ORDER BY " . $this->_col("id") . " DESC"; + array_push($this->order, ["id", "DESC"]); } + return $this; } @@ -128,17 +158,36 @@ public function limit() $args = func_get_args(); if (sizeof($args) == 2) { $this->limit = " LIMIT {$args[0]}, {$args[1]}"; + } else { $this->limit = " LIMIT {$args[0]}"; + } + + return $this; + } + + public function union() + { + $args = func_get_args(); + $this->union .= $this->_unionParse($args[0]); + + return $this; + } + + public function unionAll() + { + $args = func_get_args(); + $this->union .= $this->_unionParse($args[0], "ALL "); + return $this; } /** - * generate select statement + * generate SELECT statement * @return Object SQL Query */ - private function _get() + public function _get() { $args = func_get_args(); @@ -148,16 +197,96 @@ private function _get() $this->query .= $this->_table($this->table); $this->query .= $this->join; $this->query .= $this->_where(); - $this->query .= $this->group; - $this->query .= $this->order; + $this->query .= $this->_group(); + $this->query .= $this->_order(); $this->query .= $this->limit; + $this->query .= $this->union; if(!$args[0])$this->query .= ";"; return $this->query; } public function get() { - $this->_get(); + return $this->_get(); + return $this->records = Database::query($this->query); + } + + /** + * generate INSERT, UPDATE statement + * @return Object SQL Query + */ + private function _set() + { + $args = func_get_args(); + + if (!strlen($this->where)) { + $this->query = "INSERT INTO "; + $this->query .= $this->_table($this->table); + $this->query .= " (".$this->_param("insert",1).")"; + $this->query .= " VALUES"; + $this->query .= " (".$this->_param("insert",2).")"; + + }else{ + $this->query = "UPDATE "; + $this->query .= $this->_table($this->table); + $this->query .= " SET "; + $this->query .= $this->_param("update"); + $this->query .= $this->join; + $this->query .= $this->_where(); + } + + $this->query .= ";"; + + return $this->query; + } + + public function set() + { + $this->_set(); + return $this->query; + return $this->records = Database::query($this->query); + } + + /** + * generate DELETE statement + * @return Object SQL Query + */ + private function _delete() + { + $this->query = "DELETE FROM "; + $this->query .= $this->_table($this->table); + $this->query .= $this->_where(); + $this->query .= $this->_order(); + $this->query .= $this->limit; + $this->query .= ";"; + + return $this->query; + } + + public function delete() + { + $this->_delete(); + return $this->query; + return $this->records = Database::query($this->query); + } + + /** + * generate TRUNCATE statement + * @return Object SQL Query + */ + private function _truncate() + { + $this->query = "TRUNCATE TABLE "; + $this->query .= $this->_table($this->table); + $this->query .= ";"; + + return $this->query; + } + + public function truncate() + { + $this->_truncate(); + return $this->query; return $this->records = Database::query($this->query); } @@ -178,6 +307,16 @@ private function _col() { $args = func_get_args(); + if(is_array($args[0])){ + $temp = array(); + foreach($args as $arg){ + foreach($arg as $param){ + array_push($temp, $this->_col($param)); + } + } + return $temp; + } + if (is_callable($args[0])) { $q = new QueryBuilder(); call_user_func($args[0], $q); @@ -191,32 +330,85 @@ private function _col() }else if(substr_count($args[0],' as ') == 1 && !$args[1]){ $exp = explode(" as ",$args[0]); - print_r($exp); + // array_push($this->ascol, $exp[1]); return $this->_col($exp[0]). " AS `{$exp[1]}`"; + // }else if(in_array($args[0],$this->ascol)){ + // return $this->_col($args[0],"single"); + }else if(substr_count($args[0],'.') == 1 && !$args[1]){ $exp = explode(".",$args[0]); return "`{$exp[0]}`.`{$exp[1]}`"; - }else if($args[1]){ + }else if($args[1] == "single"){ + return "`{$args[0]}`"; + + }else if($args[1] == "string"){ if(is_array($args[0]))return "('".implode("', '", $args[0])."')"; - else return "'{$args[0]}'"; + else return "'".String::escape($args[0])."'"; }else{ return "`{$this->table}`.`{$args[0]}`"; } } + private function _group() + { + $args = func_get_args(); + $arr = array(); + + if (!sizeof($this->group)) { + return ""; + } + + foreach ($this->group as $col) { + array_push($arr, $this->_col($col)); + } + + return " GROUP BY " . implode(", ", $arr); + } + + private function _order() + { + $args = func_get_args(); + $arr = array(); + + if (!sizeof($this->order)) { + return ""; + } + + foreach ($this->order as $col) { + array_push($arr, $this->_col($col[0]) . " {$col[1]}"); + } + + return " ORDER BY " . implode(", ", $arr); + } + private function _param() { + $args = func_get_args(); + $arr = array(); + if (!sizeof($this->param)) { return "*"; } - // else - $arr = array(); - foreach ($this->param as $param) { - array_push($arr, $this->_col($param)); + //$this->param = $this->_col($this->param); + + if($args[0] == 'insert'){ + for ($i = $args[1]-1; $i < sizeof($this->param); $i+=2) { + array_push($arr, $this->_col($this->param[$i],$args[1]==1?"single":"string")); + } + + }else if($args[0] == 'update'){ + for ($i = 0; $i < sizeof($this->param); $i+=2) { + array_push($arr, $this->_col($this->param[$i],"single")." = ".$this->_col($this->param[$i+1],"string")); + } + + }else{ + foreach ($this->param as $param) { + array_push($arr, $this->_col($param)); + } } return implode(", ", $arr); @@ -232,31 +424,40 @@ public function _where() return " WHERE {$this->where}"; } - private function _joinParse($args) + private function _unionParse($args) { - if (is_callable($args[0])) { + $args = func_get_args(); + + if($args[0] instanceof QueryBuilder){ + return " UNION {$args[1]}" . $args[0]->_get(true); + + }else if (is_callable($args[0])) { $q = new QueryBuilder(); - $q->table($this->table); call_user_func($args[0], $q); - return "( {$q->where} )"; + return " UNION $args[1]" . $q->_get(true); + } - // TODO : check is function and send the table to create inline where - $str = ""; + return ""; + } - $str .= " JOIN "; + private function _joinParse($args) + { + $this->join_on = ""; + $str = " JOIN "; $str .= $this->_table($args[0]); - $str .= " ON "; array_shift($args); - $str .= call_user_func_array(array($this, "_parseOperators"), $args); - // $str .= $this->_col($args[1]); - // if (!$args[3]) { - // $str .= " = "; - // $str .= $this->_col($args[2]); - // } else { - // $str .= " {$args[2]} "; - // $str .= $this->_col($args[3]); - // } + // $str .= call_user_func_array(array($this, "_parseOperators"), $args); + + if (is_callable($args[0])) { + $q = new QueryBuilder(); + $q->table($this->table); + call_user_func($args[0], $q); + return $q->join_on; + }else{ + $this->on($args); + $str .= $this->join_on; + } return $str; } @@ -267,7 +468,6 @@ private function _whereParse($args) $q = new QueryBuilder(); $q->table($this->table); call_user_func($args[0], $q); - // TODO : check if in to return full query in or it seems next args to check; return "( {$q->where} )"; } @@ -283,23 +483,23 @@ private function _parseOperators() switch ($args[1]) { case '=': - $str .= " = ".$this->_col($args[2],true); + $str .= " = ".$this->_col($args[2],"string"); break; case '!=': - $str .= " <> ".$this->_col($args[2],true); + $str .= " <> ".$this->_col($args[2],"string"); break; case '<>': - $str .= " <> ".$this->_col($args[2],true); + $str .= " <> ".$this->_col($args[2],"string"); break; case 'in': - $str .= " IN ".$this->_col($args[2],true); + $str .= " IN ".$this->_col($args[2],"string"); break; default: - $str .= " = ".$this->_col($args[1],true); + $str .= " = ".$this->_col($args[1],"string"); break; } From 8175dd0c5f2bcde7cd1091f658feb31e91aa4a89 Mon Sep 17 00:00:00 2001 From: Tamer Zorba Date: Tue, 15 Mar 2016 14:46:12 +0200 Subject: [PATCH 035/114] support truncate in database class --- system/core/Database.php | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/system/core/Database.php b/system/core/Database.php index 0a6f505..e0624b6 100644 --- a/system/core/Database.php +++ b/system/core/Database.php @@ -99,13 +99,15 @@ public static function query($sql){ $i = strpos($temp_sql,'insert'); $u = strpos($temp_sql,'update'); $d = strpos($temp_sql,'delete'); + $t = strpos($temp_sql,'truncate'); if($s < 10 && $s !== false)$type = 'select'; if($i < 10 && $i !== false)$type = 'insert'; if($u < 10 && $u !== false)$type = 'update'; if($d < 10 && $d !== false)$type = 'delete'; + if($d < 10 && $d !== false)$type = 'truncate'; $fetch = $config['database']['fetch']=="array"?PDO::FETCH_ASSOC:PDO::FETCH_CLASS; - if(in_array($type, array('select','update','delete')))$return->count = $query->rowCount(); + if(in_array($type, array('select','update','delete','truncate')))$return->count = $query->rowCount(); if($type == 'select')$return->data = @$query->fetchAll($fetch); if($type == 'insert')$return->last = self::$db->lastInsertId(); From 244d53c6c19dd6ecfe1705da6a7cd4840c32c5b2 Mon Sep 17 00:00:00 2001 From: Tamer Zorba Date: Tue, 15 Mar 2016 14:48:58 +0200 Subject: [PATCH 036/114] fix join on query builder --- system/module/QueryBuilder.php | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/system/module/QueryBuilder.php b/system/module/QueryBuilder.php index 09d0bd2..9f459f8 100644 --- a/system/module/QueryBuilder.php +++ b/system/module/QueryBuilder.php @@ -207,7 +207,7 @@ public function _get() public function get() { - return $this->_get(); + $this->_get(); return $this->records = Database::query($this->query); } @@ -447,7 +447,6 @@ private function _joinParse($args) $str = " JOIN "; $str .= $this->_table($args[0]); array_shift($args); - // $str .= call_user_func_array(array($this, "_parseOperators"), $args); if (is_callable($args[0])) { $q = new QueryBuilder(); @@ -455,7 +454,7 @@ private function _joinParse($args) call_user_func($args[0], $q); return $q->join_on; }else{ - $this->on($args); + call_user_func_array(array($this, "on"), $args); $str .= $this->join_on; } From 5f0ccdda82cfbdef388448a9a449dcea45a4a270 Mon Sep 17 00:00:00 2001 From: Tamer Zorba Date: Tue, 15 Mar 2016 15:57:41 +0200 Subject: [PATCH 037/114] add some operators and fix array string col --- system/module/QueryBuilder.php | 75 +++++++++++++++++++++++++++++++--- 1 file changed, 70 insertions(+), 5 deletions(-) diff --git a/system/module/QueryBuilder.php b/system/module/QueryBuilder.php index 9f459f8..4d6e8e6 100644 --- a/system/module/QueryBuilder.php +++ b/system/module/QueryBuilder.php @@ -307,7 +307,7 @@ private function _col() { $args = func_get_args(); - if(is_array($args[0])){ + if(is_array($args[0]) && $args[1] != "string"){ $temp = array(); foreach($args as $arg){ foreach($arg as $param){ @@ -323,7 +323,7 @@ private function _col() return "( {$q->_get(true)} )"; } - $args[0] = trim($args[0]); + if(!is_array($args[0]))$args[0] = trim($args[0]); if(strpos($args[0],'~') === 0){ return $this->_col(substr($args[0],1)); @@ -478,25 +478,90 @@ private function _parseOperators() $args = func_get_args(); $str = ""; - $str .= $this->_col($args[0]); + + if(!in_array($args[1], array("set", "inset"))) + $str .= $this->_col($args[0]); switch ($args[1]) { case '=': $str .= " = ".$this->_col($args[2],"string"); break; - case '!=': - $str .= " <> ".$this->_col($args[2],"string"); + case 'like': + $str .= " LIKE ".$this->_col($args[2],"string"); break; + case '!=': + $str .= " != ".$this->_col($args[2],"string"); + break; + case '<>': $str .= " <> ".$this->_col($args[2],"string"); break; + case 'lt': + case '<': + case '!>': + $str .= " < ".$this->_col($args[2],"string"); + break; + + case 'lte': + case '<=': + $str .= " <= ".$this->_col($args[2],"string"); + break; + + case 'lg': + case '>': + case '!<': + $str .= " > ".$this->_col($args[2],"string"); + break; + + case 'lge': + case '>=': + $str .= " > ".$this->_col($args[2],"string"); + break; + + case 'is': + $str .= " IS ".strtoupper($args[2]); + break; + case 'in': $str .= " IN ".$this->_col($args[2],"string"); break; + case 'notin': + $str .= " NOT IN ".$this->_col($args[2],"string"); + break; + + case 'bet': + case 'between': + case '><': + case 'notbet': + case 'notbetween': + case '!><': + + $b = in_array($args[1], array("between", "bet", "><")) ? "BETWEEN" : "NOT BETWEEN"; + + if(is_array($args[2])){ + $str .= " {$b} " . $this->_col($args[2][0],"string") . " AND " . $this->_col($args[2][1],"string"); + }else{ + $str .= " {$b} " . $this->_col($args[2],"string") . " AND " . $this->_col($args[3],"string"); + } + break; + + case 'set': + case 'inset': + if(is_array($args[2])){ + $temp = array(); + foreach($args[2] as $v){ + array_push($temp, "FIND_IN_SET (".$this->_col($v,"string").",".$this->_col($args[0]).")"); + } + $str .= "( " . implode(" AND ", $temp) . ")"; + }else{ + $str .= "FIND_IN_SET (".$this->_col($args[2],"string").",".$this->_col($args[0]).")"; + } + break; + default: $str .= " = ".$this->_col($args[1],"string"); break; From 335739679bc169d247d53be85def12d704c7deaa Mon Sep 17 00:00:00 2001 From: Tamer Zorba Date: Sun, 20 Mar 2016 21:54:00 +0200 Subject: [PATCH 038/114] allow query builder to accept capital and small letters --- system/module/QueryBuilder.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/system/module/QueryBuilder.php b/system/module/QueryBuilder.php index 4d6e8e6..635a587 100644 --- a/system/module/QueryBuilder.php +++ b/system/module/QueryBuilder.php @@ -482,7 +482,7 @@ private function _parseOperators() if(!in_array($args[1], array("set", "inset"))) $str .= $this->_col($args[0]); - switch ($args[1]) { + switch (strtolower($args[1])) { case '=': $str .= " = ".$this->_col($args[2],"string"); break; From f1deebbdb8733d9e62d204bed0ad8bf1f0c636b5 Mon Sep 17 00:00:00 2001 From: Tamer Zorba Date: Wed, 30 Mar 2016 16:31:04 +0300 Subject: [PATCH 039/114] fix database error view in debugger --- system/core/Database.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/system/core/Database.php b/system/core/Database.php index e0624b6..1be7828 100644 --- a/system/core/Database.php +++ b/system/core/Database.php @@ -116,7 +116,7 @@ public static function query($sql){ if($config['ENVIRONMENT'] == 'debug')debug::count('Database Queries'); }catch(PDOException $e){ - if($config['ENVIRONMENT'] == 'debug')debug::error("Database Error",$e->getMessage()); + if($config['ENVIRONMENT'] == 'debug')debug::error("Database Error",String::escape($e->getMessage())); $return->status = false; $return->error = $e->getMessage(); } From b87bf907615e86639a5e264e0517aa77c77331fa Mon Sep 17 00:00:00 2001 From: Tamer Zorba Date: Wed, 30 Mar 2016 18:48:29 +0300 Subject: [PATCH 040/114] Assets update Assets : add private string parser Assets : better calling for Events as string Assets : change Events to Hooks Assets : use PSR-2 --- system/core/Assets.php | 344 ++++++++++++++++++++++------------------- 1 file changed, 183 insertions(+), 161 deletions(-) diff --git a/system/core/Assets.php b/system/core/Assets.php index 13cffba..98a939d 100644 --- a/system/core/Assets.php +++ b/system/core/Assets.php @@ -1,164 +1,186 @@ - + * @copyright Copyright (c) 2013 - 2016, PureCore International Solutions (http://purecis.com/) + * @license http://opensource.org/licenses/MIT MIT License + * + * @link http://codehive.purecis.com/package/Assets + * @since File available since Release 2.0.0 + * + * @version V: 2.1.0 */ - -class Assets{ - - protected static $code = array("var codeHive = codeHive || {};"); - protected static $codev = array(); - - public static function __bootstrap(){ - // define globals (create function to globals .. call on listener & v get) - global $config; - self::define("path","{}"); - self::define("path.base",Request::base()); - self::define("path.app",Request::base($config['app'])); - self::define("path.view",Request::base("{$config['app']}/view")); - self::define("path.vendor",Request::base("{$config['app']}/vendor")); - self::define("path.library",Request::base("{$config['assets']}/library")); - self::define("path.domain",Request::domain()); - - Event::addListener('defaults',function(){ - - // parse code - $code = implode("\n\t\t", self::$code); - return "\n\t"; - }); - } - - /** - * define javascript code - * - * @return void - */ - public static function define($a,$b,$c=false){ - self::$codev[$a] = $b; - - if($b != "{}" && $b != "[]"){ - $b = "'{$b}'"; - }else{ - $b = "codeHive.{$a} || {$b}"; - } - - if(!$c){ - $b = " = {$b}"; - }else{ - $b = ".{$c}({$b})"; - } - - array_push(self::$code,"codeHive.{$a}{$b};"); - } - - /** - * get defined all variables - * - * @return void - */ - public static function variables(){ - return self::$codev; - } - - // TODO : load folder ( scripts ) - - /** - * load script - * - * @return void - */ - public static function script($src,$folder="vendor",$listener='script'){ - global $config; - - - $external = explode("://", $src);// chk external - if(sizeof($external) <= 1){ - - $ex = explode("@",$src); - $path = (sizeof($ex) > 1)?Module::path($ex[1]):false; - if(!$path)$path = "{$config['app']}"; - else $src = $ex[0]; - - $path = Request::base($path); - $src = "{$path}/{$folder}/{$src}"; - } - - Event::addListener($listener,function() use ($src){ - return "\n\t"; - }); - } - - /** - * style load - * - * @return void - */ - public static function style($src,$folder="vendor",$listener='style'){ - global $config; - - $external = explode("://", $src);// chk external - if(sizeof($external) <= 1){ - - $ex = explode("@",$src); - $path = (sizeof($ex) > 1)?Module::path($ex[1]):false; - if(!$path)$path = "{$config['app']}"; - else $src = $ex[0]; - - $path = Request::base($path); - - $src = "{$path}/{$folder}/{$src}"; - } - - $extra = File::extension($src)=='less'?'/less':""; - - Event::addListener($listener,function() use ($src, $extra){ - return "\n\t"; - }); - } - - /** - * element load - * - * @return void - */ - public static function element($src,$folder="vendor",$listener='element'){ - global $config; - - $external = explode("://", $src);// chk external - if(sizeof($external) <= 1){ - - $ex = explode("@",$src); - $path = (sizeof($ex) > 1)?Module::path($ex[1]):false; - if(!$path)$path = "{$config['app']}"; - else $src = $ex[0]; - - $path = Request::base($path); - - if(!strpos($src, "."))$src="{$src}/{$src}.html"; - - $src = "{$path}/{$folder}/{$src}"; - } - - $extra = File::extension($src)=='less'?'/less':""; - - Event::addListener($listener,function() use ($src, $extra){ - return "\n\t"; - }); - } - - /** - * style load - * - * @return void - */ - public static function vendor($src=''){ - global $config; - - return Request::base("{$config['app']}/vendor{$src}"); - } -} \ No newline at end of file +class Assets +{ + /** + * initialize js code. + */ + protected static $code = array('var codeHive = codeHive || {};'); + + /** + * code variables. + */ + protected static $codev = array(); + + /** + * codeHive Assets class constructor. + * + * define javascript default path values from codeHive + */ + public static function __bootstrap() + { + // define globals (create function to globals .. call on listener & v get) + global $config; + self::define('path', '{}'); + self::define('path.base', Request::base()); + self::define('path.app', Request::base($config['app'])); + self::define('path.view', Request::base("{$config['app']}/view")); + self::define('path.vendor', Request::base("{$config['app']}/vendor")); + self::define('path.library', Request::base("{$config['assets']}/library")); + self::define('path.domain', Request::domain()); + + Hook::on('script', function () { + $code = implode("\n\t\t", self::$code); + + return "\n\t"; + }); + Hook::on('defaults', "\n\t"); + Hook::on('defaults', "\n\t"); + Hook::on('defaults', "\n\t"); + } + + /** + * define javascript code. + * + * @param string $a path + * @param Mixen $b equality + * @param string $c method + */ + public static function define($a, $b, $c = false) + { + self::$codev[$a] = $b; + + if ($b != '{}' && $b != '[]') { + $b = "'{$b}'"; + } else { + $b = "codeHive.{$a} || {$b}"; + } + + if (!$c) { + $b = " = {$b}"; + } else { + $b = ".{$c}({$b})"; + } + + array_push(self::$code, "codeHive.{$a}{$b};"); + } + + /** + * get defined all variables. + * + * @return array List of all defintions + */ + public static function variables() + { + return self::$codev; + } + + /** + * Parse Source string Load assets. + * + * @param string $src Path of js file + * @param string $folder default load folder + * @param string $ext extension to load inside folder + * + * @return string + */ + private static function src_parser($src, $folder, $ext = false) + { + global $config; + if (strpos($src, '://') === false) { // check is external + $ex = explode('@', $src); + $path = (sizeof($ex) > 1) ? Module::path($ex[1]) : false; + if (!$path) { + $path = "{$config['app']}"; + } else { + $src = $ex[0]; + } + $path = Request::base($path); + if (!strpos($src, '.') && $ext) { + $src = "{$src}/{$src}.{$ext}"; + } + $src = "{$path}/{$folder}/{$src}"; + } + + return $src; + } + + /** + * Register Hook to Load script. + * + * @param string $src Path of js file + * @param string $folder default load folder + * @param string $listener default listener name + */ + public static function script($src, $folder = 'vendor', $listener = 'script') + { + $src = self::src_parser($src, $folder); + Hook::on($listener, "\n\t"); + } + + /** + * Register Hook to Load style. + * + * @param string $src Path of js file + * @param string $folder default load folder + * @param string $listener default listener name + */ + public static function style($src, $folder = 'vendor', $listener = 'style') + { + $src = self::src_parser($src, $folder); + $extra = File::extension($src) == 'less' ? '/less' : ''; + // TODO : make less and scss as plugins or hooks to fetch + + Hook::on($listener, "\n\t"); + } + + /** + * Register Hook to Load element. + * + * @param string $src Path of js file + * @param string $folder default load folder + * @param string $listener default listener name + */ + public static function element($src, $folder = 'vendor', $listener = 'element') + { + $src = self::src_parser($src, $folder, 'html'); + $extra = File::extension($src) == 'less' ? '/less' : ''; + + Hook::addListener($listener, "\n\t"); + } + + /** + * get file source in vendor. + * + * @param string $src Path of js file + * + * @return string path + */ + public static function vendor($src = '') + { + global $config; + + return Request::base("{$config['app']}/vendor{$src}"); + } +} + +/* End of file Assets.php */ +/* Location: ./system/core/Assets.php */ From f8f27c2482b325676615b03390c4c1e68051364e Mon Sep 17 00:00:00 2001 From: Tamer Zorba Date: Wed, 30 Mar 2016 18:49:08 +0300 Subject: [PATCH 041/114] Benchmark update Benchmark : use stdClass as default instead of array Benchmark : use PSR-2 --- system/core/Benchmark.php | 115 ++++++++++++++++++++------------------ 1 file changed, 61 insertions(+), 54 deletions(-) diff --git a/system/core/Benchmark.php b/system/core/Benchmark.php index 401b0fb..572491b 100644 --- a/system/core/Benchmark.php +++ b/system/core/Benchmark.php @@ -1,69 +1,76 @@ - + * @copyright Copyright (c) 2013 - 2016, PureCore International Solutions (http://purecis.com/) + * @license http://opensource.org/licenses/MIT MIT License + * + * @link http://codehive.purecis.com/package/Benchmark + * @since File available since Release 2.0.0 + * + * @version V: 2.1.0 */ +class Benchmark +{ + /** + * List of benchmarks. + */ + protected static $benchmarks = array(); + + // -------------------------------------------------------------------- -class Benchmark{ + /** + * Benchmark Start. + * + * @param string Benchmark name + * + * @return array + */ + public static function start($name) + { + self::$benchmarks[$name] = new stdClass(); + self::$benchmarks[$name]->time = microtime(true); + self::$benchmarks[$name]->memory = memory_get_usage(); - /** - * List of benchmarks - * - * @var array - * @access protected - */ - protected static $Benchmarks = array(); + return self::$benchmarks[$name]; + } - // -------------------------------------------------------------------- + // -------------------------------------------------------------------- - /** - * Benchmark Start - * - * @access public - * @param string Benchmark name - * @return array - */ - public static function start($name){ - self::$Benchmarks[$name] = array(); - self::$Benchmarks[$name]['time'] = microtime(true); - self::$Benchmarks[$name]['memory'] = memory_get_usage(); - return self::$Benchmarks[$name]; - } + /** + * Benchmark Complete. + * + * @param string Benchmark name + * + * @return array + */ + public static function complete($name) + { + global $config; - // -------------------------------------------------------------------- + $end = new stdClass(); + $end->time = microtime(true); + $end->memory = memory_get_usage(); - /** - * Benchmark Complete - * - * @access public - * @param string Benchmark name - * @return array - */ - public static function complete($name){ - global $config; - - $arr = array( - "time" => microtime(true), - "memory" => memory_get_usage() - ); - if($config['ENVIRONMENT'] == 'debug'){ - $time = round($arr['time']-self::$Benchmarks[$name]['time'],4); - $memory = $arr['memory'] - self::$Benchmarks[$name]['memory']; - $memory = $memory." - ".File::format($memory); + if ($config['ENVIRONMENT'] == 'debug') { + $time = round($end->time - self::$benchmarks[$name]->time, 4); + $memory = $end->memory - self::$benchmarks[$name]->memory; + $memory = $memory.' - '.File::format($memory); - debug::error("Benchmark {$name}","Time : {$time} | Memory : {$memory}"); - } - return $arr; - } + Debug::error("Benchmark {$name}", "Time : {$time} | Memory : {$memory}"); + } + return $arr; + } } /* End of file Benchmark.php */ -/* Location: ./system/core/Benchmark.php */ \ No newline at end of file +/* Location: ./system/core/Benchmark.php */ From f3126d1b5ffb7fb3ddf6c66e1170bf149598bf6f Mon Sep 17 00:00:00 2001 From: Tamer Zorba Date: Wed, 30 Mar 2016 18:49:23 +0300 Subject: [PATCH 042/114] Event : accept string to callback --- system/core/Event.php | 87 +++++++++++++++++++++++++------------------ 1 file changed, 51 insertions(+), 36 deletions(-) diff --git a/system/core/Event.php b/system/core/Event.php index f7e4cb1..a8f0336 100644 --- a/system/core/Event.php +++ b/system/core/Event.php @@ -1,52 +1,67 @@ - Date: Wed, 30 Mar 2016 18:49:37 +0300 Subject: [PATCH 043/114] Internationalization : the __ alias require initialize this module --- system/core/Internationalization.php | 380 ++++++++++++++------------- 1 file changed, 204 insertions(+), 176 deletions(-) diff --git a/system/core/Internationalization.php b/system/core/Internationalization.php index e6f11df..9448897 100644 --- a/system/core/Internationalization.php +++ b/system/core/Internationalization.php @@ -1,187 +1,215 @@ - $v) { + $arr[":{$k}"] = $v; + } + $msg = strtr($msg, $arr); + + //$msg = preg_replace('/:(\w+)/e', 'isset($args["$1"])?$args["$1"]:0', $msg); + + return $msg; + } + + // -------------------------------------------------------------------- + + /** + * Locale Parse. + * + * @param mixen str or array keys only + * + * @return mixen + */ + private static function parse($msg_arr, $args) + { + foreach ($msg_arr as $exp => $msg) { + if (self::plural($exp, $args)) { + if (is_array($msg)) { + return self::parse($msg, $args); + } else { + return $msg; + } + } + } + + return false; + } + + // -------------------------------------------------------------------- + + /** + * Locale plural. + * + * @param mixen str or array keys only + * + * @return mixen + */ + private static function plural($exp, $args) + { + $exp = explode(':', $exp); + + if (!isset($args[$exp[0]])) { + return false; + } + + if ($exp[1] == 'eq') { + return $args[$exp[0]] == $exp[2]; + } elseif ($exp[1] == 'gt') { + return $args[$exp[0]] > $exp[2]; + } elseif ($exp[1] == 'gte') { + return $args[$exp[0]] >= $exp[2]; + } elseif ($exp[1] == 'lt') { + return $args[$exp[0]] < $exp[2]; + } elseif ($exp[1] == 'lte') { + return $args[$exp[0]] <= $exp[2]; + } elseif ($exp[1] == 'zero') { + return $args[$exp[0]] == 0; + } elseif ($exp[1] == 'one') { + return $args[$exp[0]] == 1; + } elseif ($exp[1] == 'few') { + return $args[$exp[0]] >= 2 && $args[$exp[0]] <= 4; + } elseif ($exp[1] == 'other') { + return true; + } + + return false; + } + + // -------------------------------------------------------------------- + + /** + * Locale prepare. + * + * @param mixen str or array keys only + * + * @return mixen + */ + public static function prepare($space = false, $force = false) + { + global $config; + + $locale = Session::exist('locale') ? Session::get('locale') : (isset($config['locale']) ? $config['locale'] : self::$locale); + + if ($space) { + if ($force) { + Module::import($space); + } + $path = Module::path($space)."/language/{$locale}"; + } else { + $path = "{$config['app']}/language/{$locale}"; + if (!file_exists($path)) { + $path = "{$config['app']}/locale/{$locale}"; + } + if (!file_exists($path)) { + $path = "{$config['system']}/language/{$locale}"; + } + } + if (!is_dir($path)) { + if ($config['ENVIRONMENT'] == 'debug') { + debug::error('Missing Locales', $space); + } + //else die("Locales at {$space} not Found."); + + return; + } + + foreach (glob("{$path}/*.php") as $filename) { + $lng = self::localeFile($filename); + if (!is_array($lng)) { + return false; + } + if (!$space) { + self::$phrases = array_merge(self::$phrases, $lng); + } else { + if (!is_array(self::$phrases_space[$space])) { + self::$phrases_space[$space] = array(); + } + self::$phrases_space[$space] = array_merge(self::$phrases_space[$space], $lng); + } + } + + if (!$space) { + return self::$phrases; + } else { + return self::$phrases_space[$space]; + } + } + + private static function localeFile($filename) + { + return require_once $filename; + } + + public static function requestLocale($locale = 'locale') + { + if (Request::get($locale)) { + Session::set(array('locale' => Request::get($locale))); + } + } +} -class Internationalization{ - - /** - * @var array - * @access protected - */ - protected static $phrases = array(); - protected static $phrases_space = array(); - public static $locale = 'en-us'; - - // -------------------------------------------------------------------- - - /** - * Locale translate - * - * @access public - * @param mixen str or array keys only - * @return mixen - */ - public static function translate($msg, $args=array(),$space=false){ - self::prepare($space); - - if(!$space){ - $localeArr = isset(self::$phrases[$msg])?self::$phrases[$msg]:$msg; - }else{ - $localeArr = isset(self::$phrases_space[$space][$msg])?self::$phrases_space[$space][$msg]:$msg; - } - - if(is_array($localeArr)){ - $parsing = self::parse($localeArr,$args); - if($parsing)$msg = $parsing; - - }else if(is_string($localeArr)){ - $msg = $localeArr; - - } - - // we use this bcz preg_replace Modifier /e deprecated - $arr = array(); - foreach($args as $k => $v)$arr[":{$k}"] = $v; - $msg = strtr($msg,$arr); - - //$msg = preg_replace('/:(\w+)/e', 'isset($args["$1"])?$args["$1"]:0', $msg); - - - return $msg; - } - - // -------------------------------------------------------------------- - - /** - * Locale Parse - * - * @access private - * @param mixen str or array keys only - * @return mixen - */ - private static function parse($msg_arr, $args){ - foreach($msg_arr as $exp => $msg){ - if(self::plural($exp,$args)){ - if(is_array($msg)){ - - return self::parse($msg,$args); - }else{ - - return $msg; - } - } - } - return false; - } - - // -------------------------------------------------------------------- - - /** - * Locale plural - * - * @access private - * @param mixen str or array keys only - * @return mixen - */ - private static function plural($exp, $args){ - - $exp = explode(":",$exp); - - if(!isset($args[$exp[0]]))return false; - - if($exp[1] == 'eq'){ - return $args[$exp[0]] == $exp[2]; - - }else if($exp[1] == 'gt'){ - return $args[$exp[0]] > $exp[2]; - - }else if($exp[1] == 'gte'){ - return $args[$exp[0]] >= $exp[2]; - - }else if($exp[1] == 'lt'){ - return $args[$exp[0]] < $exp[2]; - - }else if($exp[1] == 'lte'){ - return $args[$exp[0]] <= $exp[2]; - - }else if($exp[1] == 'zero'){ - return $args[$exp[0]] == 0; - - }else if($exp[1] == 'one'){ - return $args[$exp[0]] == 1; - - }else if($exp[1] == 'few'){ - return ($args[$exp[0]] >= 2 && $args[$exp[0]] <= 4); - - }else if($exp[1] == 'other'){ - return true; - } - - return false; - } - - // -------------------------------------------------------------------- - - /** - * Locale prepare - * - * @access public - * @param mixen str or array keys only - * @return mixen - */ - public static function prepare($space=false,$force=false){ - global $config; - - $locale = Session::exist('locale')?Session::get('locale'):(isset($config['locale'])?$config['locale']:self::$locale); - - if($space){ - if($force)Module::import($space); - $path = Module::path($space)."/language/{$locale}"; - }else{ - $path = "{$config['app']}/language/{$locale}"; - if(!file_exists($path))$path = "{$config['app']}/locale/{$locale}"; - if(!file_exists($path))$path = "{$config['system']}/language/{$locale}"; - } - if(!is_dir($path)){ - if($config['ENVIRONMENT'] == 'debug')debug::error("Missing Locales",$space); - //else die("Locales at {$space} not Found."); - - return null; - } - - foreach (glob("{$path}/*.php") as $filename){ - $lng = self::localeFile($filename); - if(!is_array($lng))return false; - if(!$space){ - self::$phrases = array_merge(self::$phrases,$lng); - }else{ - if(!is_array(self::$phrases_space[$space]))self::$phrases_space[$space] = array(); - self::$phrases_space[$space] = array_merge(self::$phrases_space[$space],$lng); - } - } - - if(!$space)return self::$phrases; - else return self::$phrases_space[$space]; - } - - private static function localeFile($filename){ - return require_once $filename; - } - - - public static function requestLocale($locale='locale'){ - if(Request::get($locale))Session::set(array('locale'=>Request::get($locale))); - } +/** + * Locale Alias __. + * + * @param mixen str or array keys only + * + * @return mixen + */ +function __($e, $a = array(), $space = false) +{ + return Internationalization::translate($e, $a, $space); } /* End of file Locale.php */ -/* Location: ./system/core/Locale.php */ \ No newline at end of file +/* Location: ./system/core/Locale.php */ From b7eae5fe80beb9c94b5d1175cfab4bf91e1a9ec5 Mon Sep 17 00:00:00 2001 From: Tamer Zorba Date: Wed, 30 Mar 2016 18:50:14 +0300 Subject: [PATCH 044/114] Hook : init new class create new alias for Events class --- system/core/Hook.php | 42 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 system/core/Hook.php diff --git a/system/core/Hook.php b/system/core/Hook.php new file mode 100644 index 0000000..35feb9d --- /dev/null +++ b/system/core/Hook.php @@ -0,0 +1,42 @@ + Date: Wed, 30 Mar 2016 18:50:28 +0300 Subject: [PATCH 045/114] Debug : fix view on js --- system/core/Debug.php | 260 +++++++++++++++++++++++------------------- 1 file changed, 144 insertions(+), 116 deletions(-) diff --git a/system/core/Debug.php b/system/core/Debug.php index f1e0d12..954f072 100644 --- a/system/core/Debug.php +++ b/system/core/Debug.php @@ -1,125 +1,153 @@ - array(), - "memory" => array() - ); - - public static function __bootstrap(){ - if(self::$disabled)return; - self::$microtime = microtime(true); - self::$memory = memory_get_usage(); - } - - public static function __shutdown(){ - if(self::$disabled)return; - - $time = round(microtime(true)-self::$microtime,4); - $memory = memory_get_usage(); - $rmemory = $memory-self::$memory; - $memory .= " - %c".File::format($memory); - $rmemory .= " - %c".File::format($rmemory); - $memoryp = memory_get_peak_usage(true); - $memoryp .= " - %c".File::format($memoryp); - $version = VERSION; - $ext = File::extension(request::alias()); - - $comment = (in_array($ext, array('js','css')))?true:false; - - if($comment)echo "/** Debug **"; - - echo "\n\n\n\n\n\n"; - - if($comment)echo "*/"; - - } - - public static function message($parent,$msg){ - if(!isset(self::$message[$parent]))self::$message[$parent] = array(); - if(array_search($msg,self::$message[$parent]) === false)array_push(self::$message[$parent],$msg); - } - - public static function error($parent,$msg){ - if(!isset(self::$error[$parent]))self::$error[$parent] = array(); - if(array_search($msg,self::$error[$parent]) === false)array_push(self::$error[$parent],$msg); - } - - public static function count($parent){ - if(!isset(self::$count[$parent]))self::$count[$parent] = array(); - array_push(self::$count[$parent],""); - } - - public static function disable(){ - self::$disabled = true; - } - - - public static function start($name="default"){ - self::$custom["time"][$name] = microtime(true); - self::$custom["memory"][$name] = memory_get_usage(); - } - - public static function finish($name="default"){ - $cls = new stdClass(); - $cls->time = round(microtime(true)-self::$custom["time"][$name],4); - $cls->memory = File::format(memory_get_usage()-self::$memory); - return $cls; - } - +class Debug +{ + private static $message = array(); + private static $error = array(); + private static $count = array(); + private static $microtime; + private static $memory; + + private static $disabled = false; + + private static $custom = array( + 'time' => array(), + 'memory' => array(), + ); + + public static function __bootstrap() + { + if (self::$disabled) { + return; + } + self::$microtime = microtime(true); + self::$memory = memory_get_usage(); + } + + public static function __shutdown() + { + if (self::$disabled) { + return; + } + + $time = round(microtime(true) - self::$microtime, 4); + $memory = memory_get_usage(); + $rmemory = $memory - self::$memory; + $memory .= ' - %c'.File::format($memory); + $rmemory .= ' - %c'.File::format($rmemory); + $memoryp = memory_get_peak_usage(true); + $memoryp .= ' - %c'.File::format($memoryp); + $version = VERSION; + $ext = File::extension(request::alias()); + + $comment = (in_array($ext, array('js', 'css'))) ? true : false; + + if ($comment) { + echo '/** Debug **'; + } + + echo "\n\n\n\n\n\n'; + + if ($comment) { + echo '*/'; + } + } + + public static function message($parent, $msg) + { + if (!isset(self::$message[$parent])) { + self::$message[$parent] = array(); + } + if (array_search($msg, self::$message[$parent]) === false) { + array_push(self::$message[$parent], $msg); + } + } + + public static function error($parent, $msg) + { + if (!isset(self::$error[$parent])) { + self::$error[$parent] = array(); + } + if (array_search($msg, self::$error[$parent]) === false) { + array_push(self::$error[$parent], $msg); + } + } + + public static function count($parent) + { + if (!isset(self::$count[$parent])) { + self::$count[$parent] = array(); + } + array_push(self::$count[$parent], ''); + } + + public static function disable() + { + self::$disabled = true; + } + + public static function start($name = 'default') + { + self::$custom['time'][$name] = microtime(true); + self::$custom['memory'][$name] = memory_get_usage(); + } + + public static function finish($name = 'default') + { + $cls = new stdClass(); + $cls->time = round(microtime(true) - self::$custom['time'][$name], 4); + $cls->memory = File::format(memory_get_usage() - self::$memory); + + return $cls; + } } -?> \ No newline at end of file From 27298b763c23d35d863be688b0b5db005f9cc6c6 Mon Sep 17 00:00:00 2001 From: Tamer Zorba Date: Wed, 30 Mar 2016 18:50:50 +0300 Subject: [PATCH 046/114] Core update codeHive Core : fix some notice and better code codeHive Core : use PSR-2 --- system/core/codeHive.php | 225 +++++++++++++++++++-------------------- 1 file changed, 112 insertions(+), 113 deletions(-) diff --git a/system/core/codeHive.php b/system/core/codeHive.php index 41c9c52..04a40a6 100644 --- a/system/core/codeHive.php +++ b/system/core/codeHive.php @@ -1,124 +1,123 @@ + * @copyright Copyright (c) 2013 - 2016, PureCore International Solutions (http://purecis.com/) + * @license http://opensource.org/licenses/MIT MIT License * - * @access public - * @param mixen str or array keys only - * @return mixen + * @link http://codehive.purecis.com/package/Benchmark + * @since File available since Release 2.0.0 + * + * @version V: 2.1.0 */ -function __($e,$a=array(),$space=false){ - return Internationalization::translate($e,$a,$space); +class codeHive +{ + public static function start($start = array('app' => 'app')) + { + global $config; + + if (version_compare(PHP_VERSION, '5.3.0', '<')) { + throw new Exception('The codeHive Framework v2.1 requires PHP version 5.3 or higher, (5.4) is Recomonded.'); + } + + define('VersionMajor', '2'); + define('VersionMinor', '1'); + define('VersionPatch', '00'); + define('VersionCode', 'Beta'); + define('VersionBuild', '3000'); + + define('VERSION', 'v.'.VersionMajor.'.'.VersionMinor.'.'.VersionPatch.' '.VersionCode.', Build '.VersionBuild); + + $config = array(); + $config['app'] = $start['app'] ?: 'app'; + $config['assets'] = $start['assets'] ?: 'assets'; + $config['system'] = $start['system'] ?: 'system'; + + $config = array_merge($config, self::config($config['app'])); + + if (!$config['settings']) { + $config['settings'] = array(); + } + + // defines + define('INDEX_FILE', isset($config['index']) ? $config['index'] : 'index.php'); + define('SESSION_PERFIX', isset($config['session']) ? $config['session'] : ''); + + if (isset($config['license'])) { + if (isset($config['license']['hash'])) { + define('SECURITY_HASH', $config['license']['hash']); + } + } + if (isset($config['timezone'])) { + date_default_timezone_set($config['timezone']); + } + + if (isset($config['ENVIRONMENT'])) { + switch ($config['ENVIRONMENT']) { + case 'development' : + error_reporting(E_ALL); + break; + + case 'debug' : + error_reporting(E_ALL); + Debug::__bootstrap(); + break; + + case 'production' : + error_reporting(0); + break; + + default: + exit('The application environment is not set correctly.'); + } + } + + echo Module::__bootstrap(); + + require_once "{$start['app']}/app.php"; + + echo Module::__shutdown(); + + if (isset($config['ENVIRONMENT']) && $config['ENVIRONMENT'] == 'debug') { + Debug::__shutdown(); + } + } + + private static function config($app) + { + if (!file_exists("{$app}/config.php")) { + Install::initialize(); + exit; + }; + + return require_once "{$app}/config.php"; + } } -/** - * Class Start +/* + * auto load class when it called (Core Classes Only). */ -class codeHive{//composer, artisan, Hive , Arti, Zorba, codeHive, iBuilder - - public static function start($start = array('app'=>'app')){ - global $config; - - if (version_compare(PHP_VERSION, '5.3.0', '<')) { - throw new Exception('The codeHive Framework v2 requires PHP version 5.3 or higher, (5.4) is Recomonded.'); - } - - define(VersionMajor,"2"); - define(VersionMinor,"0"); - define(VersionPatch,"00"); - define(VersionCode,"Alpha"); - define(VersionBuild,"2096"); - - define(VERSION,"v.".VersionMajor.".".VersionMinor.".".VersionPatch." ".VersionCode.", Build ".VersionBuild); - - $config = array(); - $config['app'] = $start['app']?:"app"; - $config['assets'] = $start['assets']?:"assets"; - $config['system'] = $start['system']?:"system"; - - $config = array_merge($config,self::config($config['app'])); - - if(!$config['settings'])$config['settings'] = array(); - - // defines - define(INDEX_FILE, $config['index']?:'index.php'); - define(SESSION_PERFIX, $config['session']?:''); - if($config['license'])define(SECURITY_HASH, $config['license']['hash']); - if($config['timezone'])date_default_timezone_set($config['timezone']); - - // env - if ($config['ENVIRONMENT']){ - switch ($config['ENVIRONMENT']){ - case 'development': - error_reporting(E_ALL); - break; - - case 'debug': - error_reporting(E_ALL); - Debug::__bootstrap(); - break; - - case 'production': - error_reporting(0); - break; - - default: - exit('The application environment is not set correctly.'); - } - } - - echo Module::__bootstrap(); - - require_once "{$start['app']}/app.php"; - - echo Module::__shutdown(); - - if($config['ENVIRONMENT'] == 'debug')Debug::__shutdown(); - } - - private static function config($app){ - if(!file_exists("{$app}/config.php")){ - Install::initialize(); - exit; - }; - return require_once "{$app}/config.php"; - } -} - +spl_autoload_register(function ($class) { + global $config; + $class = str_replace('\\', '/', $class); + if (is_file("{$config['system']}/core/{$class}.php")) { + require_once "{$class}.php"; + if (is_callable(array($class, '__bootstrap'))) { + call_user_func(array($class, '__bootstrap')); + } + if (isset($config['ENVIRONMENT']) && $config['ENVIRONMENT'] == 'debug') { + debug::message('Used System Cores', $class); + } + } else { + if ($config['ENVIRONMENT'] == 'debug') { + debug::error('System Cores Faild', $class); + } + } +}); /* End of file codeHive.php */ /* Location: ./system/core/codeHive.php */ From 2c1cb93b81bd82441f8f75624b972c808db8d07a Mon Sep 17 00:00:00 2001 From: Tamer Zorba Date: Tue, 5 Apr 2016 14:35:00 +0300 Subject: [PATCH 047/114] fix some issues new database connection new trace and globalize it api can handle module inside api's and alot more --- system/core/{Assets.php => Asset.php} | 16 +- system/core/Benchmark.php | 17 +- system/core/Controller.php | 216 ++-- system/core/Database.php | 302 +++--- system/core/Internationalization.php | 4 +- system/core/Module.php | 396 ++++--- system/core/Session.php | 195 ++-- system/core/{Debug.php => Trace.php} | 10 +- system/core/View.php | 118 ++- system/core/codeHive.php | 29 +- system/helper/Cache.php | 9 + system/module/API.php | 426 ++++---- system/module/Query.php | 1412 +++++++++++++------------ system/module/QueryBuilder.php | 323 +++--- system/module/Router.php | 251 +++-- 15 files changed, 2032 insertions(+), 1692 deletions(-) rename system/core/{Assets.php => Asset.php} (93%) rename system/core/{Debug.php => Trace.php} (94%) create mode 100644 system/helper/Cache.php diff --git a/system/core/Assets.php b/system/core/Asset.php similarity index 93% rename from system/core/Assets.php rename to system/core/Asset.php index 98a939d..1da981d 100644 --- a/system/core/Assets.php +++ b/system/core/Asset.php @@ -3,9 +3,9 @@ defined('VERSION') or exit('Direct access to this location is not permitted'); /** - * codeHive Assets. + * codeHive Asset. * - * Assets class prepare resources, meta and elements to initiate in app + * Asset class prepare resources, meta and elements to initiate in app * * @category core * @@ -13,12 +13,12 @@ * @copyright Copyright (c) 2013 - 2016, PureCore International Solutions (http://purecis.com/) * @license http://opensource.org/licenses/MIT MIT License * - * @link http://codehive.purecis.com/package/Assets + * @link http://codehive.purecis.com/package/Asset * @since File available since Release 2.0.0 * * @version V: 2.1.0 */ -class Assets +class Asset { /** * initialize js code. @@ -31,7 +31,7 @@ class Assets protected static $codev = array(); /** - * codeHive Assets class constructor. + * codeHive Asset class constructor. * * define javascript default path values from codeHive */ @@ -147,7 +147,7 @@ public static function style($src, $folder = 'vendor', $listener = 'style') { $src = self::src_parser($src, $folder); $extra = File::extension($src) == 'less' ? '/less' : ''; - // TODO : make less and scss as plugins or hooks to fetch + // TODO:20 : make less and scss as plugins or hooks to fetch Hook::on($listener, "\n\t"); } @@ -182,5 +182,5 @@ public static function vendor($src = '') } } -/* End of file Assets.php */ -/* Location: ./system/core/Assets.php */ +/* End of file Asset.php */ +/* Location: ./system/core/Asset.php */ diff --git a/system/core/Benchmark.php b/system/core/Benchmark.php index 572491b..d957521 100644 --- a/system/core/Benchmark.php +++ b/system/core/Benchmark.php @@ -34,7 +34,7 @@ class Benchmark * * @return array */ - public static function start($name) + public static function start($name = 'default') { self::$benchmarks[$name] = new stdClass(); self::$benchmarks[$name]->time = microtime(true); @@ -52,7 +52,7 @@ public static function start($name) * * @return array */ - public static function complete($name) + public static function complete($name = 'default') { global $config; @@ -60,15 +60,16 @@ public static function complete($name) $end->time = microtime(true); $end->memory = memory_get_usage(); - if ($config['ENVIRONMENT'] == 'debug') { - $time = round($end->time - self::$benchmarks[$name]->time, 4); - $memory = $end->memory - self::$benchmarks[$name]->memory; - $memory = $memory.' - '.File::format($memory); + $result = new stdClass(); + $result->time = round($end->time - self::$benchmarks[$name]->time, 4); + $result->memory = $end->memory - self::$benchmarks[$name]->memory; + $result->memory .= ' - '.File::format($result->memory); - Debug::error("Benchmark {$name}", "Time : {$time} | Memory : {$memory}"); + if (strtoupper($config['ENVIRONMENT']) == 'TRACE') { + Trace::error("Benchmark {$name}", "Time : {$result->time} | Memory : {$result->memory}"); } - return $arr; + return $result; } } diff --git a/system/core/Controller.php b/system/core/Controller.php index 7c55125..7ec8d5a 100644 --- a/system/core/Controller.php +++ b/system/core/Controller.php @@ -1,119 +1,133 @@ - + * @copyright Copyright (c) 2013 - 2016, PureCore International Solutions (http://purecis.com/) + * @license http://opensource.org/licenses/MIT MIT License * - * @package codeHive - * @subpackage Core - * @category Libraries - * @author Tamer Zorba - * @link http://purecis.com/ + * @link http://codehive.purecis.com/package/Controller + * @since File available since Release 2.0.0 + * + * @version V: 2.1.0 */ +class Controller +{ + /** + * List on predefined controllers. + */ + protected static $controllers = array(); -class Controller{ - - /** - * List of paths to load views from - * - * @var array - * @access protected - */ - protected static $controllers = array(); - public static $scope; - - // -------------------------------------------------------------------- + /** + * application object (the owner of application variables and functions). + */ + public static $scope; // TODO:30 : multiple scopes per view with its childs - /** - * Controller bootstrap - * - * Update : For better performance change this start to per file load - * - * @access public - * @return string - */ - public static function __bootstrap(){ - global $config; - foreach (glob("{$config['app']}/controller/*.bootstrap.php") as $filename){ - require_once $filename; - } - } + /** + * codeHive Controller class constructor. + * + * initialize default controllers + */ + public static function __bootstrap() + { + global $config; + foreach (glob("{$config['app']}/controller/*.bootstrap.php") as $filename) { + require_once $filename; + } + foreach (glob("{$config['app']}/controller/*.init.php") as $filename) { + require_once $filename; + } + } - // -------------------------------------------------------------------- - - /** - * Controller Define Scope - * - * @access public - * @param array key:value - * @return array scope - */ - public static function scope($arr=array()){ - if(empty(self::$scope))self::$scope = new stdClass(); - foreach ($arr as $key => $value){ - self::$scope->$key = $value; - } - return self::$scope; - } + /** + * append array to the Scope. + * + * @param array $arr key:cvalue + * + * @return object Scope + */ + public static function scope($arr = array()) + { + if (empty(self::$scope)) { + self::$scope = new stdClass(); + } + foreach ($arr as $key => $value) { + self::$scope->$key = $value; + } - // -------------------------------------------------------------------- + return self::$scope; + } - /** - * Controller Register - * - * @access public - * @param string controller name - * @param mixen callback - * @return string - */ - public static function register($name,$fn){ - $name = urlencode($name); + /** + * register new controller. + * + * @param string $name controller name + * @param mixen $fn callback + * + * @return array Controllers + */ + public static function register($name, $fn) + { + $name = urlencode($name); - self::$controllers[$name] = $fn; - - return self::$controllers; - } + self::$controllers[$name] = $fn; - // -------------------------------------------------------------------- + return self::$controllers; + } - /** - * Controller Trigger - * - * @access public - * @param mixen controller - * @param mixen args to pass - * @return mixen - */ - public static function trigger($name,$arg=null){ - global $config; + /** + * trigger controller by name and send args to callback. + * + * @param string $name controller name + * @param array $arg callback arguments + */ + public static function trigger($name, $arg = null) + { + global $config; - if(empty(self::$scope))self::$scope = new stdClass(); + if (empty(self::$scope)) { + self::$scope = new stdClass(); + } - if(is_string($name)){ - if(array_key_exists($name,self::$controllers)){ - $name = self::$controllers[$name]; - }else{ - $path = "{$config['app']}/controller/{$name}.php"; - if(is_file($path))require_once $path; - } - if(array_key_exists($name,self::$controllers)){ - $name = self::$controllers[$name]; - } - } - if(is_array($name)){ - $path = "{$config['app']}/controller/{$name[0]}.php"; - if(is_file($path))require_once $path; - $name[0] = str_replace(".", "\\", $name[0]); - } + if (is_string($name)) { + if (array_key_exists($name, self::$controllers)) { + $name = self::$controllers[$name]; + } else { + $path = "{$config['app']}/controller/{$name}.php"; + if (is_file($path)) { + require_once $path; + } + } + if (array_key_exists($name, self::$controllers)) { + $name = self::$controllers[$name]; + } + } + if (is_array($name)) { + $path = "{$config['app']}/controller/{$name[0]}.php"; + if (is_file($path)) { + require_once $path; + } + $name[0] = str_replace('.', '\\', $name[0]); + } - if(is_callable($name)){ - return call_user_func_array($name, array(&self::$scope,$arg)); - }else{ - if($config['ENVIRONMENT'] == 'debug')debug::error("Missing Controller",$name); - else die("Controller {$name} not Found."); - } - } + if (is_callable($name)) { + return call_user_func_array($name, array(&self::$scope, $arg)); + } else { + if (strtoupper($config['ENVIRONMENT']) == 'TRACE') { + Trace::error('Missing Controller', $name); + } else { + die("Controller {$name} not Found."); + } + } + } } /* End of file Controller.php */ -/* Location: ./system/core/Controller.php */ \ No newline at end of file +/* Location: ./system/core/Controller.php */ diff --git a/system/core/Database.php b/system/core/Database.php index 1be7828..284bb76 100644 --- a/system/core/Database.php +++ b/system/core/Database.php @@ -1,129 +1,185 @@ - + * @copyright Copyright (c) 2013 - 2016, PureCore International Solutions (http://purecis.com/) + * @license http://opensource.org/licenses/MIT MIT License + * + * @link http://codehive.purecis.com/package/Database + * @since File available since Release 2.0.0 + * + * @version V: 2.1.0 */ - -class Database{ - - /** - * Database Live Connection - * - * @var mixen - * @access protected - */ - protected static $db = null; - - // -------------------------------------------------------------------- - - /** - * Database Connect - * - * @access public - * @param string Database name - * @param string Database host - * @param string Database user - * @param string Database pass - * @param string Database port - * @return mixen - */ - public static function connect($db_name=null,$db_host=null,$db_user=null,$db_pass=null,$db_port=null){ - global $config; - - if(!$config['database'])$config['database'] = array(); - - if (!self::$db or ($db_name && $db_name != $config['database']['name'])){ - if($db_name)$config['database']['name'] = $db_name; - if($db_host)$config['database']['host'] = $db_host; - if($db_user)$config['database']['user'] = $db_user; - if($db_pass)$config['database']['pass'] = $db_pass; - if($db_port)$config['database']['port'] = $db_port; - - $type = $config['database']['type']; - $host = $config['database']['host']; - $name = $config['database']['name']; - $user = $config['database']['user']; - $pass = $config['database']['pass']; - $port = $config['database']['port']; - - try{ - // Checking Database Type… - if($type == 'sqlite') self::$db = new PDO("sqlite:{$name}"); - if($type == 'mysql') self::$db = new PDO("mysql:host={$host};dbname={$name};charset=utf8;Allow User Variables=True", $user, $pass); - if($type == 'pgsql') self::$db = new PDO("pgsql:dbname={$name};host={$host}", $user, $pass ); - if($type == 'oracle') self::$db = new PDO("OCI:dbname={$name};charset=UTF-8", $user, $pass); - if($type == 'firebird') self::$db = new PDO("firebird:dbname={$host}:{$name}", "SYSDBA", $pass); - if($type == 'infomix') self::$db = new PDO("informix:DSN={$name}", $user, $pass); - if($type == 'dblib') self::$db = new PDO ("dblib:host={$host}:{$port};dbname={$name}",$user,$pass); - if($type == 'odbc') self::$db = new PDO("odbc:Driver={Microsoft Access Driver (*.mdb)};Dbq={$name}"); - - self::$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);//set character set utf8 - - }catch(PDOException $e){ - //if($config['ENVIRONMENT'] == 'debug')debug::error("Database Error",$e->getMessage()); - //else - die("Database Error :".$e->getMessage()); - } - } - return self::$db; - } - - // -------------------------------------------------------------------- - - /** - * Database Query - * - * @access public - * @param string sql - * @return array - */ - public static function query($sql){ - global $config; - - self::connect(); - $return = new stdClass(); - try{ - $query = self::$db->query($sql); - //$query = $link->prepare('SELECT * FROM users WHERE username = :name LIMIT 1;'); - //$query->execute([':name' => $username]); # No need to escape it! - - $temp_sql = strtolower($sql); - $s = strpos($temp_sql,'select'); - $i = strpos($temp_sql,'insert'); - $u = strpos($temp_sql,'update'); - $d = strpos($temp_sql,'delete'); - $t = strpos($temp_sql,'truncate'); - if($s < 10 && $s !== false)$type = 'select'; - if($i < 10 && $i !== false)$type = 'insert'; - if($u < 10 && $u !== false)$type = 'update'; - if($d < 10 && $d !== false)$type = 'delete'; - if($d < 10 && $d !== false)$type = 'truncate'; - - $fetch = $config['database']['fetch']=="array"?PDO::FETCH_ASSOC:PDO::FETCH_CLASS; - if(in_array($type, array('select','update','delete','truncate')))$return->count = $query->rowCount(); - if($type == 'select')$return->data = @$query->fetchAll($fetch); - if($type == 'insert')$return->last = self::$db->lastInsertId(); - - $return->status = true; - - if($config['ENVIRONMENT'] == 'debug')debug::count('Database Queries'); - - }catch(PDOException $e){ - if($config['ENVIRONMENT'] == 'debug')debug::error("Database Error",String::escape($e->getMessage())); - $return->status = false; - $return->error = $e->getMessage(); - } - - if(in_array($config['ENVIRONMENT'], array('debug','development')))$return->sql = $sql; - return $return; - } +class Database +{ + /** + * Database Connection. + */ + private static $current = null; + protected static $connection = null; + + // -------------------------------------------------------------------- + + /** + * Database Connect. + * + * @param string Database name + * @param string Database host + * @param string Database user + * @param string Database pass + * @param string Database port + * + * @return mixen + */ + public static function connect($con = array()) + { + global $config; + + if (!$config['database']) { + $config['database'] = array(); + } + + if (self::$connection && (!isset($con['name']) or $con['name'] == self::$current)) { + return self::$connection; + } + if (self::$connection && $con['name'] == $config['database']['name']) { + return self::$connection; + } + + $crd = new stdClass(); + $crd->type = isset($con['type']) ? $con['type'] : $config['database']['type']; + $crd->host = isset($con['host']) ? $con['host'] : $config['database']['host']; + $crd->name = isset($con['name']) ? $con['name'] : $config['database']['name']; + $crd->user = isset($con['user']) ? $con['user'] : $config['database']['user']; + $crd->pass = isset($con['pass']) ? $con['pass'] : $config['database']['pass']; + $crd->port = isset($con['port']) ? $con['port'] : $config['database']['port']; + + try { + switch ($crd->type) { + case 'sqlite': + $dsn = "sqlite:{$crd->name}"; + break; + + case 'pgsql': + $dsn = "pgsql:dbname={$crd->name};host={$crd->host}"; + break; + + case 'oracle': + $dsn = "OCI:dbname={$crd->name};charset=UTF-8"; + break; + + case 'firebird': + $dsn = "firebird:dbname={$crd->host}:{$crd->name}"; + $crd->user = 'SYSDBA'; + break; + + case 'infomix': + $dsn = "informix:DSN={$crd->name}"; + break; + + case 'dblib': + $dsn = "dblib:host={$crd->host}:{$crd->port};dbname={$crd->name}"; + break; + + case 'odbc': + $dsn = "odbc:Driver={Microsoft Access Driver (*.mdb)};Dbq={$crd->name}"; + break; + + case 'mysql': + default: + $crd->port = $crd->port ?: 3306; + $dsn = "mysql:host={$crd->host};dbname={$crd->name};port={$crd->port};charset=utf8"; + break; + } + + self::$connection = self::$current = new PDO($dsn, $crd->user, $crd->pass); + self::$connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); + } catch (PDOException $e) { + if (strtoupper($config['ENVIRONMENT']) == 'TRACE') { + Trace::error('Database Error', String::escape($e->getMessage())); + } else { + die('Database Error :'.$e->getMessage()); + } + } + + return self::$connection; + } + + // -------------------------------------------------------------------- + + /** + * Database Query. + * + * @param string sql + * + * @return array + */ + public static function query($sql, $args = array()) + { + global $config; + + self::connect(); + $return = new stdClass(); + try { + if (!sizeof($args)) { + $query = self::$connection->query($sql); + } else { + $query = self::$connection->prepare($sql); + $query->execute($args); + } + + $type = strtoupper(substr($sql, 0, 10)); + if (strpos($type, 'INSERT') !== false) { + $type = 'insert'; + } elseif (strpos($type, 'UPDATE') !== false) { + $type = 'update'; + } elseif (strpos($type, 'DELETE') !== false) { + $type = 'delete'; + } elseif (strpos($type, 'TRUNCATE') !== false) { + $type = 'truncate'; + } else { + $type = 'select'; // show + } + + $fetch = isset($config['database']['fetch']) && $config['database']['fetch'] == 'array' ? PDO::FETCH_ASSOC : PDO::FETCH_CLASS; + if (in_array($type, array('select', 'update', 'delete', 'truncate'))) { + $return->count = $query->rowCount(); + } + if ($type == 'select') { + $return->record = $query->fetchAll($fetch); + } + if ($type == 'insert') { + $return->last = self::$connection->lastInsertId(); + } + + $return->status = true; + + if (strtoupper($config['ENVIRONMENT']) == 'TRACE') { + Trace::count('Database Queries'); + } + } catch (PDOException $e) { + if (strtoupper($config['ENVIRONMENT']) == 'TRACE') { + Trace::error('Database Error', String::escape($e->getMessage())); + } + $return->status = false; + $return->error = $e->getMessage(); + } + + if (in_array(strtoupper($config['ENVIRONMENT']), array('TRACE', 'DEVELOPMENT'))) { + $return->sql = $sql; + // TODO : append sql to tracer .. + } + + return $return; + } } /* End of file Database.php */ diff --git a/system/core/Internationalization.php b/system/core/Internationalization.php index 9448897..2af0234 100644 --- a/system/core/Internationalization.php +++ b/system/core/Internationalization.php @@ -156,8 +156,8 @@ public static function prepare($space = false, $force = false) } } if (!is_dir($path)) { - if ($config['ENVIRONMENT'] == 'debug') { - debug::error('Missing Locales', $space); + if (strtoupper($config['ENVIRONMENT']) == 'TRACE') { + Trace::error('Missing Locales', $space); } //else die("Locales at {$space} not Found."); diff --git a/system/core/Module.php b/system/core/Module.php index d4ef613..fd2b678 100644 --- a/system/core/Module.php +++ b/system/core/Module.php @@ -1,167 +1,251 @@ -{$k} not Found in {$path}."); - }else{ - self::$modules[$k] = array("dir"=>dirname($path),"version"=>"1"); - require_once $path; - $k = str_replace(".", "\\", $k); - if(is_callable(array($k,"__bootstrap")))call_user_func(array($k,"__bootstrap")); - } - } - - // -------------------------------------------------------------------- - - /** - * Check if Module Used - * - * @access public - * @param mixen module or array of modules - * @return boolean - */ - public static function used($mod){ - if(is_array($mod)){ - foreach($mod as $m){ - if(!isset(self::$modules[$m]))return false; - } - return true; - }else{ - if(isset(self::$modules[$mod]))return true; - } - return false; - } - - // -------------------------------------------------------------------- - - /** - * Get Module Path - * - * @access public - * @param mixen module or array of modules - * @return boolean - */ - public static function path($mod,$full=false){ - if(isset(self::$modules[$mod])){ - return self::$modules[$mod]['dir']; - } - - global $config; - if(strpos($mod, ".")){ - $ex = explode(".", $mod); - $file = end($ex); - }else{ - $file = $mod; - } - - // TODO : the module, plugins, etc folders called SPACE, PACKAGE in doc's - - $path = "{$config['app']}/module/{$mod}/{$file}.php"; - if(!is_file($path))$path = "{$config['app']}/hook/{$mod}/{$file}.php"; - if(!is_file($path))$path = "{$config['app']}/plugin/{$mod}/{$file}.php"; - if(!is_file($path))$path = "{$config['app']}/extension/{$mod}/{$file}.php"; - if(!is_file($path))$path = "{$config['app']}/component/{$mod}/{$file}.php"; - if(!is_file($path))$path = "{$config['app']}/element/{$mod}/{$file}.php"; - if(!is_file($path))$path = "{$config['app']}/service/{$mod}/{$file}.php"; - if(!is_file($path))$path = "{$config['app']}/helper/{$mod}/{$file}.php"; - if(!is_file($path))$path = "{$config['assets']}/extensions/{$mod}/{$file}.php"; - if(!is_file($path))$path = "{$config['system']}/module/{$mod}.php"; - - if(is_file($path)){ - if($full) return $path; - else return dirname($path); - } - return false; - } - - // -------------------------------------------------------------------- - - /** - * Shutdown - * - * @access public - * @return void - */ - public static function __shutdown(){ - global $config; - foreach(self::$modules as $k => $v){ - if(is_callable(array($k,"__shutdown")))call_user_func(array($k,"__shutdown")); - } - if($config['ENVIRONMENT'] == 'debug'){ - foreach(self::$modules as $k => $v){ - debug::message("Used Modules","{$k}"); - } - } - } +class Module +{ + /** + * List of paths to load views from. + * + * @var array + */ + protected static $modules = array(); + + /** + * BootStrap. + */ + public static function __bootstrap() + { + global $config; + self::import($config['modules']); + } + + // -------------------------------------------------------------------- + + /** + * Use and Import Module. + * + * Defines Module and prepare to call bootstrap for each + * + * @param mixen module or array of modules + */ + public static function import($mod) + { + if (is_array($mod)) { + foreach ($mod as $m) { + if (!isset(self::$modules[$m])) { + self::register($m); + } + } + } else { + if (!isset(self::$modules[$mod])) { + self::register($mod); + } + } + } + + // -------------------------------------------------------------------- + + /** + * Register Module and initialize it by calling bootstrap. + * + * @param string module name + */ + private static function register($k) + { + global $config; + + $path = self::path($k, true); + + if (!$path) { + if (strtoupper($config['ENVIRONMENT']) == 'TRACE') { + Trace::error('Missing Module', "{$k}"); + } else { + die("Module {$k} not Found in {$path}."); + } + } else { + self::$modules[$k] = array('dir' => dirname($path), 'version' => '1'); + require_once $path; + $k = str_replace('.', '\\', $k); + if (is_callable(array($k, '__bootstrap'))) { + call_user_func(array($k, '__bootstrap')); + } + } + } + + // -------------------------------------------------------------------- + + /** + * Check if Module Used. + * + * @param mixen module or array of modules + * + * @return bool + */ + public static function used($mod) + { + if (is_array($mod)) { + foreach ($mod as $m) { + if (!isset(self::$modules[$m])) { + return false; + } + } + + return true; + } else { + if (isset(self::$modules[$mod])) { + return true; + } + } + + return false; + } + + // -------------------------------------------------------------------- + + /** + * Get Module Path. + * + * @param mixen module or array of modules + * + * @return bool + */ + public static function path($mod, $full = false) + { + if (isset(self::$modules[$mod])) { + return self::$modules[$mod]['dir']; + } + + global $config; + if (strpos($mod, '.')) { + $ex = explode('.', $mod); + $file = end($ex); + } else { + $file = $mod; + } + + $alias = array('module', 'hook', 'plugin', 'extension', 'component', 'element', 'service', 'helper', 'lib', 'kernel', 'space', 'package'); + foreach ($alias as $als) { + $path = "{$config['app']}/{$als}/{$mod}/{$file}.php"; + if (is_file($path)) { + break; + } + $path = "{$config['assets']}/{$als}/{$mod}/{$file}.php"; + if (is_file($path)) { + break; + } + $path = "{$config['system']}/{$als}/{$mod}/{$file}.php"; + if (is_file($path)) { + break; + } + $path = "{$config['system']}/{$als}/{$mod}.php"; + if (is_file($path)) { + break; + } + } + + /* + $path = "{$config['app']}/module/{$mod}/{$file}.php"; + if (!is_file($path)) { + $path = "{$config['app']}/hook/{$mod}/{$file}.php"; + } + if (!is_file($path)) { + $path = "{$config['app']}/plugin/{$mod}/{$file}.php"; + } + if (!is_file($path)) { + $path = "{$config['app']}/extension/{$mod}/{$file}.php"; + } + if (!is_file($path)) { + $path = "{$config['app']}/component/{$mod}/{$file}.php"; + } + if (!is_file($path)) { + $path = "{$config['app']}/element/{$mod}/{$file}.php"; + } + if (!is_file($path)) { + $path = "{$config['app']}/service/{$mod}/{$file}.php"; + } + if (!is_file($path)) { + $path = "{$config['app']}/helper/{$mod}/{$file}.php"; + } + + if (!is_file($path)) { + $path = "{$config['assets']}/extensions/{$mod}/{$file}.php"; + } + if (!is_file($path)) { + $path = "{$config['system']}/module/{$mod}.php"; + } + if (!is_file($path)) { + $path = "{$config['system']}/hook/{$mod}.php"; + } + if (!is_file($path)) { + $path = "{$config['system']}/plugin/{$mod}.php"; + } + if (!is_file($path)) { + $path = "{$config['system']}/extension/{$mod}.php"; + } + if (!is_file($path)) { + $path = "{$config['system']}/component/{$mod}.php"; + } + if (!is_file($path)) { + $path = "{$config['system']}/element/{$mod}.php"; + } + if (!is_file($path)) { + $path = "{$config['system']}/service/{$mod}.php"; + } + if (!is_file($path)) { + $path = "{$config['system']}/helper/{$mod}.php"; + } + */ + + if (is_file($path)) { + if ($full) { + return $path; + } else { + return dirname($path); + } + } + + return false; + } + + // -------------------------------------------------------------------- + + public static function exist($mod, $full = false) + { + return (bool) self::path($mod, $full); + } + // -------------------------------------------------------------------- + + /** + * Shutdown. + */ + public static function __shutdown() + { + global $config; + foreach (self::$modules as $k => $v) { + if (is_callable(array($k, '__shutdown'))) { + call_user_func(array($k, '__shutdown')); + } + } + if (strtoupper($config['ENVIRONMENT']) == 'TRACE') { + foreach (self::$modules as $k => $v) { + Trace::message('Used Modules', "{$k}"); + } + } + } } /* End of file Module.php */ -/* Location: ./system/core/Module.php */ \ No newline at end of file +/* Location: ./system/core/Module.php */ diff --git a/system/core/Session.php b/system/core/Session.php index 1a46f54..e15ae8b 100644 --- a/system/core/Session.php +++ b/system/core/Session.php @@ -1,117 +1,126 @@ - 1) { + foreach ($arr as $key => $val) { + if (!isset($_SESSION[static::$SESSION_PERFIX.$val])) { + $cls->$val = false; + } else { + $cls->$val = $_SESSION[static::$SESSION_PERFIX.$val]; + } + } - $cls = new stdClass(); - if(sizeof($arr) > 1){ - foreach($arr as $key => $val){ - if(!isset($_SESSION[static::$SESSION_PERFIX.$val])){ - $cls->$val = false; - }else{ - $cls->$val = $_SESSION[static::$SESSION_PERFIX.$val]; - } - } - return $cls; - }else{ - return isset($_SESSION[static::$SESSION_PERFIX.$arr[0]])?$_SESSION[static::$SESSION_PERFIX.$arr[0]]:false; - } - } + return $cls; + } else { + return isset($_SESSION[static::$SESSION_PERFIX.$arr[0]]) ? $_SESSION[static::$SESSION_PERFIX.$arr[0]] : false; + } + } - // -------------------------------------------------------------------- + // -------------------------------------------------------------------- - /** - * Session exist - * - * will check all is exist or none - * - * @access public - * @param mixen str or array keys only - * @return boolean - */ - public static function exist($arr){ + /** + * Session exist. + * + * will check all is exist or none + * + * @param mixen str or array keys only + * + * @return bool + */ + public static function exist($arr) + { + if (!is_array($arr)) { + $arr = explode(',', $arr); + } - if(!is_array($arr))$arr = explode(",", $arr); + foreach ($arr as $key) { + if ( + !isset($_SESSION[static::$SESSION_PERFIX.$key]) or + $_SESSION[static::$SESSION_PERFIX.$key] == false + ) { + return false; + } + } - foreach($arr as $key){ - if( - !isset($_SESSION[static::$SESSION_PERFIX.$key]) or - $_SESSION[static::$SESSION_PERFIX.$key] == false - ){ - return false; - } - } - return true; - } + return true; + } - // -------------------------------------------------------------------- + // -------------------------------------------------------------------- - /** - * Session set - * - * register array of sessions with values - * - * @access public - * @param array str or array key value - * @return void - */ - public static function set($arr){ - - foreach($arr as $key => $val){ - $_SESSION[static::$SESSION_PERFIX.$key] = $val; - } - - } + /** + * Session set. + * + * register array of sessions with values + * + * @param array str or array key value + */ + public static function set($arr) + { + foreach ($arr as $key => $val) { + $_SESSION[static::$SESSION_PERFIX.$key] = $val; + } + } - // -------------------------------------------------------------------- + // -------------------------------------------------------------------- - /** - * Session remove - * - * remove all sessions - * - * @access public - * @param array str or array key value - * @return void - */ - public static function remove($arr=array(),$all=false){ - if(sizeof($arr) < 1 || $all){ - @session_unset(); - @session_destroy(); - }else{ - foreach($arr as $val){ - unset($_SESSION[static::$SESSION_PERFIX.$val]); - } - } - - } + /** + * Session remove. + * + * remove all sessions + * + * @param array str or array key value + */ + public static function remove($arr = array(), $all = false) + { + if (sizeof($arr) < 1 || $all) { + @session_unset(); + @session_destroy(); + } else { + foreach ($arr as $val) { + unset($_SESSION[static::$SESSION_PERFIX.$val]); + } + } + } } /* End of file Session.php */ -/* Location: ./system/core/Session.php */ \ No newline at end of file +/* Location: ./system/core/Session.php */ diff --git a/system/core/Debug.php b/system/core/Trace.php similarity index 94% rename from system/core/Debug.php rename to system/core/Trace.php index 954f072..e3da933 100644 --- a/system/core/Debug.php +++ b/system/core/Trace.php @@ -3,7 +3,7 @@ exit('Direct access to this location is not permitted.'); } /** - * Purecis Debug Class. + * Trace Class. * * This class Control Files on the server. * @@ -13,7 +13,7 @@ * * @link http://purecis.com/ */ -class Debug +class Trace { private static $message = array(); private static $error = array(); @@ -56,7 +56,7 @@ public static function __shutdown() $comment = (in_array($ext, array('js', 'css'))) ? true : false; if ($comment) { - echo '/** Debug **'; + echo '/** Trace **'; } echo "\n\n\n\n\n\n