repo
stringlengths
7
63
file_url
stringlengths
81
284
file_path
stringlengths
5
200
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-04 15:02:33
2026-01-05 05:24:06
truncated
bool
2 classes
xcg340122/PHP300Framework2x
https://github.com/xcg340122/PHP300Framework2x/blob/2ba403cd277680a050c457d39db2aef652fb8e8f/Extend/Package/smarty/sysplugins/smarty_internal_method_setdebugtemplate.php
Extend/Package/smarty/sysplugins/smarty_internal_method_setdebugtemplate.php
<?php /** * Smarty Method SetDebugTemplate * * Smarty::setDebugTemplate() method * * @package Smarty * @subpackage PluginsInternal * @author Uwe Tews */ class Smarty_Internal_Method_SetDebugTemplate { /** * Valid for Smarty and template object * * @var int */ public $objMap = 3; /** * set the debug template * * @api Smarty::setDebugTemplate() * * @param \Smarty_Internal_TemplateBase|\Smarty_Internal_Template|\Smarty $obj * @param string $tpl_name * * @return \Smarty|\Smarty_Internal_Template * @throws SmartyException if file is not readable */ public function setDebugTemplate(Smarty_Internal_TemplateBase $obj, $tpl_name) { $smarty = $obj->_getSmartyObj(); if (!is_readable($tpl_name)) { throw new SmartyException("Unknown file '{$tpl_name}'"); } $smarty->debug_tpl = $tpl_name; return $obj; } }
php
Apache-2.0
2ba403cd277680a050c457d39db2aef652fb8e8f
2026-01-05T04:52:44.635355Z
false
xcg340122/PHP300Framework2x
https://github.com/xcg340122/PHP300Framework2x/blob/2ba403cd277680a050c457d39db2aef652fb8e8f/Extend/Package/smarty/sysplugins/smarty_internal_runtime_tplfunction.php
Extend/Package/smarty/sysplugins/smarty_internal_runtime_tplfunction.php
<?php /** * TplFunction Runtime Methods callTemplateFunction * * @package Smarty * @subpackage PluginsInternal * @author Uwe Tews * **/ class Smarty_Internal_Runtime_TplFunction { /** * Call template function * * @param \Smarty_Internal_Template $tpl template object * @param string $name template function name * @param array $params parameter array * @param bool $nocache true if called nocache * * @throws \SmartyException */ public function callTemplateFunction(Smarty_Internal_Template $tpl, $name, $params, $nocache) { $funcParam = isset($tpl->tplFunctions[ $name ]) ? $tpl->tplFunctions[ $name ] : (isset($tpl->smarty->tplFunctions[ $name ]) ? $tpl->smarty->tplFunctions[ $name ] : null); if (isset($funcParam)) { if (!$tpl->caching || ($tpl->caching && $nocache)) { $function = $funcParam[ 'call_name' ]; } else { if (isset($funcParam[ 'call_name_caching' ])) { $function = $funcParam[ 'call_name_caching' ]; } else { $function = $funcParam[ 'call_name' ]; } } if (function_exists($function)) { $this->saveTemplateVariables($tpl, $name); $function ($tpl, $params); $this->restoreTemplateVariables($tpl, $name); return; } // try to load template function dynamically if ($this->addTplFuncToCache($tpl, $name, $function)) { $this->saveTemplateVariables($tpl, $name); $function ($tpl, $params); $this->restoreTemplateVariables($tpl, $name); return; } } throw new SmartyException("Unable to find template function '{$name}'"); } /** * Register template functions defined by template * * @param \Smarty|\Smarty_Internal_Template|\Smarty_Internal_TemplateBase $obj * @param array $tplFunctions source information array of template functions defined in template * @param bool $override if true replace existing functions with same name */ public function registerTplFunctions(Smarty_Internal_TemplateBase $obj, $tplFunctions, $override = true) { $obj->tplFunctions = $override ? array_merge($obj->tplFunctions, $tplFunctions) : array_merge($tplFunctions, $obj->tplFunctions); // make sure that the template functions are known in parent templates if ($obj->_isSubTpl()) { $obj->smarty->ext->_tplFunction->registerTplFunctions($obj->parent, $tplFunctions, false); } else { $obj->smarty->tplFunctions = $override ? array_merge($obj->smarty->tplFunctions, $tplFunctions) : array_merge($tplFunctions, $obj->smarty->tplFunctions); } } /** * Return source parameter array for single or all template functions * * @param \Smarty_Internal_Template $tpl template object * @param null|string $name template function name * * @return array|bool|mixed */ public function getTplFunction(Smarty_Internal_Template $tpl, $name = null) { if (isset($name)) { return isset($tpl->tplFunctions[ $name ]) ? $tpl->tplFunctions[ $name ] : (isset($tpl->smarty->tplFunctions[ $name ]) ? $tpl->smarty->tplFunctions[ $name ] : false); } else { return empty($tpl->tplFunctions) ? $tpl->smarty->tplFunctions : $tpl->tplFunctions; } } /** * * Add template function to cache file for nocache calls * * @param Smarty_Internal_Template $tpl * @param string $_name template function name * @param string $_function PHP function name * * @return bool */ public function addTplFuncToCache(Smarty_Internal_Template $tpl, $_name, $_function) { $funcParam = $tpl->tplFunctions[ $_name ]; if (is_file($funcParam[ 'compiled_filepath' ])) { // read compiled file $code = file_get_contents($funcParam[ 'compiled_filepath' ]); // grab template function if (preg_match("/\/\* {$_function} \*\/([\S\s]*?)\/\*\/ {$_function} \*\//", $code, $match)) { // grab source info from file dependency preg_match("/\s*'{$funcParam['uid']}'([\S\s]*?)\),/", $code, $match1); unset($code); // make PHP function known eval($match[ 0 ]); if (function_exists($_function)) { // search cache file template $tplPtr = $tpl; while (!isset($tplPtr->cached) && isset($tplPtr->parent)) { $tplPtr = $tplPtr->parent; } // add template function code to cache file if (isset($tplPtr->cached)) { /* @var Smarty_Template_Cached $cache */ $cache = $tplPtr->cached; $content = $cache->read($tplPtr); if ($content) { // check if we must update file dependency if (!preg_match("/'{$funcParam['uid']}'(.*?)'nocache_hash'/", $content, $match2)) { $content = preg_replace("/('file_dependency'(.*?)\()/", "\\1{$match1[0]}", $content); } $tplPtr->smarty->ext->_updateCache->write($cache, $tplPtr, preg_replace('/\s*\?>\s*$/', "\n", $content) . "\n" . preg_replace(array('/^\s*<\?php\s+/', '/\s*\?>\s*$/',), "\n", $match[ 0 ])); } } return true; } } } return false; } /** * Save current template variables on stack * * @param \Smarty_Internal_Template $tpl * @param string $name stack name */ public function saveTemplateVariables(Smarty_Internal_Template $tpl, $name) { $tpl->_cache[ 'varStack' ][] = array('tpl' => $tpl->tpl_vars, 'config' => $tpl->config_vars, 'name' => "_tplFunction_{$name}"); } /** * Restore saved variables into template objects * * @param \Smarty_Internal_Template $tpl * @param string $name stack name */ public function restoreTemplateVariables(Smarty_Internal_Template $tpl, $name) { if (isset($tpl->_cache[ 'varStack' ])) { $vars = array_pop($tpl->_cache[ 'varStack' ]); $tpl->tpl_vars = $vars[ 'tpl' ]; $tpl->config_vars = $vars[ 'config' ]; } } }
php
Apache-2.0
2ba403cd277680a050c457d39db2aef652fb8e8f
2026-01-05T04:52:44.635355Z
false
xcg340122/PHP300Framework2x
https://github.com/xcg340122/PHP300Framework2x/blob/2ba403cd277680a050c457d39db2aef652fb8e8f/Extend/Package/smarty/sysplugins/smarty_internal_resource_stream.php
Extend/Package/smarty/sysplugins/smarty_internal_resource_stream.php
<?php /** * Smarty Internal Plugin Resource Stream * Implements the streams as resource for Smarty template * * @package Smarty * @subpackage TemplateResources * @author Uwe Tews * @author Rodney Rehm */ /** * Smarty Internal Plugin Resource Stream * Implements the streams as resource for Smarty template * * @link http://php.net/streams * @package Smarty * @subpackage TemplateResources */ class Smarty_Internal_Resource_Stream extends Smarty_Resource_Recompiled { /** * populate Source Object with meta data from Resource * * @param Smarty_Template_Source $source source object * @param Smarty_Internal_Template $_template template object * * @return void * @throws \SmartyException */ public function populate(Smarty_Template_Source $source, Smarty_Internal_Template $_template = null) { if (strpos($source->resource, '://') !== false) { $source->filepath = $source->resource; } else { $source->filepath = str_replace(':', '://', $source->resource); } $source->uid = false; $source->content = $this->getContent($source); $source->timestamp = $source->exists = !!$source->content; } /** * Load template's source from stream into current template object * * @param Smarty_Template_Source $source source object * * @return string template source * @throws SmartyException if source cannot be loaded */ public function getContent(Smarty_Template_Source $source) { $t = ''; // the availability of the stream has already been checked in Smarty_Resource::fetch() $fp = fopen($source->filepath, 'r+'); if ($fp) { while (!feof($fp) && ($current_line = fgets($fp)) !== false) { $t .= $current_line; } fclose($fp); return $t; } else { return false; } } /** * modify resource_name according to resource handlers specifications * * @param Smarty $smarty Smarty instance * @param string $resource_name resource_name to make unique * @param boolean $isConfig flag for config resource * * @return string unique resource name */ public function buildUniqueResourceName(Smarty $smarty, $resource_name, $isConfig = false) { return get_class($this) . '#' . $resource_name; } }
php
Apache-2.0
2ba403cd277680a050c457d39db2aef652fb8e8f
2026-01-05T04:52:44.635355Z
false
xcg340122/PHP300Framework2x
https://github.com/xcg340122/PHP300Framework2x/blob/2ba403cd277680a050c457d39db2aef652fb8e8f/Extend/Package/smarty/sysplugins/smarty_internal_compile_setfilter.php
Extend/Package/smarty/sysplugins/smarty_internal_compile_setfilter.php
<?php /** * Smarty Internal Plugin Compile Setfilter * Compiles code for setfilter tag * * @package Smarty * @subpackage Compiler * @author Uwe Tews */ /** * Smarty Internal Plugin Compile Setfilter Class * * @package Smarty * @subpackage Compiler */ class Smarty_Internal_Compile_Setfilter extends Smarty_Internal_CompileBase { /** * Compiles code for setfilter tag * * @param array $args array with attributes from parser * @param \Smarty_Internal_TemplateCompilerBase $compiler compiler object * @param array $parameter array with compilation parameter * * @return string compiled code */ public function compile($args, Smarty_Internal_TemplateCompilerBase $compiler, $parameter) { $compiler->variable_filter_stack[] = $compiler->variable_filters; $compiler->variable_filters = $parameter[ 'modifier_list' ]; // this tag does not return compiled code $compiler->has_code = false; return true; } } /** * Smarty Internal Plugin Compile Setfilterclose Class * * @package Smarty * @subpackage Compiler */ class Smarty_Internal_Compile_Setfilterclose extends Smarty_Internal_CompileBase { /** * Compiles code for the {/setfilter} tag * This tag does not generate compiled output. It resets variable filter. * * @param array $args array with attributes from parser * @param \Smarty_Internal_TemplateCompilerBase $compiler compiler object * * @return string compiled code */ public function compile($args, Smarty_Internal_TemplateCompilerBase $compiler) { $_attr = $this->getAttributes($compiler, $args); // reset variable filter to previous state if (count($compiler->variable_filter_stack)) { $compiler->variable_filters = array_pop($compiler->variable_filter_stack); } else { $compiler->variable_filters = array(); } // this tag does not return compiled code $compiler->has_code = false; return true; } }
php
Apache-2.0
2ba403cd277680a050c457d39db2aef652fb8e8f
2026-01-05T04:52:44.635355Z
false
xcg340122/PHP300Framework2x
https://github.com/xcg340122/PHP300Framework2x/blob/2ba403cd277680a050c457d39db2aef652fb8e8f/Extend/Package/smarty/sysplugins/smarty_internal_block.php
Extend/Package/smarty/sysplugins/smarty_internal_block.php
<?php /** * Smarty {block} tag class * * @package Smarty * @subpackage PluginsInternal * @author Uwe Tews */ class Smarty_Internal_Block { /** * Block name * * @var string */ public $name = ''; /** * Hide attribute * * @var bool */ public $hide = false; /** * Append attribute * * @var bool */ public $append = false; /** * prepend attribute * * @var bool */ public $prepend = false; /** * Block calls $smarty.block.child * * @var bool */ public $callsChild = false; /** * Inheritance child block * * @var Smarty_Internal_Block|null */ public $child = null; /** * Inheritance calling parent block * * @var Smarty_Internal_Block|null */ public $parent = null; /** * Inheritance Template index * * @var int */ public $tplIndex = 0; /** * Smarty_Internal_Block constructor. * - if outer level {block} of child template ($state === 1) save it as child root block * - otherwise process inheritance and render * * @param string $name block name * @param int|null $tplIndex index of outer level {block} if nested */ public function __construct($name, $tplIndex) { $this->name = $name; $this->tplIndex = $tplIndex; } /** * Compiled block code overloaded by {block} class * * @param \Smarty_Internal_Template $tpl */ public function callBlock(Smarty_Internal_Template $tpl) { } }
php
Apache-2.0
2ba403cd277680a050c457d39db2aef652fb8e8f
2026-01-05T04:52:44.635355Z
false
xcg340122/PHP300Framework2x
https://github.com/xcg340122/PHP300Framework2x/blob/2ba403cd277680a050c457d39db2aef652fb8e8f/Extend/Package/smarty/sysplugins/smarty_internal_method_assignbyref.php
Extend/Package/smarty/sysplugins/smarty_internal_method_assignbyref.php
<?php /** * Smarty Method AssignByRef * * Smarty::assignByRef() method * * @package Smarty * @subpackage PluginsInternal * @author Uwe Tews */ class Smarty_Internal_Method_AssignByRef { /** * assigns values to template variables by reference * * @param \Smarty_Internal_Data|\Smarty_Internal_Template|\Smarty $data * @param string $tpl_var the template variable name * @param $value * @param boolean $nocache if true any output of this variable will be not cached * * @return \Smarty_Internal_Data|\Smarty_Internal_Template|\Smarty */ public function assignByRef(Smarty_Internal_Data $data, $tpl_var, &$value, $nocache) { if ($tpl_var !== '') { $data->tpl_vars[ $tpl_var ] = new Smarty_Variable(null, $nocache); $data->tpl_vars[ $tpl_var ]->value = &$value; if ($data->_isTplObj() && $data->scope) { $data->ext->_updateScope->_updateScope($data, $tpl_var); } } return $data; } }
php
Apache-2.0
2ba403cd277680a050c457d39db2aef652fb8e8f
2026-01-05T04:52:44.635355Z
false
xcg340122/PHP300Framework2x
https://github.com/xcg340122/PHP300Framework2x/blob/2ba403cd277680a050c457d39db2aef652fb8e8f/Extend/Package/smarty/sysplugins/smarty_internal_templatelexer.php
Extend/Package/smarty/sysplugins/smarty_internal_templatelexer.php
<?php /* * This file is part of Smarty. * * (c) 2015 Uwe Tews * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ /** * Smarty_Internal_Templatelexer * This is the template file lexer. * It is generated from the smarty_internal_templatelexer.plex file * * * @author Uwe Tews <uwe.tews@googlemail.com> */ class Smarty_Internal_Templatelexer { const TEXT = 1; const TAG = 2; const TAGBODY = 3; const LITERAL = 4; const DOUBLEQUOTEDSTRING = 5; /** * Source * * @var string */ public $data; /** * Source length * * @var int */ public $dataLength = null; /** * byte counter * * @var int */ public $counter; /** * token number * * @var int */ public $token; /** * token value * * @var string */ public $value; /** * current line * * @var int */ public $line; /** * tag start line * * @var */ public $taglineno; /** * php code type * * @var string */ public $phpType = ''; /** * state number * * @var int */ public $state = 1; /** * Smarty object * * @var Smarty */ public $smarty = null; /** * compiler object * * @var Smarty_Internal_TemplateCompilerBase */ public $compiler = null; /** * trace file * * @var resource */ public $yyTraceFILE; /** * trace prompt * * @var string */ public $yyTracePrompt; /** * XML flag true while processing xml * * @var bool */ public $is_xml = false; /** * state names * * @var array */ public $state_name = array(1 => 'TEXT', 2 => 'TAG', 3 => 'TAGBODY', 4 => 'LITERAL', 5 => 'DOUBLEQUOTEDSTRING',); /** * token names * * @var array */ public $smarty_token_names = array( // Text for parser error messages 'NOT' => '(!,not)', 'OPENP' => '(', 'CLOSEP' => ')', 'OPENB' => '[', 'CLOSEB' => ']', 'PTR' => '->', 'APTR' => '=>', 'EQUAL' => '=', 'NUMBER' => 'number', 'UNIMATH' => '+" , "-', 'MATH' => '*" , "/" , "%', 'INCDEC' => '++" , "--', 'SPACE' => ' ', 'DOLLAR' => '$', 'SEMICOLON' => ';', 'COLON' => ':', 'DOUBLECOLON' => '::', 'AT' => '@', 'HATCH' => '#', 'QUOTE' => '"', 'BACKTICK' => '`', 'VERT' => '"|" modifier', 'DOT' => '.', 'COMMA' => '","', 'QMARK' => '"?"', 'ID' => 'id, name', 'TEXT' => 'text', 'LDELSLASH' => '{/..} closing tag', 'LDEL' => '{...} Smarty tag', 'COMMENT' => 'comment', 'AS' => 'as', 'TO' => 'to', 'PHP' => '"<?php", "<%", "{php}" tag', 'LOGOP' => '"<", "==" ... logical operator', 'TLOGOP' => '"lt", "eq" ... logical operator; "is div by" ... if condition', 'SCOND' => '"is even" ... if condition', ); /** * literal tag nesting level * * @var int */ private $literal_cnt = 0; /** * preg token pattern for state TEXT * * @var string */ private $yy_global_pattern1 = null; /** * preg token pattern for state TAG * * @var string */ private $yy_global_pattern2 = null; /** * preg token pattern for state TAGBODY * * @var string */ private $yy_global_pattern3 = null; /** * preg token pattern for state LITERAL * * @var string */ private $yy_global_pattern4 = null; /** * preg token pattern for state DOUBLEQUOTEDSTRING * * @var null */ private $yy_global_pattern5 = null; private $_yy_state = 1; private $_yy_stack = array(); /** * constructor * * @param string $source template source * @param Smarty_Internal_TemplateCompilerBase $compiler */ function __construct($source, Smarty_Internal_TemplateCompilerBase $compiler) { $this->data = $source; $this->dataLength = strlen($this->data); $this->counter = 0; if (preg_match('/^\xEF\xBB\xBF/i', $this->data, $match)) { $this->counter += strlen($match[ 0 ]); } $this->line = 1; $this->smarty = $compiler->template->smarty; $this->compiler = $compiler; $this->compiler->initDelimiterPreg(); $this->smarty_token_names[ 'LDEL' ] = $this->smarty->getLeftDelimiter(); $this->smarty_token_names[ 'RDEL' ] = $this->smarty->getRightDelimiter(); } /** * open lexer/parser trace file * */ public function PrintTrace() { $this->yyTraceFILE = fopen('php://output', 'w'); $this->yyTracePrompt = '<br>'; } /** * replace placeholders with runtime preg code * * @param string $preg * * @return string */ public function replace($preg) { return $this->compiler->replaceDelimiter($preg); } /** * check if current value is an autoliteral left delimiter * * @return bool */ public function isAutoLiteral() { return $this->smarty->getAutoLiteral() && isset($this->value[ $this->compiler->getLdelLength() ]) ? strpos(" \n\t\r", $this->value[ $this->compiler->getLdelLength() ]) !== false : false; } // end function public function yylex() { return $this->{'yylex' . $this->_yy_state}(); } public function yypushstate($state) { if ($this->yyTraceFILE) { fprintf($this->yyTraceFILE, "%sState push %s\n", $this->yyTracePrompt, isset($this->state_name[ $this->_yy_state ]) ? $this->state_name[ $this->_yy_state ] : $this->_yy_state); } array_push($this->_yy_stack, $this->_yy_state); $this->_yy_state = $state; if ($this->yyTraceFILE) { fprintf($this->yyTraceFILE, "%snew State %s\n", $this->yyTracePrompt, isset($this->state_name[ $this->_yy_state ]) ? $this->state_name[ $this->_yy_state ] : $this->_yy_state); } } public function yypopstate() { if ($this->yyTraceFILE) { fprintf($this->yyTraceFILE, "%sState pop %s\n", $this->yyTracePrompt, isset($this->state_name[ $this->_yy_state ]) ? $this->state_name[ $this->_yy_state ] : $this->_yy_state); } $this->_yy_state = array_pop($this->_yy_stack); if ($this->yyTraceFILE) { fprintf($this->yyTraceFILE, "%snew State %s\n", $this->yyTracePrompt, isset($this->state_name[ $this->_yy_state ]) ? $this->state_name[ $this->_yy_state ] : $this->_yy_state); } } public function yybegin($state) { $this->_yy_state = $state; if ($this->yyTraceFILE) { fprintf($this->yyTraceFILE, "%sState set %s\n", $this->yyTracePrompt, isset($this->state_name[ $this->_yy_state ]) ? $this->state_name[ $this->_yy_state ] : $this->_yy_state); } } public function yylex1() { if (!isset($this->yy_global_pattern1)) { $this->yy_global_pattern1 = $this->replace("/\G([{][}])|\G((SMARTYldel)SMARTYal[*])|\G((SMARTYldel)SMARTYalphp([ ].*?)?SMARTYrdel|(SMARTYldel)SMARTYal[\/]phpSMARTYrdel)|\G((SMARTYldel)SMARTYautoliteral\\s+SMARTYliteral)|\G((SMARTYldel)SMARTYalliteral\\s*SMARTYrdel)|\G((SMARTYldel)SMARTYal[\/]literal\\s*SMARTYrdel)|\G((SMARTYldel)SMARTYal)|\G([<][?]((php\\s+|=)|\\s+)|[<][%]|[<][?]xml\\s+|[<]script\\s+language\\s*=\\s*[\"']?\\s*php\\s*[\"']?\\s*[>]|[?][>]|[%][>])|\G((.*?)(?=((SMARTYldel)SMARTYal|[<][?]((php\\s+|=)|\\s+)|[<][%]|[<][?]xml\\s+|[<]script\\s+language\\s*=\\s*[\"']?\\s*php\\s*[\"']?\\s*[>]|[?][>]|[%][>]SMARTYliteral))|[\s\S]+)/isS"); } if (!isset($this->dataLength)) { $this->dataLength = strlen($this->data); } if ($this->counter >= $this->dataLength) { return false; // end of input } do { if (preg_match($this->yy_global_pattern1, $this->data, $yymatches, 0, $this->counter)) { if (!isset($yymatches[ 0 ][ 1 ])) { $yymatches = preg_grep("/(.|\s)+/", $yymatches); } else { $yymatches = array_filter($yymatches); } if (empty($yymatches)) { throw new Exception('Error: lexing failed because a rule matched' . ' an empty string. Input "' . substr($this->data, $this->counter, 5) . '... state TEXT'); } next($yymatches); // skip global match $this->token = key($yymatches); // token number $this->value = current($yymatches); // token value $r = $this->{'yy_r1_' . $this->token}(); if ($r === null) { $this->counter += strlen($this->value); $this->line += substr_count($this->value, "\n"); // accept this token return true; } else if ($r === true) { // we have changed state // process this token in the new state return $this->yylex(); } else if ($r === false) { $this->counter += strlen($this->value); $this->line += substr_count($this->value, "\n"); if ($this->counter >= $this->dataLength) { return false; // end of input } // skip this token continue; } } else { throw new Exception('Unexpected input at line' . $this->line . ': ' . $this->data[ $this->counter ]); } break; } while (true); } function yy_r1_1() { $this->token = Smarty_Internal_Templateparser::TP_TEXT; } function yy_r1_2() { preg_match("/[*]{$this->compiler->getRdelPreg()}[\n]?/", $this->data, $match, PREG_OFFSET_CAPTURE, $this->counter); if (isset($match[ 0 ][ 1 ])) { $to = $match[ 0 ][ 1 ] + strlen($match[ 0 ][ 0 ]); } else { $this->compiler->trigger_template_error("missing or misspelled comment closing tag '{$this->smarty->getRightDelimiter()}'"); } $this->value = substr($this->data, $this->counter, $to - $this->counter); return false; } function yy_r1_4() { $this->compiler->getTagCompiler('private_php')->parsePhp($this); } function yy_r1_8() { $this->token = Smarty_Internal_Templateparser::TP_TEXT; } function yy_r1_10() { $this->token = Smarty_Internal_Templateparser::TP_LITERALSTART; $this->yypushstate(self::LITERAL); } function yy_r1_12() { $this->token = Smarty_Internal_Templateparser::TP_LITERALEND; $this->yypushstate(self::LITERAL); } // end function function yy_r1_14() { $this->yypushstate(self::TAG); return true; } function yy_r1_16() { $this->compiler->getTagCompiler('private_php')->parsePhp($this); } function yy_r1_19() { $this->token = Smarty_Internal_Templateparser::TP_TEXT; } public function yylex2() { if (!isset($this->yy_global_pattern2)) { $this->yy_global_pattern2 = $this->replace("/\G((SMARTYldel)SMARTYal(if|elseif|else if|while)\\s+)|\G((SMARTYldel)SMARTYalfor\\s+)|\G((SMARTYldel)SMARTYalforeach(?![^\s]))|\G((SMARTYldel)SMARTYalsetfilter\\s+)|\G((SMARTYldel)SMARTYalmake_nocache\\s+)|\G((SMARTYldel)SMARTYal[0-9]*[a-zA-Z_]\\w*(\\s+nocache)?\\s*SMARTYrdel)|\G((SMARTYldel)SMARTYal[\/](?:(?!block)[0-9]*[a-zA-Z_]\\w*)\\s*SMARTYrdel)|\G((SMARTYldel)SMARTYal[$][0-9]*[a-zA-Z_]\\w*(\\s+nocache)?\\s*SMARTYrdel)|\G((SMARTYldel)SMARTYal[\/])|\G((SMARTYldel)SMARTYal)/isS"); } if (!isset($this->dataLength)) { $this->dataLength = strlen($this->data); } if ($this->counter >= $this->dataLength) { return false; // end of input } do { if (preg_match($this->yy_global_pattern2, $this->data, $yymatches, 0, $this->counter)) { if (!isset($yymatches[ 0 ][ 1 ])) { $yymatches = preg_grep("/(.|\s)+/", $yymatches); } else { $yymatches = array_filter($yymatches); } if (empty($yymatches)) { throw new Exception('Error: lexing failed because a rule matched' . ' an empty string. Input "' . substr($this->data, $this->counter, 5) . '... state TAG'); } next($yymatches); // skip global match $this->token = key($yymatches); // token number $this->value = current($yymatches); // token value $r = $this->{'yy_r2_' . $this->token}(); if ($r === null) { $this->counter += strlen($this->value); $this->line += substr_count($this->value, "\n"); // accept this token return true; } else if ($r === true) { // we have changed state // process this token in the new state return $this->yylex(); } else if ($r === false) { $this->counter += strlen($this->value); $this->line += substr_count($this->value, "\n"); if ($this->counter >= $this->dataLength) { return false; // end of input } // skip this token continue; } } else { throw new Exception('Unexpected input at line' . $this->line . ': ' . $this->data[ $this->counter ]); } break; } while (true); } function yy_r2_1() { $this->token = Smarty_Internal_Templateparser::TP_LDELIF; $this->yybegin(self::TAGBODY); $this->taglineno = $this->line; } function yy_r2_4() { $this->token = Smarty_Internal_Templateparser::TP_LDELFOR; $this->yybegin(self::TAGBODY); $this->taglineno = $this->line; } function yy_r2_6() { $this->token = Smarty_Internal_Templateparser::TP_LDELFOREACH; $this->yybegin(self::TAGBODY); $this->taglineno = $this->line; } function yy_r2_8() { $this->token = Smarty_Internal_Templateparser::TP_LDELSETFILTER; $this->yybegin(self::TAGBODY); $this->taglineno = $this->line; } function yy_r2_10() { $this->token = Smarty_Internal_Templateparser::TP_LDELMAKENOCACHE; $this->yybegin(self::TAGBODY); $this->taglineno = $this->line; } function yy_r2_12() { $this->yypopstate(); $this->token = Smarty_Internal_Templateparser::TP_SIMPLETAG; $this->taglineno = $this->line; } function yy_r2_15() { $this->yypopstate(); $this->token = Smarty_Internal_Templateparser::TP_CLOSETAG; $this->taglineno = $this->line; } function yy_r2_17() { if ($this->_yy_stack[ count($this->_yy_stack) - 1 ] === self::TEXT) { $this->yypopstate(); $this->token = Smarty_Internal_Templateparser::TP_SIMPELOUTPUT; $this->taglineno = $this->line; } else { $this->value = $this->smarty->getLeftDelimiter(); $this->token = Smarty_Internal_Templateparser::TP_LDEL; $this->yybegin(self::TAGBODY); $this->taglineno = $this->line; } } // end function function yy_r2_20() { $this->token = Smarty_Internal_Templateparser::TP_LDELSLASH; $this->yybegin(self::TAGBODY); $this->taglineno = $this->line; } function yy_r2_22() { $this->token = Smarty_Internal_Templateparser::TP_LDEL; $this->yybegin(self::TAGBODY); $this->taglineno = $this->line; } public function yylex3() { if (!isset($this->yy_global_pattern3)) { $this->yy_global_pattern3 = $this->replace("/\G(\\s*SMARTYrdel)|\G((SMARTYldel)SMARTYal)|\G([\"])|\G('[^'\\\\]*(?:\\\\.[^'\\\\]*)*')|\G([$][0-9]*[a-zA-Z_]\\w*)|\G([$])|\G(\\s+is\\s+in\\s+)|\G(\\s+as\\s+)|\G(\\s+to\\s+)|\G(\\s+step\\s+)|\G(\\s+instanceof\\s+)|\G(\\s*([!=][=]{1,2}|[<][=>]?|[>][=]?|[&|]{2})\\s*)|\G(\\s+(eq|ne|neq|gt|ge|gte|lt|le|lte|mod|and|or|xor)\\s+)|\G(\\s+is\\s+(not\\s+)?(odd|even|div)\\s+by\\s+)|\G(\\s+is\\s+(not\\s+)?(odd|even))|\G([!]\\s*|not\\s+)|\G([(](int(eger)?|bool(ean)?|float|double|real|string|binary|array|object)[)]\\s*)|\G(\\s*[(]\\s*)|\G(\\s*[)])|\G(\\[\\s*)|\G(\\s*\\])|\G(\\s*[-][>]\\s*)|\G(\\s*[=][>]\\s*)|\G(\\s*[=]\\s*)|\G(([+]|[-]){2})|\G(\\s*([+]|[-])\\s*)|\G(\\s*([*]{1,2}|[%\/^&]|[<>]{2})\\s*)|\G([@])|\G([#])|\G(\\s+[0-9]*[a-zA-Z_][a-zA-Z0-9_\-:]*\\s*[=]\\s*)|\G(([0-9]*[a-zA-Z_]\\w*)?(\\\\[0-9]*[a-zA-Z_]\\w*)+)|\G([0-9]*[a-zA-Z_]\\w*)|\G(\\d+)|\G([`])|\G([|][@]?)|\G([.])|\G(\\s*[,]\\s*)|\G(\\s*[;]\\s*)|\G([:]{2})|\G(\\s*[:]\\s*)|\G(\\s*[?]\\s*)|\G(0[xX][0-9a-fA-F]+)|\G(\\s+)|\G([\S\s])/isS"); } if (!isset($this->dataLength)) { $this->dataLength = strlen($this->data); } if ($this->counter >= $this->dataLength) { return false; // end of input } do { if (preg_match($this->yy_global_pattern3, $this->data, $yymatches, 0, $this->counter)) { if (!isset($yymatches[ 0 ][ 1 ])) { $yymatches = preg_grep("/(.|\s)+/", $yymatches); } else { $yymatches = array_filter($yymatches); } if (empty($yymatches)) { throw new Exception('Error: lexing failed because a rule matched' . ' an empty string. Input "' . substr($this->data, $this->counter, 5) . '... state TAGBODY'); } next($yymatches); // skip global match $this->token = key($yymatches); // token number $this->value = current($yymatches); // token value $r = $this->{'yy_r3_' . $this->token}(); if ($r === null) { $this->counter += strlen($this->value); $this->line += substr_count($this->value, "\n"); // accept this token return true; } else if ($r === true) { // we have changed state // process this token in the new state return $this->yylex(); } else if ($r === false) { $this->counter += strlen($this->value); $this->line += substr_count($this->value, "\n"); if ($this->counter >= $this->dataLength) { return false; // end of input } // skip this token continue; } } else { throw new Exception('Unexpected input at line' . $this->line . ': ' . $this->data[ $this->counter ]); } break; } while (true); } function yy_r3_1() { $this->token = Smarty_Internal_Templateparser::TP_RDEL; $this->yypopstate(); } function yy_r3_2() { $this->yypushstate(self::TAG); return true; } function yy_r3_4() { $this->token = Smarty_Internal_Templateparser::TP_QUOTE; $this->yypushstate(self::DOUBLEQUOTEDSTRING); $this->compiler->enterDoubleQuote(); } function yy_r3_5() { $this->token = Smarty_Internal_Templateparser::TP_SINGLEQUOTESTRING; } function yy_r3_6() { $this->token = Smarty_Internal_Templateparser::TP_DOLLARID; } function yy_r3_7() { $this->token = Smarty_Internal_Templateparser::TP_DOLLAR; } function yy_r3_8() { $this->token = Smarty_Internal_Templateparser::TP_ISIN; } function yy_r3_9() { $this->token = Smarty_Internal_Templateparser::TP_AS; } function yy_r3_10() { $this->token = Smarty_Internal_Templateparser::TP_TO; } function yy_r3_11() { $this->token = Smarty_Internal_Templateparser::TP_STEP; } function yy_r3_12() { $this->token = Smarty_Internal_Templateparser::TP_INSTANCEOF; } function yy_r3_13() { $this->token = Smarty_Internal_Templateparser::TP_LOGOP; } function yy_r3_15() { $this->token = Smarty_Internal_Templateparser::TP_SLOGOP; } function yy_r3_17() { $this->token = Smarty_Internal_Templateparser::TP_TLOGOP; } function yy_r3_20() { $this->token = Smarty_Internal_Templateparser::TP_SINGLECOND; } function yy_r3_23() { $this->token = Smarty_Internal_Templateparser::TP_NOT; } function yy_r3_24() { $this->token = Smarty_Internal_Templateparser::TP_TYPECAST; } function yy_r3_28() { $this->token = Smarty_Internal_Templateparser::TP_OPENP; } function yy_r3_29() { $this->token = Smarty_Internal_Templateparser::TP_CLOSEP; } function yy_r3_30() { $this->token = Smarty_Internal_Templateparser::TP_OPENB; } function yy_r3_31() { $this->token = Smarty_Internal_Templateparser::TP_CLOSEB; } function yy_r3_32() { $this->token = Smarty_Internal_Templateparser::TP_PTR; } function yy_r3_33() { $this->token = Smarty_Internal_Templateparser::TP_APTR; } function yy_r3_34() { $this->token = Smarty_Internal_Templateparser::TP_EQUAL; } function yy_r3_35() { $this->token = Smarty_Internal_Templateparser::TP_INCDEC; } function yy_r3_37() { $this->token = Smarty_Internal_Templateparser::TP_UNIMATH; } function yy_r3_39() { $this->token = Smarty_Internal_Templateparser::TP_MATH; } function yy_r3_41() { $this->token = Smarty_Internal_Templateparser::TP_AT; } function yy_r3_42() { $this->token = Smarty_Internal_Templateparser::TP_HATCH; } function yy_r3_43() { // resolve conflicts with shorttag and right_delimiter starting with '=' if (substr($this->data, $this->counter + strlen($this->value) - 1, $this->compiler->getRdelLength()) === $this->smarty->getRightDelimiter()) { preg_match('/\s+/', $this->value, $match); $this->value = $match[ 0 ]; $this->token = Smarty_Internal_Templateparser::TP_SPACE; } else { $this->token = Smarty_Internal_Templateparser::TP_ATTR; } } function yy_r3_44() { $this->token = Smarty_Internal_Templateparser::TP_NAMESPACE; } function yy_r3_47() { $this->token = Smarty_Internal_Templateparser::TP_ID; } function yy_r3_48() { $this->token = Smarty_Internal_Templateparser::TP_INTEGER; } function yy_r3_49() { $this->token = Smarty_Internal_Templateparser::TP_BACKTICK; $this->yypopstate(); } function yy_r3_50() { $this->token = Smarty_Internal_Templateparser::TP_VERT; } function yy_r3_51() { $this->token = Smarty_Internal_Templateparser::TP_DOT; } function yy_r3_52() { $this->token = Smarty_Internal_Templateparser::TP_COMMA; } function yy_r3_53() { $this->token = Smarty_Internal_Templateparser::TP_SEMICOLON; } function yy_r3_54() { $this->token = Smarty_Internal_Templateparser::TP_DOUBLECOLON; } function yy_r3_55() { $this->token = Smarty_Internal_Templateparser::TP_COLON; } function yy_r3_56() { $this->token = Smarty_Internal_Templateparser::TP_QMARK; } function yy_r3_57() { $this->token = Smarty_Internal_Templateparser::TP_HEX; } function yy_r3_58() { $this->token = Smarty_Internal_Templateparser::TP_SPACE; } // end function function yy_r3_59() { $this->token = Smarty_Internal_Templateparser::TP_TEXT; } public function yylex4() { if (!isset($this->yy_global_pattern4)) { $this->yy_global_pattern4 = $this->replace("/\G((SMARTYldel)SMARTYalliteral\\s*SMARTYrdel)|\G((SMARTYldel)SMARTYal[\/]literal\\s*SMARTYrdel)|\G((.*?)(?=(SMARTYldel)SMARTYal[\/]?literalSMARTYrdel))/isS"); } if (!isset($this->dataLength)) { $this->dataLength = strlen($this->data); } if ($this->counter >= $this->dataLength) { return false; // end of input } do { if (preg_match($this->yy_global_pattern4, $this->data, $yymatches, 0, $this->counter)) { if (!isset($yymatches[ 0 ][ 1 ])) { $yymatches = preg_grep("/(.|\s)+/", $yymatches); } else { $yymatches = array_filter($yymatches); } if (empty($yymatches)) { throw new Exception('Error: lexing failed because a rule matched' . ' an empty string. Input "' . substr($this->data, $this->counter, 5) . '... state LITERAL'); } next($yymatches); // skip global match $this->token = key($yymatches); // token number $this->value = current($yymatches); // token value $r = $this->{'yy_r4_' . $this->token}(); if ($r === null) { $this->counter += strlen($this->value); $this->line += substr_count($this->value, "\n"); // accept this token return true; } else if ($r === true) { // we have changed state // process this token in the new state return $this->yylex(); } else if ($r === false) { $this->counter += strlen($this->value); $this->line += substr_count($this->value, "\n"); if ($this->counter >= $this->dataLength) { return false; // end of input } // skip this token continue; } } else { throw new Exception('Unexpected input at line' . $this->line . ': ' . $this->data[ $this->counter ]); } break; } while (true); } function yy_r4_1() { $this->literal_cnt++; $this->token = Smarty_Internal_Templateparser::TP_LITERAL; } function yy_r4_3() { if ($this->literal_cnt) { $this->literal_cnt--; $this->token = Smarty_Internal_Templateparser::TP_LITERAL; } else { $this->token = Smarty_Internal_Templateparser::TP_LITERALEND; $this->yypopstate(); } } function yy_r4_5() { $this->token = Smarty_Internal_Templateparser::TP_LITERAL; } // end function public function yylex5() { if (!isset($this->yy_global_pattern5)) { $this->yy_global_pattern5 = $this->replace("/\G((SMARTYldel)SMARTYautoliteral\\s+SMARTYliteral)|\G((SMARTYldel)SMARTYalliteral\\s*SMARTYrdel)|\G((SMARTYldel)SMARTYal[\/]literal\\s*SMARTYrdel)|\G((SMARTYldel)SMARTYal[\/])|\G((SMARTYldel)SMARTYal[0-9]*[a-zA-Z_]\\w*)|\G((SMARTYldel)SMARTYal)|\G([\"])|\G([`][$])|\G([$][0-9]*[a-zA-Z_]\\w*)|\G([$])|\G(([^\"\\\\]*?)((?:\\\\.[^\"\\\\]*?)*?)(?=((SMARTYldel)SMARTYal|\\$|`\\$|\"SMARTYliteral)))/isS"); } if (!isset($this->dataLength)) { $this->dataLength = strlen($this->data); } if ($this->counter >= $this->dataLength) { return false; // end of input } do { if (preg_match($this->yy_global_pattern5, $this->data, $yymatches, 0, $this->counter)) { if (!isset($yymatches[ 0 ][ 1 ])) { $yymatches = preg_grep("/(.|\s)+/", $yymatches); } else { $yymatches = array_filter($yymatches); } if (empty($yymatches)) { throw new Exception('Error: lexing failed because a rule matched' . ' an empty string. Input "' . substr($this->data, $this->counter, 5) . '... state DOUBLEQUOTEDSTRING'); } next($yymatches); // skip global match $this->token = key($yymatches); // token number $this->value = current($yymatches); // token value $r = $this->{'yy_r5_' . $this->token}(); if ($r === null) { $this->counter += strlen($this->value);
php
Apache-2.0
2ba403cd277680a050c457d39db2aef652fb8e8f
2026-01-05T04:52:44.635355Z
true
xcg340122/PHP300Framework2x
https://github.com/xcg340122/PHP300Framework2x/blob/2ba403cd277680a050c457d39db2aef652fb8e8f/Extend/Package/smarty/sysplugins/smarty_internal_errorhandler.php
Extend/Package/smarty/sysplugins/smarty_internal_errorhandler.php
<?php /** * Smarty error handler * * * @package Smarty * @subpackage PluginsInternal * @author Uwe Tews * * @deprecated Smarty does no longer use @filemtime() */ class Smarty_Internal_ErrorHandler { /** * contains directories outside of SMARTY_DIR that are to be muted by muteExpectedErrors() */ public static $mutedDirectories = array(); /** * error handler returned by set_error_handler() in self::muteExpectedErrors() */ private static $previousErrorHandler = null; /** * Enable error handler to mute expected messages * * @return boolean */ public static function muteExpectedErrors() { /* error muting is done because some people implemented custom error_handlers using http://php.net/set_error_handler and for some reason did not understand the following paragraph: It is important to remember that the standard PHP error handler is completely bypassed for the error types specified by error_types unless the callback function returns FALSE. error_reporting() settings will have no effect and your error handler will be called regardless - however you are still able to read the current value of error_reporting and act appropriately. Of particular note is that this value will be 0 if the statement that caused the error was prepended by the @ error-control operator. Smarty deliberately uses @filemtime() over file_exists() and filemtime() in some places. Reasons include - @filemtime() is almost twice as fast as using an additional file_exists() - between file_exists() and filemtime() a possible race condition is opened, which does not exist using the simple @filemtime() approach. */ $error_handler = array('Smarty_Internal_ErrorHandler', 'mutingErrorHandler'); $previous = set_error_handler($error_handler); // avoid dead loops if ($previous !== $error_handler) { self::$previousErrorHandler = $previous; } } /** * Error Handler to mute expected messages * * @link http://php.net/set_error_handler * * @param integer $errno Error level * @param $errstr * @param $errfile * @param $errline * @param $errcontext * * @return bool */ public static function mutingErrorHandler($errno, $errstr, $errfile, $errline, $errcontext) { $_is_muted_directory = false; // add the SMARTY_DIR to the list of muted directories if (!isset(self::$mutedDirectories[ SMARTY_DIR ])) { $smarty_dir = realpath(SMARTY_DIR); if ($smarty_dir !== false) { self::$mutedDirectories[ SMARTY_DIR ] = array('file' => $smarty_dir, 'length' => strlen($smarty_dir),); } } // walk the muted directories and test against $errfile foreach (self::$mutedDirectories as $key => &$dir) { if (!$dir) { // resolve directory and length for speedy comparisons $file = realpath($key); if ($file === false) { // this directory does not exist, remove and skip it unset(self::$mutedDirectories[ $key ]); continue; } $dir = array('file' => $file, 'length' => strlen($file),); } if (!strncmp($errfile, $dir[ 'file' ], $dir[ 'length' ])) { $_is_muted_directory = true; break; } } // pass to next error handler if this error did not occur inside SMARTY_DIR // or the error was within smarty but masked to be ignored if (!$_is_muted_directory || ($errno && $errno & error_reporting())) { if (self::$previousErrorHandler) { return call_user_func(self::$previousErrorHandler, $errno, $errstr, $errfile, $errline, $errcontext); } else { return false; } } } }
php
Apache-2.0
2ba403cd277680a050c457d39db2aef652fb8e8f
2026-01-05T04:52:44.635355Z
false
xcg340122/PHP300Framework2x
https://github.com/xcg340122/PHP300Framework2x/blob/2ba403cd277680a050c457d39db2aef652fb8e8f/Extend/Package/smarty/sysplugins/smarty_internal_runtime_codeframe.php
Extend/Package/smarty/sysplugins/smarty_internal_runtime_codeframe.php
<?php /** * Smarty Internal Extension * This file contains the Smarty template extension to create a code frame * * @package Smarty * @subpackage Template * @author Uwe Tews */ /** * Class Smarty_Internal_Extension_CodeFrame * Create code frame for compiled and cached templates */ class Smarty_Internal_Runtime_CodeFrame { /** * Create code frame for compiled and cached templates * * @param Smarty_Internal_Template $_template * @param string $content optional template content * @param string $functions compiled template function and block code * @param bool $cache flag for cache file * @param \Smarty_Internal_TemplateCompilerBase $compiler * * @return string */ public function create(Smarty_Internal_Template $_template, $content = '', $functions = '', $cache = false, Smarty_Internal_TemplateCompilerBase $compiler = null) { // build property code $properties[ 'version' ] = Smarty::SMARTY_VERSION; $properties[ 'unifunc' ] = 'content_' . str_replace(array('.', ','), '_', uniqid('', true)); if (!$cache) { $properties[ 'has_nocache_code' ] = $_template->compiled->has_nocache_code; $properties[ 'file_dependency' ] = $_template->compiled->file_dependency; $properties[ 'includes' ] = $_template->compiled->includes; } else { $properties[ 'has_nocache_code' ] = $_template->cached->has_nocache_code; $properties[ 'file_dependency' ] = $_template->cached->file_dependency; $properties[ 'cache_lifetime' ] = $_template->cache_lifetime; } $output = "<?php\n"; $output .= "/* Smarty version {$properties[ 'version' ]}, created on " . strftime("%Y-%m-%d %H:%M:%S") . "\n from '" . str_replace('*/','* /',$_template->source->filepath) . "' */\n\n"; $output .= "/* @var Smarty_Internal_Template \$_smarty_tpl */\n"; $dec = "\$_smarty_tpl->_decodeProperties(\$_smarty_tpl, " . var_export($properties, true) . ',' . ($cache ? 'true' : 'false') . ')'; $output .= "if ({$dec}) {\n"; $output .= "function {$properties['unifunc']} (Smarty_Internal_Template \$_smarty_tpl) {\n"; if (!$cache && !empty($compiler->tpl_function)) { $output .= '$_smarty_tpl->smarty->ext->_tplFunction->registerTplFunctions($_smarty_tpl, '; $output .= var_export($compiler->tpl_function, true); $output .= ");\n"; } if ($cache && isset($_template->smarty->ext->_tplFunction)) { $output .= "\$_smarty_tpl->smarty->ext->_tplFunction->registerTplFunctions(\$_smarty_tpl, " . var_export($_template->smarty->ext->_tplFunction->getTplFunction($_template), true) . ");\n"; } // include code for plugins if (!$cache) { if (!empty($_template->compiled->required_plugins[ 'compiled' ])) { foreach ($_template->compiled->required_plugins[ 'compiled' ] as $tmp) { foreach ($tmp as $data) { $file = addslashes($data[ 'file' ]); if (is_array($data[ 'function' ])) { $output .= "if (!is_callable(array('{$data['function'][0]}','{$data['function'][1]}'))) require_once '{$file}';\n"; } else { $output .= "if (!is_callable('{$data['function']}')) require_once '{$file}';\n"; } } } } if ($_template->caching && !empty($_template->compiled->required_plugins[ 'nocache' ])) { $_template->compiled->has_nocache_code = true; $output .= "echo '/*%%SmartyNocache:{$_template->compiled->nocache_hash}%%*/<?php \$_smarty = \$_smarty_tpl->smarty; "; foreach ($_template->compiled->required_plugins[ 'nocache' ] as $tmp) { foreach ($tmp as $data) { $file = addslashes($data[ 'file' ]); if (is_array($data[ 'function' ])) { $output .= addslashes("if (!is_callable(array('{$data['function'][0]}','{$data['function'][1]}'))) require_once '{$file}';\n"); } else { $output .= addslashes("if (!is_callable('{$data['function']}')) require_once '{$file}';\n"); } } } $output .= "?>/*/%%SmartyNocache:{$_template->compiled->nocache_hash}%%*/';\n"; } } $output .= "?>"; $output .= $content; $output .= "<?php }\n?>"; $output .= $functions; $output .= "<?php }\n"; // remove unneeded PHP tags return preg_replace(array('/\s*\?>[\n]?<\?php\s*/', '/\?>\s*$/'), array("\n", ''), $output); } }
php
Apache-2.0
2ba403cd277680a050c457d39db2aef652fb8e8f
2026-01-05T04:52:44.635355Z
false
xcg340122/PHP300Framework2x
https://github.com/xcg340122/PHP300Framework2x/blob/2ba403cd277680a050c457d39db2aef652fb8e8f/Extend/Package/smarty/sysplugins/smarty_internal_compile_private_function_plugin.php
Extend/Package/smarty/sysplugins/smarty_internal_compile_private_function_plugin.php
<?php /** * Smarty Internal Plugin Compile Function Plugin * Compiles code for the execution of function plugin * * @package Smarty * @subpackage Compiler * @author Uwe Tews */ /** * Smarty Internal Plugin Compile Function Plugin Class * * @package Smarty * @subpackage Compiler */ class Smarty_Internal_Compile_Private_Function_Plugin extends Smarty_Internal_CompileBase { /** * Attribute definition: Overwrites base class. * * @var array * @see Smarty_Internal_CompileBase */ public $required_attributes = array(); /** * Attribute definition: Overwrites base class. * * @var array * @see Smarty_Internal_CompileBase */ public $optional_attributes = array('_any'); /** * Compiles code for the execution of function plugin * * @param array $args array with attributes from parser * @param \Smarty_Internal_TemplateCompilerBase $compiler compiler object * @param array $parameter array with compilation parameter * @param string $tag name of function plugin * @param string $function PHP function name * * @return string compiled code * @throws \SmartyCompilerException * @throws \SmartyException */ public function compile($args, Smarty_Internal_TemplateCompilerBase $compiler, $parameter, $tag, $function) { // check and get attributes $_attr = $this->getAttributes($compiler, $args); unset($_attr[ 'nocache' ]); // convert attributes into parameter array string $_paramsArray = array(); foreach ($_attr as $_key => $_value) { if (is_int($_key)) { $_paramsArray[] = "$_key=>$_value"; } else { $_paramsArray[] = "'$_key'=>$_value"; } } $_params = 'array(' . implode(',', $_paramsArray) . ')'; // compile code $output = "{$function}({$_params},\$_smarty_tpl)"; if (!empty($parameter[ 'modifierlist' ])) { $output = $compiler->compileTag('private_modifier', array(), array('modifierlist' => $parameter[ 'modifierlist' ], 'value' => $output)); } $output = "<?php echo {$output};?>\n"; return $output; } }
php
Apache-2.0
2ba403cd277680a050c457d39db2aef652fb8e8f
2026-01-05T04:52:44.635355Z
false
xcg340122/PHP300Framework2x
https://github.com/xcg340122/PHP300Framework2x/blob/2ba403cd277680a050c457d39db2aef652fb8e8f/Extend/Package/smarty/sysplugins/smarty_internal_compile_call.php
Extend/Package/smarty/sysplugins/smarty_internal_compile_call.php
<?php /** * Smarty Internal Plugin Compile Function_Call * Compiles the calls of user defined tags defined by {function} * * @package Smarty * @subpackage Compiler * @author Uwe Tews */ /** * Smarty Internal Plugin Compile Function_Call Class * * @package Smarty * @subpackage Compiler */ class Smarty_Internal_Compile_Call extends Smarty_Internal_CompileBase { /** * Attribute definition: Overwrites base class. * * @var array * @see Smarty_Internal_CompileBase */ public $required_attributes = array('name'); /** * Attribute definition: Overwrites base class. * * @var array * @see Smarty_Internal_CompileBase */ public $shorttag_order = array('name'); /** * Attribute definition: Overwrites base class. * * @var array * @see Smarty_Internal_CompileBase */ public $optional_attributes = array('_any'); /** * Compiles the calls of user defined tags defined by {function} * * @param array $args array with attributes from parser * @param object $compiler compiler object * * @return string compiled code */ public function compile($args, $compiler) { // check and get attributes $_attr = $this->getAttributes($compiler, $args); // save possible attributes if (isset($_attr[ 'assign' ])) { // output will be stored in a smarty variable instead of being displayed $_assign = $_attr[ 'assign' ]; } //$_name = trim($_attr['name'], "''"); $_name = $_attr[ 'name' ]; unset($_attr[ 'name' ], $_attr[ 'assign' ], $_attr[ 'nocache' ]); // set flag (compiled code of {function} must be included in cache file if (!$compiler->template->caching || $compiler->nocache || $compiler->tag_nocache) { $_nocache = 'true'; } else { $_nocache = 'false'; } $_paramsArray = array(); foreach ($_attr as $_key => $_value) { if (is_int($_key)) { $_paramsArray[] = "$_key=>$_value"; } else { $_paramsArray[] = "'$_key'=>$_value"; } } $_params = 'array(' . implode(',', $_paramsArray) . ')'; //$compiler->suppressNocacheProcessing = true; // was there an assign attribute if (isset($_assign)) { $_output = "<?php ob_start();\n\$_smarty_tpl->smarty->ext->_tplFunction->callTemplateFunction(\$_smarty_tpl, {$_name}, {$_params}, {$_nocache});\n\$_smarty_tpl->assign({$_assign}, ob_get_clean());?>\n"; } else { $_output = "<?php \$_smarty_tpl->smarty->ext->_tplFunction->callTemplateFunction(\$_smarty_tpl, {$_name}, {$_params}, {$_nocache});?>\n"; } return $_output; } }
php
Apache-2.0
2ba403cd277680a050c457d39db2aef652fb8e8f
2026-01-05T04:52:44.635355Z
false
xcg340122/PHP300Framework2x
https://github.com/xcg340122/PHP300Framework2x/blob/2ba403cd277680a050c457d39db2aef652fb8e8f/Extend/Package/smarty/sysplugins/smarty_internal_method_getstreamvariable.php
Extend/Package/smarty/sysplugins/smarty_internal_method_getstreamvariable.php
<?php /** * Smarty Method GetStreamVariable * * Smarty::getStreamVariable() method * * @package Smarty * @subpackage PluginsInternal * @author Uwe Tews */ class Smarty_Internal_Method_GetStreamVariable { /** * Valid for all objects * * @var int */ public $objMap = 7; /** * gets a stream variable * * @api Smarty::getStreamVariable() * * @param \Smarty_Internal_Data|\Smarty_Internal_Template|\Smarty $data * @param string $variable the stream of the variable * * @return mixed * @throws \SmartyException */ public function getStreamVariable(Smarty_Internal_Data $data, $variable) { $_result = ''; $fp = fopen($variable, 'r+'); if ($fp) { while (!feof($fp) && ($current_line = fgets($fp)) !== false) { $_result .= $current_line; } fclose($fp); return $_result; } $smarty = isset($data->smarty) ? $data->smarty : $data; if ($smarty->error_unassigned) { throw new SmartyException('Undefined stream variable "' . $variable . '"'); } else { return null; } } }
php
Apache-2.0
2ba403cd277680a050c457d39db2aef652fb8e8f
2026-01-05T04:52:44.635355Z
false
xcg340122/PHP300Framework2x
https://github.com/xcg340122/PHP300Framework2x/blob/2ba403cd277680a050c457d39db2aef652fb8e8f/Extend/Package/smarty/sysplugins/smarty_internal_parsetree_tag.php
Extend/Package/smarty/sysplugins/smarty_internal_parsetree_tag.php
<?php /** * Smarty Internal Plugin Templateparser Parse Tree * These are classes to build parse tree in the template parser * * @package Smarty * @subpackage Compiler * @author Thue Kristensen * @author Uwe Tews */ /** * A complete smarty tag. * * @package Smarty * @subpackage Compiler * @ignore */ class Smarty_Internal_ParseTree_Tag extends Smarty_Internal_ParseTree { /** * Saved block nesting level * * @var int */ public $saved_block_nesting; /** * Create parse tree buffer for Smarty tag * * @param \Smarty_Internal_Templateparser $parser parser object * @param string $data content */ public function __construct(Smarty_Internal_Templateparser $parser, $data) { $this->data = $data; $this->saved_block_nesting = $parser->block_nesting_level; } /** * Return buffer content * * @param \Smarty_Internal_Templateparser $parser * * @return string content */ public function to_smarty_php(Smarty_Internal_Templateparser $parser) { return $this->data; } /** * Return complied code that loads the evaluated output of buffer content into a temporary variable * * @param \Smarty_Internal_Templateparser $parser * * @return string template code */ public function assign_to_var(Smarty_Internal_Templateparser $parser) { $var = $parser->compiler->getNewPrefixVariable(); $tmp = $parser->compiler->appendCode('<?php ob_start();?>', $this->data); $tmp = $parser->compiler->appendCode($tmp, "<?php {$var}=ob_get_clean();?>"); $parser->compiler->prefix_code[] = sprintf('%s', $tmp); return $var; } }
php
Apache-2.0
2ba403cd277680a050c457d39db2aef652fb8e8f
2026-01-05T04:52:44.635355Z
false
xcg340122/PHP300Framework2x
https://github.com/xcg340122/PHP300Framework2x/blob/2ba403cd277680a050c457d39db2aef652fb8e8f/Extend/Package/smarty/sysplugins/smarty_internal_method_compileallconfig.php
Extend/Package/smarty/sysplugins/smarty_internal_method_compileallconfig.php
<?php /** * Smarty Method CompileAllConfig * * Smarty::compileAllConfig() method * * @package Smarty * @subpackage PluginsInternal * @author Uwe Tews */ class Smarty_Internal_Method_CompileAllConfig extends Smarty_Internal_Method_CompileAllTemplates { /** * Compile all config files * * @api Smarty::compileAllConfig() * * @param \Smarty $smarty passed smarty object * @param string $extension file extension * @param bool $force_compile force all to recompile * @param int $time_limit * @param int $max_errors * * @return int number of template files recompiled */ public function compileAllConfig(Smarty $smarty, $extension = '.conf', $force_compile = false, $time_limit = 0, $max_errors = null) { return $this->compileAll($smarty, $extension, $force_compile, $time_limit, $max_errors, true); } }
php
Apache-2.0
2ba403cd277680a050c457d39db2aef652fb8e8f
2026-01-05T04:52:44.635355Z
false
xcg340122/PHP300Framework2x
https://github.com/xcg340122/PHP300Framework2x/blob/2ba403cd277680a050c457d39db2aef652fb8e8f/Extend/Package/smarty/sysplugins/smarty_internal_runtime_getincludepath.php
Extend/Package/smarty/sysplugins/smarty_internal_runtime_getincludepath.php
<?php /** * Smarty read include path plugin * * @package Smarty * @subpackage PluginsInternal * @author Monte Ohrt */ /** * Smarty Internal Read Include Path Class * * @package Smarty * @subpackage PluginsInternal */ class Smarty_Internal_Runtime_GetIncludePath { /** * include path cache * * @var string */ public $_include_path = ''; /** * include path directory cache * * @var array */ public $_include_dirs = array(); /** * include path directory cache * * @var array */ public $_user_dirs = array(); /** * stream cache * * @var string[][] */ public $isFile = array(); /** * stream cache * * @var string[] */ public $isPath = array(); /** * stream cache * * @var int[] */ public $number = array(); /** * status cache * * @var bool */ public $_has_stream_include = null; /** * Number for array index * * @var int */ public $counter = 0; /** * Check if include path was updated * * @param \Smarty $smarty * * @return bool */ public function isNewIncludePath(Smarty $smarty) { $_i_path = get_include_path(); if ($this->_include_path !== $_i_path) { $this->_include_dirs = array(); $this->_include_path = $_i_path; $_dirs = (array)explode(PATH_SEPARATOR, $_i_path); foreach ($_dirs as $_path) { if (is_dir($_path)) { $this->_include_dirs[] = $smarty->_realpath($_path . DIRECTORY_SEPARATOR, true); } } return true; } return false; } /** * return array with include path directories * * @param \Smarty $smarty * * @return array */ public function getIncludePathDirs(Smarty $smarty) { $this->isNewIncludePath($smarty); return $this->_include_dirs; } /** * Return full file path from PHP include_path * * @param string[] $dirs * @param string $file * @param \Smarty $smarty * * @return bool|string full filepath or false * */ public function getIncludePath($dirs, $file, Smarty $smarty) { //if (!(isset($this->_has_stream_include) ? $this->_has_stream_include : $this->_has_stream_include = false)) { if (!(isset($this->_has_stream_include) ? $this->_has_stream_include : $this->_has_stream_include = function_exists('stream_resolve_include_path')) ) { $this->isNewIncludePath($smarty); } // try PHP include_path foreach ($dirs as $dir) { $dir_n = isset($this->number[ $dir ]) ? $this->number[ $dir ] : $this->number[ $dir ] = $this->counter++; if (isset($this->isFile[ $dir_n ][ $file ])) { if ($this->isFile[ $dir_n ][ $file ]) { return $this->isFile[ $dir_n ][ $file ]; } else { continue; } } if (isset($this->_user_dirs[ $dir_n ])) { if (false === $this->_user_dirs[ $dir_n ]) { continue; } else { $dir = $this->_user_dirs[ $dir_n ]; } } else { if ($dir[ 0 ] === '/' || $dir[ 1 ] === ':') { $dir = str_ireplace(getcwd(), '.', $dir); if ($dir[ 0 ] === '/' || $dir[ 1 ] === ':') { $this->_user_dirs[ $dir_n ] = false; continue; } } $dir = substr($dir, 2); $this->_user_dirs[ $dir_n ] = $dir; } if ($this->_has_stream_include) { $path = stream_resolve_include_path($dir . (isset($file) ? $file : '')); if ($path) { return $this->isFile[ $dir_n ][ $file ] = $path; } } else { foreach ($this->_include_dirs as $key => $_i_path) { $path = isset($this->isPath[ $key ][ $dir_n ]) ? $this->isPath[ $key ][ $dir_n ] : $this->isPath[ $key ][ $dir_n ] = is_dir($_dir_path = $_i_path . $dir) ? $_dir_path : false; if ($path === false) { continue; } if (isset($file)) { $_file = $this->isFile[ $dir_n ][ $file ] = (is_file($path . $file)) ? $path . $file : false; if ($_file) { return $_file; } } else { // no file was given return directory path return $path; } } } } return false; } }
php
Apache-2.0
2ba403cd277680a050c457d39db2aef652fb8e8f
2026-01-05T04:52:44.635355Z
false
xcg340122/PHP300Framework2x
https://github.com/xcg340122/PHP300Framework2x/blob/2ba403cd277680a050c457d39db2aef652fb8e8f/Extend/Package/smarty/sysplugins/smarty_internal_method_gettags.php
Extend/Package/smarty/sysplugins/smarty_internal_method_gettags.php
<?php /** * Smarty Method GetTags * * Smarty::getTags() method * * @package Smarty * @subpackage PluginsInternal * @author Uwe Tews */ class Smarty_Internal_Method_GetTags { /** * Valid for Smarty and template object * * @var int */ public $objMap = 3; /** * Return array of tag/attributes of all tags used by an template * * @api Smarty::getTags() * @link http://www.smarty.net/docs/en/api.get.tags.tpl * * @param \Smarty_Internal_TemplateBase|\Smarty_Internal_Template|\Smarty $obj * @param null|string|Smarty_Internal_Template $template * * @return array of tag/attributes * @throws \Exception * @throws \SmartyException */ public function getTags(Smarty_Internal_TemplateBase $obj, $template = null) { /* @var Smarty $smarty */ $smarty = $obj->_getSmartyObj(); if ($obj->_isTplObj() && !isset($template)) { $tpl = clone $obj; } elseif (isset($template) && $template->_isTplObj()) { $tpl = clone $template; } elseif (isset($template) && is_string($template)) { /* @var Smarty_Internal_Template $tpl */ $tpl = new $smarty->template_class($template, $smarty); // checks if template exists if (!$tpl->source->exists) { throw new SmartyException("Unable to load template {$tpl->source->type} '{$tpl->source->name}'"); } } if (isset($tpl)) { $tpl->smarty = clone $tpl->smarty; $tpl->smarty->_cache[ 'get_used_tags' ] = true; $tpl->_cache[ 'used_tags' ] = array(); $tpl->smarty->merge_compiled_includes = false; $tpl->smarty->disableSecurity(); $tpl->caching = Smarty::CACHING_OFF; $tpl->loadCompiler(); $tpl->compiler->compileTemplate($tpl); return $tpl->_cache[ 'used_tags' ]; } throw new SmartyException('Missing template specification'); } }
php
Apache-2.0
2ba403cd277680a050c457d39db2aef652fb8e8f
2026-01-05T04:52:44.635355Z
false
xcg340122/PHP300Framework2x
https://github.com/xcg340122/PHP300Framework2x/blob/2ba403cd277680a050c457d39db2aef652fb8e8f/Extend/Package/smarty/sysplugins/smarty_internal_method_registerclass.php
Extend/Package/smarty/sysplugins/smarty_internal_method_registerclass.php
<?php /** * Smarty Method RegisterClass * * Smarty::registerClass() method * * @package Smarty * @subpackage PluginsInternal * @author Uwe Tews */ class Smarty_Internal_Method_RegisterClass { /** * Valid for Smarty and template object * * @var int */ public $objMap = 3; /** * Registers static classes to be used in templates * * @api Smarty::registerClass() * @link http://www.smarty.net/docs/en/api.register.class.tpl * * @param \Smarty_Internal_TemplateBase|\Smarty_Internal_Template|\Smarty $obj * @param string $class_name * @param string $class_impl the referenced PHP class to * register * * @return \Smarty|\Smarty_Internal_Template * @throws \SmartyException */ public function registerClass(Smarty_Internal_TemplateBase $obj, $class_name, $class_impl) { $smarty = $obj->_getSmartyObj(); // test if exists if (!class_exists($class_impl)) { throw new SmartyException("Undefined class '$class_impl' in register template class"); } // register the class $smarty->registered_classes[ $class_name ] = $class_impl; return $obj; } }
php
Apache-2.0
2ba403cd277680a050c457d39db2aef652fb8e8f
2026-01-05T04:52:44.635355Z
false
xcg340122/PHP300Framework2x
https://github.com/xcg340122/PHP300Framework2x/blob/2ba403cd277680a050c457d39db2aef652fb8e8f/Extend/Package/smarty/sysplugins/smarty_internal_runtime_filterhandler.php
Extend/Package/smarty/sysplugins/smarty_internal_runtime_filterhandler.php
<?php /** * Smarty Internal Plugin Filter Handler * Smarty filter handler class * * @package Smarty * @subpackage PluginsInternal * @author Uwe Tews */ /** * Class for filter processing * * @package Smarty * @subpackage PluginsInternal */ class Smarty_Internal_Runtime_FilterHandler { /** * Run filters over content * The filters will be lazy loaded if required * class name format: Smarty_FilterType_FilterName * plugin filename format: filtertype.filtername.php * Smarty2 filter plugins could be used * * @param string $type the type of filter ('pre','post','output') which shall run * @param string $content the content which shall be processed by the filters * @param Smarty_Internal_Template $template template object * * @throws SmartyException * @return string the filtered content */ public function runFilter($type, $content, Smarty_Internal_Template $template) { // loop over autoload filters of specified type if (!empty($template->smarty->autoload_filters[ $type ])) { foreach ((array) $template->smarty->autoload_filters[ $type ] as $name) { $plugin_name = "Smarty_{$type}filter_{$name}"; if (function_exists($plugin_name)) { $callback = $plugin_name; } elseif (class_exists($plugin_name, false) && is_callable(array($plugin_name, 'execute'))) { $callback = array($plugin_name, 'execute'); } elseif ($template->smarty->loadPlugin($plugin_name, false)) { if (function_exists($plugin_name)) { // use loaded Smarty2 style plugin $callback = $plugin_name; } elseif (class_exists($plugin_name, false) && is_callable(array($plugin_name, 'execute'))) { // loaded class of filter plugin $callback = array($plugin_name, 'execute'); } else { throw new SmartyException("Auto load {$type}-filter plugin method '{$plugin_name}::execute' not callable"); } } else { // nothing found, throw exception throw new SmartyException("Unable to auto load {$type}-filter plugin '{$plugin_name}'"); } $content = call_user_func($callback, $content, $template); } } // loop over registered filters of specified type if (!empty($template->smarty->registered_filters[ $type ])) { foreach ($template->smarty->registered_filters[ $type ] as $key => $name) { $content = call_user_func($template->smarty->registered_filters[ $type ][ $key ], $content, $template); } } // return filtered output return $content; } }
php
Apache-2.0
2ba403cd277680a050c457d39db2aef652fb8e8f
2026-01-05T04:52:44.635355Z
false
xcg340122/PHP300Framework2x
https://github.com/xcg340122/PHP300Framework2x/blob/2ba403cd277680a050c457d39db2aef652fb8e8f/Extend/Package/smarty/sysplugins/smarty_internal_method_getglobal.php
Extend/Package/smarty/sysplugins/smarty_internal_method_getglobal.php
<?php /** * Smarty Method GetGlobal * * Smarty::getGlobal() method * * @package Smarty * @subpackage PluginsInternal * @author Uwe Tews */ class Smarty_Internal_Method_GetGlobal { /** * Valid for all objects * * @var int */ public $objMap = 7; /** * Returns a single or all global variables * * @api Smarty::getGlobal() * * @param \Smarty_Internal_Data $data * @param string $varName variable name or null * * @return string|array variable value or or array of variables */ public function getGlobal(Smarty_Internal_Data $data, $varName = null) { if (isset($varName)) { if (isset(Smarty::$global_tpl_vars[ $varName ])) { return Smarty::$global_tpl_vars[ $varName ]->value; } else { return ''; } } else { $_result = array(); foreach (Smarty::$global_tpl_vars AS $key => $var) { $_result[ $key ] = $var->value; } return $_result; } } }
php
Apache-2.0
2ba403cd277680a050c457d39db2aef652fb8e8f
2026-01-05T04:52:44.635355Z
false
xcg340122/PHP300Framework2x
https://github.com/xcg340122/PHP300Framework2x/blob/2ba403cd277680a050c457d39db2aef652fb8e8f/Extend/Package/smarty/sysplugins/smarty_internal_parsetree_dq.php
Extend/Package/smarty/sysplugins/smarty_internal_parsetree_dq.php
<?php /** * Double quoted string inside a tag. * * @package Smarty * @subpackage Compiler * @ignore */ /** * Double quoted string inside a tag. * * @package Smarty * @subpackage Compiler * @ignore */ class Smarty_Internal_ParseTree_Dq extends Smarty_Internal_ParseTree { /** * Create parse tree buffer for double quoted string subtrees * * @param object $parser parser object * @param Smarty_Internal_ParseTree $subtree parse tree buffer */ public function __construct($parser, Smarty_Internal_ParseTree $subtree) { $this->subtrees[] = $subtree; if ($subtree instanceof Smarty_Internal_ParseTree_Tag) { $parser->block_nesting_level = count($parser->compiler->_tag_stack); } } /** * Append buffer to subtree * * @param \Smarty_Internal_Templateparser $parser * @param Smarty_Internal_ParseTree $subtree parse tree buffer */ public function append_subtree(Smarty_Internal_Templateparser $parser, Smarty_Internal_ParseTree $subtree) { $last_subtree = count($this->subtrees) - 1; if ($last_subtree >= 0 && $this->subtrees[ $last_subtree ] instanceof Smarty_Internal_ParseTree_Tag && $this->subtrees[ $last_subtree ]->saved_block_nesting < $parser->block_nesting_level ) { if ($subtree instanceof Smarty_Internal_ParseTree_Code) { $this->subtrees[ $last_subtree ]->data = $parser->compiler->appendCode($this->subtrees[ $last_subtree ]->data, '<?php echo ' . $subtree->data . ';?>'); } elseif ($subtree instanceof Smarty_Internal_ParseTree_DqContent) { $this->subtrees[ $last_subtree ]->data = $parser->compiler->appendCode($this->subtrees[ $last_subtree ]->data, '<?php echo "' . $subtree->data . '";?>'); } else { $this->subtrees[ $last_subtree ]->data = $parser->compiler->appendCode($this->subtrees[ $last_subtree ]->data, $subtree->data); } } else { $this->subtrees[] = $subtree; } if ($subtree instanceof Smarty_Internal_ParseTree_Tag) { $parser->block_nesting_level = count($parser->compiler->_tag_stack); } } /** * Merge subtree buffer content together * * @param \Smarty_Internal_Templateparser $parser * * @return string compiled template code */ public function to_smarty_php(Smarty_Internal_Templateparser $parser) { $code = ''; foreach ($this->subtrees as $subtree) { if ($code !== '') { $code .= '.'; } if ($subtree instanceof Smarty_Internal_ParseTree_Tag) { $more_php = $subtree->assign_to_var($parser); } else { $more_php = $subtree->to_smarty_php($parser); } $code .= $more_php; if (!$subtree instanceof Smarty_Internal_ParseTree_DqContent) { $parser->compiler->has_variable_string = true; } } return $code; } }
php
Apache-2.0
2ba403cd277680a050c457d39db2aef652fb8e8f
2026-01-05T04:52:44.635355Z
false
xcg340122/PHP300Framework2x
https://github.com/xcg340122/PHP300Framework2x/blob/2ba403cd277680a050c457d39db2aef652fb8e8f/Extend/Package/smarty/sysplugins/smarty_internal_runtime_cachemodify.php
Extend/Package/smarty/sysplugins/smarty_internal_runtime_cachemodify.php
<?php /** * Inline Runtime Methods render, setSourceByUid, setupSubTemplate * * @package Smarty * @subpackage PluginsInternal * @author Uwe Tews * **/ class Smarty_Internal_Runtime_CacheModify { /** * check client side cache * * @param \Smarty_Template_Cached $cached * @param \Smarty_Internal_Template $_template * @param string $content * * @throws \Exception * @throws \SmartyException */ public function cacheModifiedCheck(Smarty_Template_Cached $cached, Smarty_Internal_Template $_template, $content) { $_isCached = $_template->isCached() && !$_template->compiled->has_nocache_code; $_last_modified_date = @substr($_SERVER[ 'HTTP_IF_MODIFIED_SINCE' ], 0, strpos($_SERVER[ 'HTTP_IF_MODIFIED_SINCE' ], 'GMT') + 3); if ($_isCached && $cached->timestamp <= strtotime($_last_modified_date)) { switch (PHP_SAPI) { case 'cgi': // php-cgi < 5.3 case 'cgi-fcgi': // php-cgi >= 5.3 case 'fpm-fcgi': // php-fpm >= 5.3.3 header('Status: 304 Not Modified'); break; case 'cli': if ( /* ^phpunit */ !empty($_SERVER[ 'SMARTY_PHPUNIT_DISABLE_HEADERS' ]) /* phpunit$ */ ) { $_SERVER[ 'SMARTY_PHPUNIT_HEADERS' ][] = '304 Not Modified'; } break; default: if ( /* ^phpunit */ !empty($_SERVER[ 'SMARTY_PHPUNIT_DISABLE_HEADERS' ]) /* phpunit$ */ ) { $_SERVER[ 'SMARTY_PHPUNIT_HEADERS' ][] = '304 Not Modified'; } else { header($_SERVER[ 'SERVER_PROTOCOL' ] . ' 304 Not Modified'); } break; } } else { switch (PHP_SAPI) { case 'cli': if ( /* ^phpunit */ !empty($_SERVER[ 'SMARTY_PHPUNIT_DISABLE_HEADERS' ]) /* phpunit$ */ ) { $_SERVER[ 'SMARTY_PHPUNIT_HEADERS' ][] = 'Last-Modified: ' . gmdate('D, d M Y H:i:s', $cached->timestamp) . ' GMT'; } break; default: header('Last-Modified: ' . gmdate('D, d M Y H:i:s', $cached->timestamp) . ' GMT'); break; } echo $content; } } }
php
Apache-2.0
2ba403cd277680a050c457d39db2aef652fb8e8f
2026-01-05T04:52:44.635355Z
false
xcg340122/PHP300Framework2x
https://github.com/xcg340122/PHP300Framework2x/blob/2ba403cd277680a050c457d39db2aef652fb8e8f/Extend/Package/smarty/sysplugins/smarty_internal_compile_if.php
Extend/Package/smarty/sysplugins/smarty_internal_compile_if.php
<?php /** * Smarty Internal Plugin Compile If * Compiles the {if} {else} {elseif} {/if} tags * * @package Smarty * @subpackage Compiler * @author Uwe Tews */ /** * Smarty Internal Plugin Compile If Class * * @package Smarty * @subpackage Compiler */ class Smarty_Internal_Compile_If extends Smarty_Internal_CompileBase { /** * Compiles code for the {if} tag * * @param array $args array with attributes from parser * @param \Smarty_Internal_TemplateCompilerBase $compiler compiler object * @param array $parameter array with compilation parameter * * @return string compiled code * @throws \SmartyCompilerException */ public function compile($args, Smarty_Internal_TemplateCompilerBase $compiler, $parameter) { // check and get attributes $_attr = $this->getAttributes($compiler, $args); $this->openTag($compiler, 'if', array(1, $compiler->nocache)); // must whole block be nocache ? $compiler->nocache = $compiler->nocache | $compiler->tag_nocache; if (!isset($parameter['if condition'])) { $compiler->trigger_template_error('missing if condition', null, true); } if (is_array($parameter[ 'if condition' ])) { if (is_array($parameter[ 'if condition' ][ 'var' ])) { $var = $parameter[ 'if condition' ][ 'var' ][ 'var' ]; } else { $var = $parameter[ 'if condition' ][ 'var' ]; } if ($compiler->nocache) { // create nocache var to make it know for further compiling $compiler->setNocacheInVariable($var); } $prefixVar = $compiler->getNewPrefixVariable(); $_output = "<?php {$prefixVar} = {$parameter[ 'if condition' ][ 'value' ]};?>\n"; $assignAttr = array(); $assignAttr[][ 'value' ] = $prefixVar; $assignCompiler = new Smarty_Internal_Compile_Assign(); if (is_array($parameter[ 'if condition' ][ 'var' ])) { $assignAttr[][ 'var' ] = $parameter[ 'if condition' ][ 'var' ][ 'var' ]; $_output .= $assignCompiler->compile($assignAttr, $compiler, array('smarty_internal_index' => $parameter[ 'if condition' ][ 'var' ][ 'smarty_internal_index' ])); } else { $assignAttr[][ 'var' ] = $parameter[ 'if condition' ][ 'var' ]; $_output .= $assignCompiler->compile($assignAttr, $compiler, array()); } $_output .= "<?php if ({$prefixVar}) {?>"; return $_output; } else { return "<?php if ({$parameter['if condition']}) {?>"; } } } /** * Smarty Internal Plugin Compile Else Class * * @package Smarty * @subpackage Compiler */ class Smarty_Internal_Compile_Else extends Smarty_Internal_CompileBase { /** * Compiles code for the {else} tag * * @param array $args array with attributes from parser * @param \Smarty_Internal_TemplateCompilerBase $compiler compiler object * * @return string compiled code */ public function compile($args, Smarty_Internal_TemplateCompilerBase $compiler) { list($nesting, $compiler->tag_nocache) = $this->closeTag($compiler, array('if', 'elseif')); $this->openTag($compiler, 'else', array($nesting, $compiler->tag_nocache)); return '<?php } else { ?>'; } } /** * Smarty Internal Plugin Compile ElseIf Class * * @package Smarty * @subpackage Compiler */ class Smarty_Internal_Compile_Elseif extends Smarty_Internal_CompileBase { /** * Compiles code for the {elseif} tag * * @param array $args array with attributes from parser * @param \Smarty_Internal_TemplateCompilerBase $compiler compiler object * @param array $parameter array with compilation parameter * * @return string compiled code * @throws \SmartyCompilerException */ public function compile($args, Smarty_Internal_TemplateCompilerBase $compiler, $parameter) { // check and get attributes $_attr = $this->getAttributes($compiler, $args); list($nesting, $compiler->tag_nocache) = $this->closeTag($compiler, array('if', 'elseif')); if (!isset($parameter['if condition'])) { $compiler->trigger_template_error('missing elseif condition', null, true); } $assignCode = ''; $var = ''; if (is_array($parameter[ 'if condition' ])) { $condition_by_assign = true; if (is_array($parameter[ 'if condition' ][ 'var' ])) { $var = $parameter[ 'if condition' ][ 'var' ][ 'var' ]; } else { $var = $parameter[ 'if condition' ][ 'var' ]; } if ($compiler->nocache) { // create nocache var to make it know for further compiling $compiler->setNocacheInVariable($var); } $prefixVar = $compiler->getNewPrefixVariable(); $assignCode = "<?php {$prefixVar} = {$parameter[ 'if condition' ][ 'value' ]};?>\n"; $assignCompiler = new Smarty_Internal_Compile_Assign(); $assignAttr = array(); $assignAttr[][ 'value' ] = $prefixVar; if (is_array($parameter[ 'if condition' ][ 'var' ])) { $assignAttr[][ 'var' ] = $parameter[ 'if condition' ][ 'var' ][ 'var' ]; $assignCode .= $assignCompiler->compile($assignAttr, $compiler, array('smarty_internal_index' => $parameter[ 'if condition' ][ 'var' ][ 'smarty_internal_index' ])); } else { $assignAttr[][ 'var' ] = $parameter[ 'if condition' ][ 'var' ]; $assignCode .= $assignCompiler->compile($assignAttr, $compiler, array()); } } else { $condition_by_assign = false; } $prefixCode = $compiler->getPrefixCode(); if (empty($prefixCode)) { if ($condition_by_assign) { $this->openTag($compiler, 'elseif', array($nesting + 1, $compiler->tag_nocache)); $_output = $compiler->appendCode("<?php } else {\n?>", $assignCode); return $compiler->appendCode($_output, "<?php if ({$prefixVar}) {?>"); } else { $this->openTag($compiler, 'elseif', array($nesting, $compiler->tag_nocache)); return "<?php } elseif ({$parameter['if condition']}) {?>"; } } else { $_output = $compiler->appendCode("<?php } else {\n?>", $prefixCode); $this->openTag($compiler, 'elseif', array($nesting + 1, $compiler->tag_nocache)); if ($condition_by_assign) { $_output = $compiler->appendCode($_output, $assignCode); return $compiler->appendCode($_output, "<?php if ({$prefixVar}) {?>"); } else { return $compiler->appendCode($_output, "<?php if ({$parameter['if condition']}) {?>"); } } } } /** * Smarty Internal Plugin Compile Ifclose Class * * @package Smarty * @subpackage Compiler */ class Smarty_Internal_Compile_Ifclose extends Smarty_Internal_CompileBase { /** * Compiles code for the {/if} tag * * @param array $args array with attributes from parser * @param \Smarty_Internal_TemplateCompilerBase $compiler compiler object * * @return string compiled code */ public function compile($args, Smarty_Internal_TemplateCompilerBase $compiler) { // must endblock be nocache? if ($compiler->nocache) { $compiler->tag_nocache = true; } list($nesting, $compiler->nocache) = $this->closeTag($compiler, array('if', 'else', 'elseif')); $tmp = ''; for ($i = 0; $i < $nesting; $i ++) { $tmp .= '}'; } return "<?php {$tmp}?>"; } }
php
Apache-2.0
2ba403cd277680a050c457d39db2aef652fb8e8f
2026-01-05T04:52:44.635355Z
false
xcg340122/PHP300Framework2x
https://github.com/xcg340122/PHP300Framework2x/blob/2ba403cd277680a050c457d39db2aef652fb8e8f/Extend/Package/smarty/sysplugins/smarty_internal_resource_php.php
Extend/Package/smarty/sysplugins/smarty_internal_resource_php.php
<?php /** * Smarty Internal Plugin Resource PHP * Implements the file system as resource for PHP templates * * @package Smarty * @subpackage TemplateResources * @author Uwe Tews * @author Rodney Rehm */ class Smarty_Internal_Resource_Php extends Smarty_Internal_Resource_File { /** * Flag that it's an uncompiled resource * * @var bool */ public $uncompiled = true; /** * Resource does implement populateCompiledFilepath() method * * @var bool */ public $hasCompiledHandler = true; /** * container for short_open_tag directive's value before executing PHP templates * * @var string */ protected $short_open_tag; /** * Create a new PHP Resource */ public function __construct() { $this->short_open_tag = function_exists('ini_get') ? ini_get('short_open_tag') : 1; } /** * Load template's source from file into current template object * * @param Smarty_Template_Source $source source object * * @return string template source * @throws SmartyException if source cannot be loaded */ public function getContent(Smarty_Template_Source $source) { if ($source->exists) { return ''; } throw new SmartyException("Unable to read template {$source->type} '{$source->name}'"); } /** * populate compiled object with compiled filepath * * @param Smarty_Template_Compiled $compiled compiled object * @param Smarty_Internal_Template $_template template object (is ignored) */ public function populateCompiledFilepath(Smarty_Template_Compiled $compiled, Smarty_Internal_Template $_template) { $compiled->filepath = $_template->source->filepath; $compiled->timestamp = $_template->source->timestamp; $compiled->exists = $_template->source->exists; $compiled->file_dependency[ $_template->source->uid ] = array($compiled->filepath, $compiled->timestamp, $_template->source->type,); } /** * Render and output the template (without using the compiler) * * @param Smarty_Template_Source $source source object * @param Smarty_Internal_Template $_template template object * * @return void * @throws SmartyException if template cannot be loaded or allow_php_templates is disabled */ public function renderUncompiled(Smarty_Template_Source $source, Smarty_Internal_Template $_template) { if (!$source->smarty->allow_php_templates) { throw new SmartyException('PHP templates are disabled'); } if (!$source->exists) { throw new SmartyException("Unable to load template '{$source->type}:{$source->name}'" . ($_template->_isSubTpl() ? " in '{$_template->parent->template_resource}'" : '')); } // prepare variables extract($_template->getTemplateVars()); // include PHP template with short open tags enabled if (function_exists('ini_set')) { ini_set('short_open_tag', '1'); } /** @var Smarty_Internal_Template $_smarty_template * used in included file */ $_smarty_template = $_template; include($source->filepath); if (function_exists('ini_set')) { ini_set('short_open_tag', $this->short_open_tag); } } }
php
Apache-2.0
2ba403cd277680a050c457d39db2aef652fb8e8f
2026-01-05T04:52:44.635355Z
false
xcg340122/PHP300Framework2x
https://github.com/xcg340122/PHP300Framework2x/blob/2ba403cd277680a050c457d39db2aef652fb8e8f/Extend/Package/smarty/sysplugins/smarty_internal_compile_for.php
Extend/Package/smarty/sysplugins/smarty_internal_compile_for.php
<?php /** * Smarty Internal Plugin Compile For * Compiles the {for} {forelse} {/for} tags * * @package Smarty * @subpackage Compiler * @author Uwe Tews */ /** * Smarty Internal Plugin Compile For Class * * @package Smarty * @subpackage Compiler */ class Smarty_Internal_Compile_For extends Smarty_Internal_CompileBase { /** * Compiles code for the {for} tag * Smarty 3 does implement two different syntax's: * - {for $var in $array} * For looping over arrays or iterators * - {for $x=0; $x<$y; $x++} * For general loops * The parser is generating different sets of attribute by which this compiler can * determine which syntax is used. * * @param array $args array with attributes from parser * @param object $compiler compiler object * @param array $parameter array with compilation parameter * * @return string compiled code */ public function compile($args, $compiler, $parameter) { $compiler->loopNesting ++; if ($parameter === 0) { $this->required_attributes = array('start', 'to'); $this->optional_attributes = array('max', 'step'); } else { $this->required_attributes = array('start', 'ifexp', 'var', 'step'); $this->optional_attributes = array(); } $this->mapCache = array(); // check and get attributes $_attr = $this->getAttributes($compiler, $args); $output = "<?php\n"; if ($parameter === 1) { foreach ($_attr[ 'start' ] as $_statement) { if (is_array($_statement[ 'var' ])) { $var = $_statement[ 'var' ][ 'var' ]; $index = $_statement[ 'var' ][ 'smarty_internal_index' ]; } else { $var = $_statement[ 'var' ]; $index = ''; } $output .= "\$_smarty_tpl->tpl_vars[$var] = new Smarty_Variable(null, \$_smarty_tpl->isRenderingCache);\n"; $output .= "\$_smarty_tpl->tpl_vars[$var]->value{$index} = {$_statement['value']};\n"; } if (is_array($_attr[ 'var' ])) { $var = $_attr[ 'var' ][ 'var' ]; $index = $_attr[ 'var' ][ 'smarty_internal_index' ]; } else { $var = $_attr[ 'var' ]; $index = ''; } $output .= "if ($_attr[ifexp]) {\nfor (\$_foo=true;$_attr[ifexp]; \$_smarty_tpl->tpl_vars[$var]->value{$index}$_attr[step]) {\n"; } else { $_statement = $_attr[ 'start' ]; if (is_array($_statement[ 'var' ])) { $var = $_statement[ 'var' ][ 'var' ]; $index = $_statement[ 'var' ][ 'smarty_internal_index' ]; } else { $var = $_statement[ 'var' ]; $index = ''; } $output .= "\$_smarty_tpl->tpl_vars[$var] = new Smarty_Variable(null, \$_smarty_tpl->isRenderingCache);"; if (isset($_attr[ 'step' ])) { $output .= "\$_smarty_tpl->tpl_vars[$var]->step = $_attr[step];"; } else { $output .= "\$_smarty_tpl->tpl_vars[$var]->step = 1;"; } if (isset($_attr[ 'max' ])) { $output .= "\$_smarty_tpl->tpl_vars[$var]->total = (int) min(ceil((\$_smarty_tpl->tpl_vars[$var]->step > 0 ? $_attr[to]+1 - ($_statement[value]) : $_statement[value]-($_attr[to])+1)/abs(\$_smarty_tpl->tpl_vars[$var]->step)),$_attr[max]);\n"; } else { $output .= "\$_smarty_tpl->tpl_vars[$var]->total = (int) ceil((\$_smarty_tpl->tpl_vars[$var]->step > 0 ? $_attr[to]+1 - ($_statement[value]) : $_statement[value]-($_attr[to])+1)/abs(\$_smarty_tpl->tpl_vars[$var]->step));\n"; } $output .= "if (\$_smarty_tpl->tpl_vars[$var]->total > 0) {\n"; $output .= "for (\$_smarty_tpl->tpl_vars[$var]->value{$index} = $_statement[value], \$_smarty_tpl->tpl_vars[$var]->iteration = 1;\$_smarty_tpl->tpl_vars[$var]->iteration <= \$_smarty_tpl->tpl_vars[$var]->total;\$_smarty_tpl->tpl_vars[$var]->value{$index} += \$_smarty_tpl->tpl_vars[$var]->step, \$_smarty_tpl->tpl_vars[$var]->iteration++) {\n"; $output .= "\$_smarty_tpl->tpl_vars[$var]->first = \$_smarty_tpl->tpl_vars[$var]->iteration === 1;"; $output .= "\$_smarty_tpl->tpl_vars[$var]->last = \$_smarty_tpl->tpl_vars[$var]->iteration === \$_smarty_tpl->tpl_vars[$var]->total;"; } $output .= '?>'; $this->openTag($compiler, 'for', array('for', $compiler->nocache)); // maybe nocache because of nocache variables $compiler->nocache = $compiler->nocache | $compiler->tag_nocache; // return compiled code return $output; } } /** * Smarty Internal Plugin Compile Forelse Class * * @package Smarty * @subpackage Compiler */ class Smarty_Internal_Compile_Forelse extends Smarty_Internal_CompileBase { /** * Compiles code for the {forelse} tag * * @param array $args array with attributes from parser * @param object $compiler compiler object * @param array $parameter array with compilation parameter * * @return string compiled code */ public function compile($args, $compiler, $parameter) { // check and get attributes $_attr = $this->getAttributes($compiler, $args); list($openTag, $nocache) = $this->closeTag($compiler, array('for')); $this->openTag($compiler, 'forelse', array('forelse', $nocache)); return "<?php }} else { ?>"; } } /** * Smarty Internal Plugin Compile Forclose Class * * @package Smarty * @subpackage Compiler */ class Smarty_Internal_Compile_Forclose extends Smarty_Internal_CompileBase { /** * Compiles code for the {/for} tag * * @param array $args array with attributes from parser * @param object $compiler compiler object * @param array $parameter array with compilation parameter * * @return string compiled code */ public function compile($args, $compiler, $parameter) { $compiler->loopNesting --; // check and get attributes $_attr = $this->getAttributes($compiler, $args); // must endblock be nocache? if ($compiler->nocache) { $compiler->tag_nocache = true; } list($openTag, $compiler->nocache) = $this->closeTag($compiler, array('for', 'forelse')); $output = "<?php }\n"; if ($openTag !== 'forelse') { $output .= "}\n"; } $output .= "?>"; return $output; } }
php
Apache-2.0
2ba403cd277680a050c457d39db2aef652fb8e8f
2026-01-05T04:52:44.635355Z
false
xcg340122/PHP300Framework2x
https://github.com/xcg340122/PHP300Framework2x/blob/2ba403cd277680a050c457d39db2aef652fb8e8f/Extend/Package/smarty/sysplugins/smarty_internal_method_clearallassign.php
Extend/Package/smarty/sysplugins/smarty_internal_method_clearallassign.php
<?php /** * Smarty Method ClearAllAssign * * Smarty::clearAllAssign() method * * @package Smarty * @subpackage PluginsInternal * @author Uwe Tews */ class Smarty_Internal_Method_ClearAllAssign { /** * Valid for all objects * * @var int */ public $objMap = 7; /** * clear all the assigned template variables. * * @api Smarty::clearAllAssign() * @link http://www.smarty.net/docs/en/api.clear.all.assign.tpl * * @param \Smarty_Internal_Data|\Smarty_Internal_Template|\Smarty $data * * @return \Smarty_Internal_Data|\Smarty_Internal_Template|\Smarty */ public function clearAllAssign(Smarty_Internal_Data $data) { $data->tpl_vars = array(); return $data; } }
php
Apache-2.0
2ba403cd277680a050c457d39db2aef652fb8e8f
2026-01-05T04:52:44.635355Z
false
xcg340122/PHP300Framework2x
https://github.com/xcg340122/PHP300Framework2x/blob/2ba403cd277680a050c457d39db2aef652fb8e8f/Extend/Package/smarty/sysplugins/smarty_internal_parsetree_code.php
Extend/Package/smarty/sysplugins/smarty_internal_parsetree_code.php
<?php /** * Smarty Internal Plugin Templateparser Parse Tree * These are classes to build parse trees in the template parser * * @package Smarty * @subpackage Compiler * @author Thue Kristensen * @author Uwe Tews */ /** * Code fragment inside a tag . * * @package Smarty * @subpackage Compiler * @ignore */ class Smarty_Internal_ParseTree_Code extends Smarty_Internal_ParseTree { /** * Create parse tree buffer for code fragment * * @param string $data content */ public function __construct($data) { $this->data = $data; } /** * Return buffer content in parentheses * * @param \Smarty_Internal_Templateparser $parser * * @return string content */ public function to_smarty_php(Smarty_Internal_Templateparser $parser) { return sprintf('(%s)', $this->data); } }
php
Apache-2.0
2ba403cd277680a050c457d39db2aef652fb8e8f
2026-01-05T04:52:44.635355Z
false
xcg340122/PHP300Framework2x
https://github.com/xcg340122/PHP300Framework2x/blob/2ba403cd277680a050c457d39db2aef652fb8e8f/Extend/Package/smarty/sysplugins/smarty_internal_method_clearassign.php
Extend/Package/smarty/sysplugins/smarty_internal_method_clearassign.php
<?php /** * Smarty Method ClearAssign * * Smarty::clearAssign() method * * @package Smarty * @subpackage PluginsInternal * @author Uwe Tews */ class Smarty_Internal_Method_ClearAssign { /** * Valid for all objects * * @var int */ public $objMap = 7; /** * clear the given assigned template variable(s). * * @api Smarty::clearAssign() * @link http://www.smarty.net/docs/en/api.clear.assign.tpl * * @param \Smarty_Internal_Data|\Smarty_Internal_Template|\Smarty $data * @param string|array $tpl_var the template variable(s) to clear * * @return \Smarty_Internal_Data|\Smarty_Internal_Template|\Smarty */ public function clearAssign(Smarty_Internal_Data $data, $tpl_var) { if (is_array($tpl_var)) { foreach ($tpl_var as $curr_var) { unset($data->tpl_vars[ $curr_var ]); } } else { unset($data->tpl_vars[ $tpl_var ]); } return $data; } }
php
Apache-2.0
2ba403cd277680a050c457d39db2aef652fb8e8f
2026-01-05T04:52:44.635355Z
false
xcg340122/PHP300Framework2x
https://github.com/xcg340122/PHP300Framework2x/blob/2ba403cd277680a050c457d39db2aef652fb8e8f/Extend/Package/smarty/sysplugins/smarty_internal_compile_nocache.php
Extend/Package/smarty/sysplugins/smarty_internal_compile_nocache.php
<?php /** * Smarty Internal Plugin Compile Nocache * Compiles the {nocache} {/nocache} tags. * * @package Smarty * @subpackage Compiler * @author Uwe Tews */ /** * Smarty Internal Plugin Compile Nocache Class * * @package Smarty * @subpackage Compiler */ class Smarty_Internal_Compile_Nocache extends Smarty_Internal_CompileBase { /** * Array of names of valid option flags * * @var array */ public $option_flags = array(); /** * Compiles code for the {nocache} tag * This tag does not generate compiled output. It only sets a compiler flag. * * @param array $args array with attributes from parser * @param \Smarty_Internal_TemplateCompilerBase $compiler compiler object * * @return bool */ public function compile($args, Smarty_Internal_TemplateCompilerBase $compiler) { $_attr = $this->getAttributes($compiler, $args); $this->openTag($compiler, 'nocache', array($compiler->nocache)); // enter nocache mode $compiler->nocache = true; // this tag does not return compiled code $compiler->has_code = false; return true; } } /** * Smarty Internal Plugin Compile Nocacheclose Class * * @package Smarty * @subpackage Compiler */ class Smarty_Internal_Compile_Nocacheclose extends Smarty_Internal_CompileBase { /** * Compiles code for the {/nocache} tag * This tag does not generate compiled output. It only sets a compiler flag. * * @param array $args array with attributes from parser * @param \Smarty_Internal_TemplateCompilerBase $compiler compiler object * * @return bool */ public function compile($args, Smarty_Internal_TemplateCompilerBase $compiler) { $_attr = $this->getAttributes($compiler, $args); // leave nocache mode list($compiler->nocache) = $this->closeTag($compiler, array('nocache')); // this tag does not return compiled code $compiler->has_code = false; return true; } }
php
Apache-2.0
2ba403cd277680a050c457d39db2aef652fb8e8f
2026-01-05T04:52:44.635355Z
false
xcg340122/PHP300Framework2x
https://github.com/xcg340122/PHP300Framework2x/blob/2ba403cd277680a050c457d39db2aef652fb8e8f/Extend/Package/smarty/sysplugins/smarty_internal_resource_registered.php
Extend/Package/smarty/sysplugins/smarty_internal_resource_registered.php
<?php /** * Smarty Internal Plugin Resource Registered * * @package Smarty * @subpackage TemplateResources * @author Uwe Tews * @author Rodney Rehm */ /** * Smarty Internal Plugin Resource Registered * Implements the registered resource for Smarty template * * @package Smarty * @subpackage TemplateResources * @deprecated */ class Smarty_Internal_Resource_Registered extends Smarty_Resource { /** * populate Source Object with meta data from Resource * * @param Smarty_Template_Source $source source object * @param Smarty_Internal_Template $_template template object * * @return void */ public function populate(Smarty_Template_Source $source, Smarty_Internal_Template $_template = null) { $source->filepath = $source->type . ':' . $source->name; $source->uid = sha1($source->filepath . $source->smarty->_joined_template_dir); $source->timestamp = $this->getTemplateTimestamp($source); $source->exists = !!$source->timestamp; } /** * populate Source Object with timestamp and exists from Resource * * @param Smarty_Template_Source $source source object * * @return void */ public function populateTimestamp(Smarty_Template_Source $source) { $source->timestamp = $this->getTemplateTimestamp($source); $source->exists = !!$source->timestamp; } /** * Get timestamp (epoch) the template source was modified * * @param Smarty_Template_Source $source source object * * @return integer|boolean timestamp (epoch) the template was modified, false if resources has no timestamp */ public function getTemplateTimestamp(Smarty_Template_Source $source) { // return timestamp $time_stamp = false; call_user_func_array($source->smarty->registered_resources[ $source->type ][ 0 ][ 1 ], array($source->name, &$time_stamp, $source->smarty)); return is_numeric($time_stamp) ? (int) $time_stamp : $time_stamp; } /** * Load template's source by invoking the registered callback into current template object * * @param Smarty_Template_Source $source source object * * @return string template source * @throws SmartyException if source cannot be loaded */ public function getContent(Smarty_Template_Source $source) { // return template string $content = null; $t = call_user_func_array($source->smarty->registered_resources[ $source->type ][ 0 ][ 0 ], array($source->name, &$content, $source->smarty)); if (is_bool($t) && !$t) { throw new SmartyException("Unable to read template {$source->type} '{$source->name}'"); } return $content; } /** * Determine basename for compiled filename * * @param Smarty_Template_Source $source source object * * @return string resource's basename */ public function getBasename(Smarty_Template_Source $source) { return basename($source->name); } }
php
Apache-2.0
2ba403cd277680a050c457d39db2aef652fb8e8f
2026-01-05T04:52:44.635355Z
false
xcg340122/PHP300Framework2x
https://github.com/xcg340122/PHP300Framework2x/blob/2ba403cd277680a050c457d39db2aef652fb8e8f/Extend/Package/smarty/sysplugins/smarty_internal_method_clearcache.php
Extend/Package/smarty/sysplugins/smarty_internal_method_clearcache.php
<?php /** * Smarty Method ClearCache * * Smarty::clearCache() method * * @package Smarty * @subpackage PluginsInternal * @author Uwe Tews */ class Smarty_Internal_Method_ClearCache { /** * Valid for Smarty object * * @var int */ public $objMap = 1; /** * Empty cache for a specific template * * @api Smarty::clearCache() * @link http://www.smarty.net/docs/en/api.clear.cache.tpl * * @param \Smarty $smarty * @param string $template_name template name * @param string $cache_id cache id * @param string $compile_id compile id * @param integer $exp_time expiration time * @param string $type resource type * * @return int number of cache files deleted * @throws \SmartyException */ public function clearCache(Smarty $smarty, $template_name, $cache_id = null, $compile_id = null, $exp_time = null, $type = null) { $smarty->_clearTemplateCache(); // load cache resource and call clear $_cache_resource = Smarty_CacheResource::load($smarty, $type); return $_cache_resource->clear($smarty, $template_name, $cache_id, $compile_id, $exp_time); } }
php
Apache-2.0
2ba403cd277680a050c457d39db2aef652fb8e8f
2026-01-05T04:52:44.635355Z
false
xcg340122/PHP300Framework2x
https://github.com/xcg340122/PHP300Framework2x/blob/2ba403cd277680a050c457d39db2aef652fb8e8f/Extend/Package/smarty/sysplugins/smarty_internal_method_configload.php
Extend/Package/smarty/sysplugins/smarty_internal_method_configload.php
<?php /** * Smarty Method ConfigLoad * * Smarty::configLoad() method * * @package Smarty * @subpackage PluginsInternal * @author Uwe Tews */ class Smarty_Internal_Method_ConfigLoad { /** * Valid for all objects * * @var int */ public $objMap = 7; /** * load a config file, optionally load just selected sections * * @api Smarty::configLoad() * @link http://www.smarty.net/docs/en/api.config.load.tpl * * @param \Smarty_Internal_Data|\Smarty_Internal_Template|\Smarty $data * @param string $config_file filename * @param mixed $sections array of section names, single * section or null * * @return \Smarty|\Smarty_Internal_Data|\Smarty_Internal_Template * @throws \Exception */ public function configLoad(Smarty_Internal_Data $data, $config_file, $sections = null) { $this->_loadConfigFile($data, $config_file, $sections, null); return $data; } /** * load a config file, optionally load just selected sections * * @api Smarty::configLoad() * @link http://www.smarty.net/docs/en/api.config.load.tpl * * @param \Smarty|\Smarty_Internal_Data|\Smarty_Internal_Template $data * @param string $config_file filename * @param mixed $sections array of section names, single * section or null * @param int $scope scope into which config variables * shall be loaded * * @return \Smarty|\Smarty_Internal_Data|\Smarty_Internal_Template * @throws \Exception */ public function _loadConfigFile(Smarty_Internal_Data $data, $config_file, $sections = null, $scope = 0) { /* @var \Smarty $smarty */ $smarty = $data->_getSmartyObj(); /* @var \Smarty_Internal_Template $confObj */ $confObj = new Smarty_Internal_Template($config_file, $smarty, $data, null, null, null, null, true); $confObj->caching = Smarty::CACHING_OFF; $confObj->source->config_sections = $sections; $confObj->source->scope = $scope; $confObj->compiled = Smarty_Template_Compiled::load($confObj); $confObj->compiled->render($confObj); if ($data->_isTplObj()) { $data->compiled->file_dependency[ $confObj->source->uid ] = array($confObj->source->filepath, $confObj->source->getTimeStamp(), $confObj->source->type); } } /** * load config variables into template object * * @param \Smarty_Internal_Template $tpl * @param array $new_config_vars * */ public function _loadConfigVars(Smarty_Internal_Template $tpl, $new_config_vars) { $this->_assignConfigVars($tpl->parent->config_vars, $tpl, $new_config_vars); $tagScope = $tpl->source->scope; if ($tagScope >= 0) { if ($tagScope === Smarty::SCOPE_LOCAL) { $this->_updateVarStack($tpl, $new_config_vars); $tagScope = 0; if (!$tpl->scope) { return; } } if ($tpl->parent->_isTplObj() && ($tagScope || $tpl->parent->scope)) { $mergedScope = $tagScope | $tpl->scope; if ($mergedScope) { // update scopes /* @var \Smarty_Internal_Template|\Smarty|\Smarty_Internal_Data $ptr */ foreach ($tpl->smarty->ext->_updateScope->_getAffectedScopes($tpl->parent, $mergedScope) as $ptr) { $this->_assignConfigVars($ptr->config_vars, $tpl, $new_config_vars); if ($tagScope && $ptr->_isTplObj() && isset($tpl->_cache[ 'varStack' ])) { $this->_updateVarStack($tpl, $new_config_vars); } } } } } } /** * Assign all config variables in given scope * * @param array $config_vars config variables in scope * @param \Smarty_Internal_Template $tpl * @param array $new_config_vars loaded config variables */ public function _assignConfigVars(&$config_vars, Smarty_Internal_Template $tpl, $new_config_vars) { // copy global config vars foreach ($new_config_vars[ 'vars' ] as $variable => $value) { if ($tpl->smarty->config_overwrite || !isset($config_vars[ $variable ])) { $config_vars[ $variable ] = $value; } else { $config_vars[ $variable ] = array_merge((array) $config_vars[ $variable ], (array) $value); } } // scan sections $sections = $tpl->source->config_sections; if (!empty($sections)) { foreach ((array) $sections as $tpl_section) { if (isset($new_config_vars[ 'sections' ][ $tpl_section ])) { foreach ($new_config_vars[ 'sections' ][ $tpl_section ][ 'vars' ] as $variable => $value) { if ($tpl->smarty->config_overwrite || !isset($config_vars[ $variable ])) { $config_vars[ $variable ] = $value; } else { $config_vars[ $variable ] = array_merge((array) $config_vars[ $variable ], (array) $value); } } } } } } /** * Update config variables in template local variable stack * * @param \Smarty_Internal_Template $tpl * @param array $config_vars */ public function _updateVarStack(Smarty_Internal_Template $tpl, $config_vars) { $i = 0; while (isset($tpl->_cache[ 'varStack' ][ $i ])) { $this->_assignConfigVars($tpl->_cache[ 'varStack' ][ $i ][ 'config' ], $tpl, $config_vars); $i ++; } } /** * gets a config variable value * * @param \Smarty|\Smarty_Internal_Data|\Smarty_Internal_Template $data * @param string $varName the name of the config variable * @param bool $errorEnable * * @return null|string the value of the config variable */ public function _getConfigVariable(Smarty_Internal_Data $data, $varName, $errorEnable = true) { $_ptr = $data; while ($_ptr !== null) { if (isset($_ptr->config_vars[ $varName ])) { // found it, return it return $_ptr->config_vars[ $varName ]; } // not found, try at parent $_ptr = $_ptr->parent; } if ($data->smarty->error_unassigned && $errorEnable) { // force a notice $x = $$varName; } return null; } }
php
Apache-2.0
2ba403cd277680a050c457d39db2aef652fb8e8f
2026-01-05T04:52:44.635355Z
false
xcg340122/PHP300Framework2x
https://github.com/xcg340122/PHP300Framework2x/blob/2ba403cd277680a050c457d39db2aef652fb8e8f/Extend/Package/smarty/sysplugins/smarty_internal_compilebase.php
Extend/Package/smarty/sysplugins/smarty_internal_compilebase.php
<?php /** * Smarty Internal Plugin CompileBase * * @package Smarty * @subpackage Compiler * @author Uwe Tews */ /** * This class does extend all internal compile plugins * * @package Smarty * @subpackage Compiler */ abstract class Smarty_Internal_CompileBase { /** * Array of names of required attribute required by tag * * @var array */ public $required_attributes = array(); /** * Array of names of optional attribute required by tag * use array('_any') if there is no restriction of attributes names * * @var array */ public $optional_attributes = array(); /** * Shorttag attribute order defined by its names * * @var array */ public $shorttag_order = array(); /** * Array of names of valid option flags * * @var array */ public $option_flags = array('nocache'); /** * Mapping array for boolean option value * * @var array */ public $optionMap = array(1 => true, 0 => false, 'true' => true, 'false' => false); /** * Mapping array with attributes as key * * @var array */ public $mapCache = array(); /** * This function checks if the attributes passed are valid * The attributes passed for the tag to compile are checked against the list of required and * optional attributes. Required attributes must be present. Optional attributes are check against * the corresponding list. The keyword '_any' specifies that any attribute will be accepted * as valid * * @param object $compiler compiler object * @param array $attributes attributes applied to the tag * * @return array of mapped attributes for further processing */ public function getAttributes($compiler, $attributes) { $_indexed_attr = array(); if (!isset($this->mapCache[ 'option' ])) { $this->mapCache[ 'option' ] = array_fill_keys($this->option_flags, true); } foreach ($attributes as $key => $mixed) { // shorthand ? if (!is_array($mixed)) { // option flag ? if (isset($this->mapCache[ 'option' ][ trim($mixed, '\'"') ])) { $_indexed_attr[ trim($mixed, '\'"') ] = true; // shorthand attribute ? } elseif (isset($this->shorttag_order[ $key ])) { $_indexed_attr[ $this->shorttag_order[ $key ] ] = $mixed; } else { // too many shorthands $compiler->trigger_template_error('too many shorthand attributes', null, true); } // named attribute } else { foreach ($mixed as $k => $v) { // option flag? if (isset($this->mapCache[ 'option' ][ $k ])) { if (is_bool($v)) { $_indexed_attr[ $k ] = $v; } else { if (is_string($v)) { $v = trim($v, '\'" '); } if (isset($this->optionMap[ $v ])) { $_indexed_attr[ $k ] = $this->optionMap[ $v ]; } else { $compiler->trigger_template_error("illegal value '" . var_export($v, true) . "' for option flag '{$k}'", null, true); } } // must be named attribute } else { $_indexed_attr[ $k ] = $v; } } } } // check if all required attributes present foreach ($this->required_attributes as $attr) { if (!isset($_indexed_attr[ $attr ])) { $compiler->trigger_template_error("missing '{$attr}' attribute", null, true); } } // check for not allowed attributes if ($this->optional_attributes !== array('_any')) { if (!isset($this->mapCache[ 'all' ])) { $this->mapCache[ 'all' ] = array_fill_keys(array_merge($this->required_attributes, $this->optional_attributes, $this->option_flags), true); } foreach ($_indexed_attr as $key => $dummy) { if (!isset($this->mapCache[ 'all' ][ $key ]) && $key !== 0) { $compiler->trigger_template_error("unexpected '{$key}' attribute", null, true); } } } // default 'false' for all option flags not set foreach ($this->option_flags as $flag) { if (!isset($_indexed_attr[ $flag ])) { $_indexed_attr[ $flag ] = false; } } if (isset($_indexed_attr[ 'nocache' ]) && $_indexed_attr[ 'nocache' ]) { $compiler->tag_nocache = true; } return $_indexed_attr; } /** * Push opening tag name on stack * Optionally additional data can be saved on stack * * @param object $compiler compiler object * @param string $openTag the opening tag's name * @param mixed $data optional data saved */ public function openTag($compiler, $openTag, $data = null) { array_push($compiler->_tag_stack, array($openTag, $data)); } /** * Pop closing tag * Raise an error if this stack-top doesn't match with expected opening tags * * @param object $compiler compiler object * @param array|string $expectedTag the expected opening tag names * * @return mixed any type the opening tag's name or saved data */ public function closeTag($compiler, $expectedTag) { if (count($compiler->_tag_stack) > 0) { // get stacked info list($_openTag, $_data) = array_pop($compiler->_tag_stack); // open tag must match with the expected ones if (in_array($_openTag, (array) $expectedTag)) { if (is_null($_data)) { // return opening tag return $_openTag; } else { // return restored data return $_data; } } // wrong nesting of tags $compiler->trigger_template_error("unclosed '{$compiler->smarty->left_delimiter}{$_openTag}{$compiler->smarty->right_delimiter}' tag"); return; } // wrong nesting of tags $compiler->trigger_template_error('unexpected closing tag', null, true); return; } }
php
Apache-2.0
2ba403cd277680a050c457d39db2aef652fb8e8f
2026-01-05T04:52:44.635355Z
false
xcg340122/PHP300Framework2x
https://github.com/xcg340122/PHP300Framework2x/blob/2ba403cd277680a050c457d39db2aef652fb8e8f/Extend/Package/smarty/sysplugins/smarty_internal_method_assignglobal.php
Extend/Package/smarty/sysplugins/smarty_internal_method_assignglobal.php
<?php /** * Smarty Method AssignGlobal * * Smarty::assignGlobal() method * * @package Smarty * @subpackage PluginsInternal * @author Uwe Tews */ class Smarty_Internal_Method_AssignGlobal { /** * Valid for all objects * * @var int */ public $objMap = 7; /** * assigns a global Smarty variable * * @param \Smarty_Internal_Data|\Smarty_Internal_Template|\Smarty $data * @param string $varName the global variable name * @param mixed $value the value to assign * @param boolean $nocache if true any output of this variable will be not cached * * @return \Smarty_Internal_Data|\Smarty_Internal_Template|\Smarty */ public function assignGlobal(Smarty_Internal_Data $data, $varName, $value = null, $nocache = false) { if ($varName !== '') { Smarty::$global_tpl_vars[ $varName ] = new Smarty_Variable($value, $nocache); $ptr = $data; while ($ptr->_isTplObj()) { $ptr->tpl_vars[ $varName ] = clone Smarty::$global_tpl_vars[ $varName ]; $ptr = $ptr->parent; } } return $data; } }
php
Apache-2.0
2ba403cd277680a050c457d39db2aef652fb8e8f
2026-01-05T04:52:44.635355Z
false
xcg340122/PHP300Framework2x
https://github.com/xcg340122/PHP300Framework2x/blob/2ba403cd277680a050c457d39db2aef652fb8e8f/Extend/Package/smarty/sysplugins/smarty_internal_method_unregistercacheresource.php
Extend/Package/smarty/sysplugins/smarty_internal_method_unregistercacheresource.php
<?php /** * Smarty Method UnregisterCacheResource * * Smarty::unregisterCacheResource() method * * @package Smarty * @subpackage PluginsInternal * @author Uwe Tews */ class Smarty_Internal_Method_UnregisterCacheResource { /** * Valid for Smarty and template object * * @var int */ public $objMap = 3; /** * Registers a resource to fetch a template * * @api Smarty::unregisterCacheResource() * @link http://www.smarty.net/docs/en/api.unregister.cacheresource.tpl * * @param \Smarty_Internal_TemplateBase|\Smarty_Internal_Template|\Smarty $obj * @param $name * * @return \Smarty|\Smarty_Internal_Template */ public function unregisterCacheResource(Smarty_Internal_TemplateBase $obj, $name) { $smarty = $obj->_getSmartyObj(); if (isset($smarty->registered_cache_resources[ $name ])) { unset($smarty->registered_cache_resources[ $name ]); } return $obj; } }
php
Apache-2.0
2ba403cd277680a050c457d39db2aef652fb8e8f
2026-01-05T04:52:44.635355Z
false
xcg340122/PHP300Framework2x
https://github.com/xcg340122/PHP300Framework2x/blob/2ba403cd277680a050c457d39db2aef652fb8e8f/Extend/Package/smarty/sysplugins/smarty_internal_method_registerdefaultpluginhandler.php
Extend/Package/smarty/sysplugins/smarty_internal_method_registerdefaultpluginhandler.php
<?php /** * Smarty Method RegisterDefaultPluginHandler * * Smarty::registerDefaultPluginHandler() method * * @package Smarty * @subpackage PluginsInternal * @author Uwe Tews */ class Smarty_Internal_Method_RegisterDefaultPluginHandler { /** * Valid for Smarty and template object * * @var int */ public $objMap = 3; /** * Registers a default plugin handler * * @api Smarty::registerDefaultPluginHandler() * @link http://www.smarty.net/docs/en/api.register.default.plugin.handler.tpl * * @param \Smarty_Internal_TemplateBase|\Smarty_Internal_Template|\Smarty $obj * @param callable $callback class/method name * * @return \Smarty|\Smarty_Internal_Template * @throws SmartyException if $callback is not callable */ public function registerDefaultPluginHandler(Smarty_Internal_TemplateBase $obj, $callback) { $smarty = $obj->_getSmartyObj(); if (is_callable($callback)) { $smarty->default_plugin_handler_func = $callback; } else { throw new SmartyException("Default plugin handler '$callback' not callable"); } return $obj; } }
php
Apache-2.0
2ba403cd277680a050c457d39db2aef652fb8e8f
2026-01-05T04:52:44.635355Z
false
xcg340122/PHP300Framework2x
https://github.com/xcg340122/PHP300Framework2x/blob/2ba403cd277680a050c457d39db2aef652fb8e8f/Web/index.php
Web/index.php
<?php /** PHP300Framework默认入口 version:2.5.3 */ if (substr(PHP_VERSION, 0, 3) < 5.4) die('<meta charset="UTF-8">PHP300:请将PHP版本切换至5.3以上运行!'); /** 引入框架文件 */ require '../Framework/frame.php'; /** @var object 实例化应用 $app */ $app = new Framework\App(); /** 设定默认访问(应用,控制器,方法) */ $app()->get('Visit')->bind(array('Home', 'Index', 'index')); /** 是否调试模式(true => 调试,false => 线上) */ $app()->get('Running')->isDev(true); /** 运行应用 */ $app()->run();
php
Apache-2.0
2ba403cd277680a050c457d39db2aef652fb8e8f
2026-01-05T04:52:44.635355Z
false
xcg340122/PHP300Framework2x
https://github.com/xcg340122/PHP300Framework2x/blob/2ba403cd277680a050c457d39db2aef652fb8e8f/Framework/frame.php
Framework/frame.php
<?php namespace Framework; use Framework\Library\Process\Running; use Framework\Library\Process\Structure; use Framework\Library\Process\Visit; /** * 系统总线 * Class App * @author chungui * @version 2.5.3 * @package Framework */ class App { /** * @var Object 扩展实例 */ static public $extend; /** * @var Object 应用实例 */ static public $app; /** * @var String 框架路径 */ public $corePath; /** * @var array 钩子列表 */ private $hook = []; /** * App constructor. * @param $Path */ public function __construct($Path = '') { $ini = ini_get('date.timezone'); if (empty($ini)) { ini_set('date.timezone', 'Asia/Shanghai'); } self::$app = $this; $this->corePath = is_dir($Path) ? $Path . '/Framework/' : __DIR__ . '/'; $this->inBatch(['Running', 'Tool', 'Structure', 'Config', 'Log', 'LogicExceptions']); $this->get('Running')->startRecord(); } /** * 处理寄存队列 * @param $array */ public function inBatch($array) { if (is_array($array)) { foreach ($array as $value) { $this->get($value); } } } /** * 获取寄存数据 * @param $Name * @return mixed */ public function get($Name) { if (!empty($this->hook[$Name]) && is_object($this->hook[$Name])) return $this->hook[$Name]; $this->put($Name, $this->inProcess($Name)); return $this->hook[$Name]; } /** * 寄存实例对象 * @param string $Name * @param $Obj */ public function put($Name, $Obj) { if (!empty($Name) && is_object($Obj) && empty($this->hook[$Name])) $this->hook[$Name] = $Obj; } /** * 处理实例化实现过程 * @param $Pointer * @return mixed */ public function inProcess($Pointer) { $PNamespace = "\Framework\Library\Process\\{$Pointer}"; $Path = $this->corePath . 'Library/Process/' . str_replace('\\', '/', $Pointer); $Path .= strpos($Pointer, 'Drive') !== false ? '.php' : '.class.php'; if (file_exists($Path)) { require_once($Path); return new $PNamespace(); } return false; } /** * 处理应用 * @return $this */ public function __invoke() { $this->inBatch(['Visit', 'Db', 'Extend']); return $this; } /** * 运行应用 */ public function run() { Running::$runMode = php_sapi_name(); if (Running::$runMode == 'cli') { Visit::setCliParam(); } $object = Visit::mergeParam(); $function = Visit::getfunction(); Running::setconstant(); $app = new $object(); if (method_exists($app, $function)) { $this->get('ReturnHandle')->Output($app->$function()); } else { $this->get('LogicExceptions')->readErrorFile([ 'file' => Structure::$endfile, 'message' => "[{$function}] 方法不存在!" ]); } } }
php
Apache-2.0
2ba403cd277680a050c457d39db2aef652fb8e8f
2026-01-05T04:52:44.635355Z
false
xcg340122/PHP300Framework2x
https://github.com/xcg340122/PHP300Framework2x/blob/2ba403cd277680a050c457d39db2aef652fb8e8f/Framework/Config/frame.cfg.php
Framework/Config/frame.cfg.php
<?php /** * 系统基础配置 */ return [ /** * 日志基础配置 */ 'log' => [ /** * 是否开启日志记录 */ 'error_switch' => true, /** * 记录错误级别(E_ERROR|E_WARNING|E_PARSE) * 全部错误(E_ALL) * 致命错误(E_ERROR) * 运行警告(E_WARNING) * 语法错误(E_PARSE) * 其他通知(E_NOTICE) * 更多错误级别请参照(http://php.net/manual/zh/errorfunc.constants.php) */ 'error_level' => 'E_ALL' ], /** * 异常处理配置 */ 'Exception' => [ /** * 是否开启异常显示 */ 'display_switch' => true, /** * 显示错误的级别(E_ERROR|E_WARNING|E_PARSE) * 全部错误(E_ALL) * 致命错误(E_ERROR) * 运行警告(E_WARNING) * 语法错误(E_PARSE) * 其他通知(E_NOTICE) * 更多错误级别请参照(http://php.net/manual/zh/errorfunc.constants.php) */ 'display_level' => 'E_ALL' ], /** * 访问信息配置 */ 'Visit' => [ /** * 默认加载实例的命名空间前缀(不建议修改) */ 'namespace' => 'App', /** * 默认实例名称 */ 'Project' => 'Home', /** * 默认控制器名称 */ 'Controller' => 'Index', /** * 默认方法名称 */ 'Function' => 'index', /** * 静态扩展名 */ 'extend' => '.html' ], /** * 参数请求 */ 'Parameter' => [ /** * 默认实例key */ 'Project' => 'p', /** * 默认控制器key */ 'Controller' => 'c', /** * 默认方法key */ 'Function' => 'f', ], 'View' => [ /** * 模板左标记 */ 'left_delimiter' => '_{', /** * 模板右标记 */ 'right_delimiter' => '}_', /** * 是否启用缓存 */ 'is_cache' => true, /** * 缓存周期 */ 'cache_lifetime' => '0', ] ];
php
Apache-2.0
2ba403cd277680a050c457d39db2aef652fb8e8f
2026-01-05T04:52:44.635355Z
false
xcg340122/PHP300Framework2x
https://github.com/xcg340122/PHP300Framework2x/blob/2ba403cd277680a050c457d39db2aef652fb8e8f/Framework/Library/Process/LogicExceptions.class.php
Framework/Library/Process/LogicExceptions.class.php
<?php namespace Framework\Library\Process; /** * 异常处理器 * Class LogicExceptions * @package Framework\Library\Process */ use Framework\App; use Framework\Library\Interfaces\LogicExceptionsInterface as LogicExceptionsInterfaces; class LogicExceptions implements LogicExceptionsInterfaces { /** * @var array 配置信息 */ static public $Config; /** * 构造函数,挂载中断回调 * LogicExceptions constructor. */ public function __construct() { error_reporting(0); register_shutdown_function([&$this, 'Mount']); self::$Config = App::$app->get('Config')->get('frame'); Running::$Debug = self::$Config['Exception']['display_switch']; } /** * 挂载异常钩子 */ public function Mount() { $error = error_get_last(); if ($error != NULL) { $errorType = [ 1 => 'E_ERROR', 2 => 'E_WARNING', 4 => 'E_PARSE', 8 => 'E_NOTICE', 16 => 'E_CORE_ERROR', 32 => 'E_CORE_WARNING', 64 => 'E_COMPILE_ERROR', 128 => 'E_COMPILE_WARNING', 256 => 'E_USER_ERROR', 512 => 'E_USER_WARNING', 1024 => 'E_USER_NOTICE', 2048 => 'E_STRICT', 4096 => 'E_RECOVERABLE_ERROR', 8192 => 'E_DEPRECATED', 16384 => 'E_USER_DEPRECATED', 30719 => 'E_ALL', ]; $error['type'] = (!empty($errorType[$error['type']])) ? ($errorType[$error['type']]) : ('Unknown'); $error['message'] = Tool::toUTF8($error['message']); if (isset(self::$Config['log']['error_switch']) && self::$Config['log']['error_switch'] === true) { if ($this->judgeLevel($error['type'], self::$Config['log']['error_level'])) { $log = 'type: '; $log .= $error['type']; $log .= "\r\n" . 'message: ' . $error['message'] . "\r\n"; $log .= 'file: ' . $error['file'] . "\r\n"; $log .= 'line: ' . $error['line']; $Project = $this->getProjectName($error['file']); if ($Project) { App::$app->get('Log')->Record(Running::$framworkPath . '/Project/runtime/' . $Project . '/log', 'error', $log); } } } if (isset(self::$Config['Exception']['display_switch']) && self::$Config['Exception']['display_switch'] === true) { if ($this->judgeLevel($error['type'], self::$Config['Exception']['display_level'])) { $this->readErrorFile($error); } } } } /** * 判断错误级别 * @param $errorlevel * @param $error * @return bool */ private function judgeLevel($errorlevel, $error) { if (!empty($errorlevel) && !empty($error)) { if ($error == 'E_ALL') return true; $errorList = explode('|', $error); foreach ($errorList as $key => $value) { $errorList[$key] = trim($value); } return in_array($errorlevel, $errorList); } return false; } /** * 返回关联应用 * @param $Path * @return bool */ private function getProjectName($Path) { App::$app->get('Structure'); $Path = str_replace('\\', '/', $Path); $Temporary = explode('Project/', $Path); if (!empty($Temporary[1])) { $Temporary = explode('/', $Temporary[1]); if (!empty($Temporary[0]) && in_array($Temporary[0], Structure::$ProjectList)) { return $Temporary[0]; } return false; } return false; } /** * 处理错误文件 * @param $error */ public function readErrorFile($error) { if (Running::$runMode == 'cli') { $error_string = "\r\nPHP300FrameworkError:\r\nerror_messag:{$error['message']}"; if (isset($error['file'])) $error_string .= "\r\nerror_file:{$error['file']}"; if (isset($error['line'])) $error_string .= "\r\nerror_line:{$error['line']}"; die($error_string); } else { ob_clean(); } if (Running::$Debug === true) { header('HTTP/1.1 ' . Tool::httpcode(500)); if (isset($error['file'])) { $path = $error['file']; $line = isset($error['line']) && is_int($error['line']) ? $error['line'] : 0; if (file_exists($path) && $line > 0) { $handle = fopen($path, "r"); $count = 1; $content = []; while ($lines = fgets($handle)) { $content[] = array($count, $lines); $count++; if ($line == ($count - 5)) { break; } } fclose($handle); if (count($content) > 10) { $content = array_slice($content, -10, 15); } $code = ''; foreach ($content as $key => $value) { if ($value[0] == $line) { $value[0] = '<span color="red">>></span>'; } $code .= $value[0] . ' ' . $value[1]; } $error['code'] = $code; } } $View = View('', App::$app->corePath . 'Library/Process/Tpl/error.tpl'); $View->getView()->left_delimiter = '{'; $View->getView()->right_delimiter = '}'; die($View->data([ 'Path' => Tool::getPublic(), 'Error' => $error, 'Server' => $_SERVER ])->get()); } $this->displayed('error', [ 'title' => '网站抽风啦!', 'second' => '3', 'message' => '出错啦~~~', 'describe' => '系统异常,请联系管理员!', 'url' => '' ]); } /** * 展示状态页 * @param string $page * @param array $data */ public function displayed($page = 'success', $data = array()) { $View = View('', App::$app->corePath . 'Library/Process/Tpl/' . $page . '_page.tpl'); $View->getView()->left_delimiter = '{'; $View->getView()->right_delimiter = '}'; die($View->data(['data' => $data])->get()); } }
php
Apache-2.0
2ba403cd277680a050c457d39db2aef652fb8e8f
2026-01-05T04:52:44.635355Z
false
xcg340122/PHP300Framework2x
https://github.com/xcg340122/PHP300Framework2x/blob/2ba403cd277680a050c457d39db2aef652fb8e8f/Framework/Library/Process/Session.class.php
Framework/Library/Process/Session.class.php
<?php namespace Framework\Library\Process; use \Framework\Library\Interfaces\SessionInterface as SessionInterfaces; /** * Session操作器 * Class Session * @package Framework\Library\Process */ class Session implements SessionInterfaces { /** * @var string 缓存名称 */ private $Name = 'PHP300SESSION'; /** * @var string 缓存周期,单位:秒 */ private $Second = 0; /** * 开启session */ public function start() { if (!isset($_SESSION)) { ini_set('session.name', $this->Name); ini_set('session.auto_start', '1'); ini_set('session.cookie_lifetime', $this->Second); session_start(); } } /** * 获取session * @param string $name * @return bool */ public function get($name = '') { if (!empty($name)) { return (!empty($_SESSION[$name])) ? ($_SESSION[$name]) : (FALSE); } return $_SESSION; } /** * 设置session * @param string $name * @param string $value * @return string */ public function set($name = 'php300', $value = '') { $_SESSION[$name] = $value; return true; } /** * 删除session * @param string $name * @return string */ public function del($name = '') { if (empty($name)) { session_destroy(); } else { $_SESSION[$name] = NULL; } return true; } }
php
Apache-2.0
2ba403cd277680a050c457d39db2aef652fb8e8f
2026-01-05T04:52:44.635355Z
false
xcg340122/PHP300Framework2x
https://github.com/xcg340122/PHP300Framework2x/blob/2ba403cd277680a050c457d39db2aef652fb8e8f/Framework/Library/Process/Db.class.php
Framework/Library/Process/Db.class.php
<?php namespace Framework\Library\Process; use Framework\App; /** * 数据基础模型 * Class Db * @package Framework\Library\Process */ class Db { /** * @var array 数据库连接标识组 */ private $link = []; /** * @var string 操作库对象 */ private $db = ''; /** * @var array 数据库驱动映射 */ private $dbType = [ 'mysqli' => 'Drive\Db\Mysqli', 'pdo' => 'Drive\Db\Pdo' ]; /** * 构造方法 * Db constructor */ public function __construct() { $this->init(Config::$AppConfig['db']); } /** * 初始化数据库连接 * @param array $configArr */ public function init($configArr = []) { if (is_array($configArr)) { foreach ($configArr as $key => $value) { $this->addlink($key, $value); } } } /** * 添加连接信息 * @param $name * @param $config */ private function addlink($name, $config) { if (!empty($name) && is_array($config) && $config['connect'] === true) { if (isset($config['dbType']) && isset($this->dbType[strtolower($config['dbType'])]) && isset($config['username'])) { if (!isset($this->link[$name])) { $this->db = \Framework\App::$app->get($this->dbType[strtolower($config['dbType'])]); $this->putlink($name, ['obj' => $this->db, 'link' => $this->db->connect($config)]); } } } } /** * 压入连接 * @param $link */ private function putlink($name, $link) { $this->link[$name] = $link; } /** * 获取所有建立的连接 * @return array */ public function getlink() { return $this->link; } }
php
Apache-2.0
2ba403cd277680a050c457d39db2aef652fb8e8f
2026-01-05T04:52:44.635355Z
false
xcg340122/PHP300Framework2x
https://github.com/xcg340122/PHP300Framework2x/blob/2ba403cd277680a050c457d39db2aef652fb8e8f/Framework/Library/Process/Extend.class.php
Framework/Library/Process/Extend.class.php
<?php namespace Framework\Library\Process; use Framework\App; /** * 系统扩展器 * Class Extend * @package Framework\Library\Process */ class Extend { /** * @var string 包路径 */ public $PackagePath; /** * @var string 类路径 */ public $ClassPath; /** * @var string 已加载的扩展容器 */ public $Extendbox; /** * 初始化相关路径 * Extend constructor. */ public function __construct() { $this->PackagePath = Running::$framworkPath . 'Extend/Package/'; $this->ClassPath = Running::$framworkPath . 'Extend/Class/'; if (file_exists(Running::$framworkPath . 'vendor/autoload.php')){ require_once Running::$framworkPath . 'vendor/autoload.php'; } } /** * 加入新的扩展包 * @param string $PackageName * @return bool */ public function addPackage($PackageName = '') { if (!empty($PackageName) && file_exists($this->PackagePath . $PackageName)) { $PackageName = $this->PackagePath . $PackageName; $extension = self::get_extension($PackageName); if (strtolower($extension) == 'php') { include_once $PackageName; return true; } if (in_array($extension, ['zip', 'tar', 'rar'])) { $Packagezip = $this->getPackageName($PackageName); $this->releasePackage($PackageName, $this->PackagePath . 'Cache', $Packagezip); } } return false; } /** * 获取扩展信息 * @param $file * @return mixed */ public static function get_extension($file) { return pathinfo($file, PATHINFO_EXTENSION); } /** * 返回包名 * @param $Package * @return bool|mixed */ private function getPackageName($Package) { $extension = self::get_extension($Package); $path = explode('Package/', $Package); if (isset($path[1])) { return str_replace(array('.', $extension), '', $path[1]); } return false; } /** * 释放压缩文件 * @param string $zipfile * @param string $folder * @param $Packagezip * @return bool */ private function releasePackage($zipfile = '', $folder = '', $Packagezip) { if ($this->iszipload($folder, $Packagezip)) { return true; } if (class_exists('ZipArchive', false)) { $zip = new \ZipArchive; $res = $zip->open($zipfile); if ($res === TRUE) { $zip->extractTo($folder); $zip->close(); $this->iszipload($folder, $Packagezip); } else { App::$app->get('LogicExceptions')->readErrorFile([ 'file' => $zipfile, 'message' => "'{$zipfile}' 读取文件失败!" ]); } } else { App::$app->get('LogicExceptions')->readErrorFile([ 'file' => $zipfile, 'message' => "你需要先启动 PHP-ZipArchive 扩展!" ]); } return true; } /** * 加载扩展文件 * @param $folder * @param $Packagezip * @return bool */ private function iszipload($folder, $Packagezip) { $autoload = $folder . '/' . $Packagezip . '/autoload.php'; if (file_exists($autoload)) { include_once $autoload; $this->Extendbox[$Packagezip] = $this->getPackageInfo($folder . '/' . $Packagezip . '/info.php'); file_put_contents($folder . '/' . $Packagezip . '/marked.txt', 'This is an automatically unpacked package. Please do not manually modify or delete it! - PHP300Framework2x'); return true; } return false; } /** * 获取zip包信息 * @param string $infoPath * @return bool|mixed */ private function getPackageInfo($infoPath = '') { if (file_exists($infoPath)) { return include $infoPath; } return false; } /** * 加入新的扩展类 * @param string $ClassName * @return bool */ public function addClass($ClassName = '') { if (!empty($ClassName) && file_exists($this->ClassPath . $ClassName)) { include_once $this->ClassPath . $ClassName; } return false; } /** * 返回已加载的包信息 * @return string */ public function getPackagebox() { return $this->Extendbox; } }
php
Apache-2.0
2ba403cd277680a050c457d39db2aef652fb8e8f
2026-01-05T04:52:44.635355Z
false
xcg340122/PHP300Framework2x
https://github.com/xcg340122/PHP300Framework2x/blob/2ba403cd277680a050c457d39db2aef652fb8e8f/Framework/Library/Process/Running.class.php
Framework/Library/Process/Running.class.php
<?php namespace Framework\Library\Process; /** * 运行监视器 * Class Running * @package Framework\Library\Process */ class Running { /** * 是否系统异常 * @var bool */ static public $iserror = false; /** * 运行模式 * @var string */ static public $runMode = 'cgi'; /** * 开发模式(true=>调试模式,false=>线上模式) * @var bool */ static public $Debug; /** * 路径信息 * @var string */ static public $framworkPath; /** * 监视运行参数 * @var array */ public $param = []; /** * 运行构造 * Running constructor. */ public function __construct() { self::$framworkPath = str_replace('Framework/', '', \Framework\App::$app->corePath); } /** * 预定义常量信息 */ static public function setconstant() { $define = [ 'RES' => Tool::getPublic(), '_P' => Visit::$param['Project'], '_C' => Visit::$param['Controller'], '_F' => Visit::$param['Function'], '_T' => time(), '_V' => '2.5.3' ]; foreach ($define as $key => $value) { define($key, $value); } } /** * 设定开发模式 * @param bool $status */ public function isDev($status = true) { self::$Debug = $status; } /** * 开始记录信息 */ public function startRecord() { $this->param['startTime'] = microtime(true); $this->param['startRam'] = (function_exists('memory_get_usage')) ? (memory_get_usage()) : (0); } /** * 停止记录信息 */ public function endRecord() { $this->param['endTime'] = microtime(true); $this->param['endRam'] = (function_exists('memory_get_usage')) ? (memory_get_usage()) : (0); $this->param['consumeRam'] = $this->consumeRam(($this->param['endRam'] - $this->param['startRam'])); } /** * 计算消耗的内存 */ private function consumeRam($size) { $unit = array('b', 'kb', 'mb', 'gb', 'tb', 'pb'); return @round($size / pow(1024, ($i = floor(log($size, 1024)))), 2) . ' ' . $unit[$i]; } /** * 程序汇总处理 * @return array */ public function TotalInfo() { return $this->param; } }
php
Apache-2.0
2ba403cd277680a050c457d39db2aef652fb8e8f
2026-01-05T04:52:44.635355Z
false
xcg340122/PHP300Framework2x
https://github.com/xcg340122/PHP300Framework2x/blob/2ba403cd277680a050c457d39db2aef652fb8e8f/Framework/Library/Process/Config.class.php
Framework/Library/Process/Config.class.php
<?php namespace Framework\Library\Process; use Framework\App; use \Framework\Library\Interfaces\ConfigInterface as ConfigInterfaces; /** * 配置处理器 * Class Config * @package Framework\Library\Process */ class Config implements ConfigInterfaces { /** * @var string 配置路径 */ private $ConfigPath; /** * @var array 配置容器 */ private $Config = []; /** * @var array 应用配置 */ static public $AppConfig = []; /** * 初始化配置信息 * Config constructor. */ public function __construct() { $this-> ConfigPath = Running::$framworkPath . 'Project/config'; if (!file_exists($this->ConfigPath)) { App::$app->get('Structure')->createDir($this->ConfigPath); } else { $fileList = App::$app->get('Structure')->getDir($this->ConfigPath); if (is_array($fileList)) { foreach ($fileList as $key => $value) { if (strpos(strtolower($value), '.cfg.php')) { $this->read(str_replace('.cfg.php', '', $value), $this->ConfigPath . '/' . $value); } } if(isset($this->Config['App'])){ self::$AppConfig = $this->Config['App']; } } } $this->loadFrameconf(); } /** * 读取配置文件 * @param string $configName * @param string $filePath */ private function read($configName = '', $filePath = '') { if (is_file($filePath)) $this->Config[$configName] = include_once $filePath; } /** * 获取配置项 * @param $keys * @return mixed */ public function get($keys = null) { if (is_null($keys)) return $this->Config; if (count($this->Config) > 0 && !empty($keys) && isset($this->Config[$keys])) { return $this->Config[$keys]; } return false; } /** * 设置临时配置项 * @param $key * @param $val */ public function set($key, $val) { if (!empty($key) && isset($val)) { $this->Config[] = [$key => $val]; } } /** * 加载框架配置文件 */ private function loadFrameconf() { $this->read('frame', App::$app->corePath . 'Config/frame.cfg.php'); } }
php
Apache-2.0
2ba403cd277680a050c457d39db2aef652fb8e8f
2026-01-05T04:52:44.635355Z
false
xcg340122/PHP300Framework2x
https://github.com/xcg340122/PHP300Framework2x/blob/2ba403cd277680a050c457d39db2aef652fb8e8f/Framework/Library/Process/Cache.class.php
Framework/Library/Process/Cache.class.php
<?php namespace Framework\Library\Process; use Framework\App; /** * 缓存器 * Class Cache * @package Framework\Library\Process */ class Cache { /** * @var object 操作对象 */ private $object; /** * @var array 数据库驱动映射 */ private $CacheType = [ 'memcache' => 'Drive\Cache\Memcache', 'redis' => 'Drive\Cache\Redis', 'file' => 'Drive\Cache\File' ]; /** * 初始化缓存配置 */ public function init() { $CacheConfig = Config::$AppConfig['cache']; if (is_array($CacheConfig) && isset($CacheConfig['ip'])) { $this->object = App::$app->get($this->CacheType[strtolower($CacheConfig['cacheType'])]); if(strtolower($CacheConfig['cacheType']) != 'file'){ $this->object->connect($CacheConfig['ip'], $CacheConfig['port']); } } return $this; } /** * 获取操作对象实例 * @return object */ public function getObj() { return $this->object; } }
php
Apache-2.0
2ba403cd277680a050c457d39db2aef652fb8e8f
2026-01-05T04:52:44.635355Z
false
xcg340122/PHP300Framework2x
https://github.com/xcg340122/PHP300Framework2x/blob/2ba403cd277680a050c457d39db2aef652fb8e8f/Framework/Library/Process/View.class.php
Framework/Library/Process/View.class.php
<?php namespace Framework\Library\Process; use \Framework\Library\Interfaces\ViewInterface as ViewInterfaces; /** * 视图处理器 * Class View * @package Framework\Library\Process */ class View implements ViewInterfaces { /** * @var string 视图编译目录 */ private $ViewCompile = ''; /** * @var string 视图存放目录 */ private $ViewPath = ''; /** * @var string 视图缓存目录 */ private $ViewCache = ''; /** * @var object 视图对象 */ private $View; /** * @var string 模板文件 */ private $file = ''; /** * @var array 变量集合 */ private $variable = []; /** * 初始化视图信息 * @return mixed|\Smarty */ public function init() { $dir = Running::$iserror ? 'view' : Visit::$param['Project']; $this->ViewCompile = Running::$framworkPath . 'Project/runtime/' . $dir . '/view'; $this->ViewPath = Running::$framworkPath . 'Project/view'; $this->ViewCache = $this->ViewCompile . '/cache'; $functions = spl_autoload_functions(); foreach ($functions as $function) { spl_autoload_unregister($function); } \Framework\App::$app->get('Extend')->addPackage('smarty/Smarty.class.php'); $this->dirProcessing([ $this->ViewCompile, $this->ViewPath, $this->ViewCache ]); $this->View = $this->ViewConfig($this->ReturnView()); return $this; } /** * 设定操作的文件 * @param $fileName */ public function set($fileName) { $this->file = $fileName; } /** * 获取渲染数据 * @return bool|string */ public function get() { if ($this->file == '') { return false; } foreach ($this->variable as $key => $value) { $this->View->assign($key, $value); } $html = $this->View->fetch($this->file); if (strpos($this->file, 'error.tpl') !== false && $html == '') { die('程序异常,请查看日志!'); } return $html; } /** * 模板变量集合 * @param $name * @param $value */ public function __set($name, $value) { if (!in_array($name, $this->variable)) { $this->variable[$name] = $value; } } /** * 设定模板变量 * @param null $data * @return $this */ public function data($data = null) { if (is_array($data)) { foreach ($data as $key => $value) { $this->variable[$key] = $value; } } return $this; } /** * 处理文件夹 * @param $dir */ private function dirProcessing($dir) { if (is_array($dir)) { foreach ($dir as $value) { Structure::createDir($value); } } } /** * 实例化视图 * @return \Smarty */ private function ReturnView() { $view = new \Smarty(); $view->setTemplateDir($this->ViewPath); $view->setCompileDir($this->ViewCompile); $view->setCacheDir($this->ViewCache); return $view; } /** * 配置视图 * @param $view * @return mixed */ private function ViewConfig($view) { $Config = LogicExceptions::$Config['View']; $view->cache_lifetime = $Config['cache_lifetime']; $view->caching = $Config['is_cache']; $view->left_delimiter = $Config['left_delimiter']; $view->right_delimiter = $Config['right_delimiter']; return $view; } /** * 获取Smarty原型 * @return mixed */ public function getView() { return $this->View; } }
php
Apache-2.0
2ba403cd277680a050c457d39db2aef652fb8e8f
2026-01-05T04:52:44.635355Z
false
xcg340122/PHP300Framework2x
https://github.com/xcg340122/PHP300Framework2x/blob/2ba403cd277680a050c457d39db2aef652fb8e8f/Framework/Library/Process/Tool.class.php
Framework/Library/Process/Tool.class.php
<?php namespace Framework\Library\Process; /** * 系统辅助器 * Class Tool * @package Framework\Library\Process */ class Tool { /** * HTTP状态码 * @param string $code 状态码 * @return mixed|string */ static public function httpcode($code = '200') { $http = [ '100' => '100 Continue', '101' => '101 Switching Protocols', '200' => '200 OK', '201' => '201 Created', '202' => '202 Accepted', '203' => '203 Non-Authoritative Information', '204' => '204 No Content', '205' => '205 Reset Content', '206' => '206 Partial Content', '300' => '300 Multiple Choices', '301' => '301 Moved Permanently', '302' => '302 Found', '303' => '303 See Other', '304' => '304 Not Modified', '305' => '305 Use Proxy', '307' => '307 Temporary Redirect', '400' => '400 Bad Request', '401' => '401 Unauthorized', '402' => '402 Payment Required', '403' => '403 Forbidden', '404' => '404 Not Found', '405' => '405 Method Not Allowed', '406' => '406 Not Acceptable', '407' => '407 Proxy Authentication Required', '408' => '408 Request Time-out', '409' => '409 Conflict', '410' => '410 Gone', '411' => '411 Length Required', '412' => '412 Precondition Failed', '413' => '413 Request Entity Too Large', '414' => '414 Request-URI Too Large', '415' => '415 Unsupported Media Type', '416' => '416 Requested range not satisfiable', '417' => '417 Expectation Failed', '500' => '500 Internal Server Error', '501' => '501 Not Implemented', '502' => '502 Bad Gateway', '503' => '503 Service Unavailable', '504' => '504 Gateway Time-out', '505' => '505 HTTP Version not supported' ]; return !empty($http[$code]) ? $http[$code] : 'Unknown'; } /** * 获取客户端IP * @return string */ static public function getIP() { if (isset($_SERVER)) { if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) { $realip = $_SERVER['HTTP_X_FORWARDED_FOR']; } elseif (isset($_SERVER['HTTP_CLIENT_IP'])) { $realip = $_SERVER['HTTP_CLIENT_IP']; } else { $realip = $_SERVER['REMOTE_ADDR']; } } else { if (getenv("HTTP_X_FORWARDED_FOR")) { $realip = getenv("HTTP_X_FORWARDED_FOR"); } elseif (getenv("HTTP_CLIENT_IP")) { $realip = getenv("HTTP_CLIENT_IP"); } else { $realip = getenv("REMOTE_ADDR"); } } return $realip; } /** * 302重定向 * @param string $url 跳转的URL地址 */ static public function redirect($url) { header("Location: {$url}"); die(); } /** * 生成URL * @param string $name 地址 * @param string $parm 参数 * @return String */ static public function Url($name, $parm = '') { if (!empty($name)) { $SSL = (self::isSSL()) ? ('https://') : ('http://'); $Port = self::Receive('server.SERVER_PORT'); $Port = ($Port != '80') ? ($Port) : (''); $ExecFile = explode('.php', self::Receive('server.PHP_SELF')); $Path = (count($ExecFile) > 0) ? ($ExecFile[0] . '.php') : (''); $Url = $SSL . self::Receive('server.HTTP_HOST') . $Port . $Path; if (strpos($name, '/')) { $PathArr = explode('/', $name); foreach ($PathArr as $val) { if (!empty($val)) $Url .= '/' . $val; } if (!empty($parm)) $Url .= '?' . $parm; } return $Url; } return false; } /** * 判断是否为SSL连接 * @return bool */ static public function isSSL() { $HTTPS = self::Receive('server.HTTPS'); $PORT = self::Receive('server.SERVER_PORT'); if (isset($HTTPS) && ('1' == $HTTPS || 'on' == strtolower($HTTPS))) { return true; } elseif (isset($PORT) && ('443' == $PORT)) { return true; } return false; } /** * 获取http数据 * @param string $name 获取的名称 * @param string $null 默认返回 * @param bool $isEncode 是否编码 * @param string $function 编码函数 * @return string */ static public function Receive($name = '', $null = '', $isEncode = true, $function = 'htmlspecialchars') { if (strpos($name, '.')) { $method = explode('.', $name); $name = $method[1]; $method = $method[0]; } else { $method = ''; } switch (strtolower($method)) { case 'get': $Data = &$_GET; break; case 'post': $Data = &$_POST; break; case 'put': parse_str(file_get_contents('php://input'), $Data); break; case 'globals': $Data = &$GLOBALS; break; case 'session': $Data = &$_SESSION; break; case 'server': $Data = &$_SERVER; break; default: switch ($_SERVER['REQUEST_METHOD']) { default: $Data = &$_GET; break; case 'POST': $Data = &$_POST; break; case 'PUT': parse_str(file_get_contents('php://input'), $Data); break; }; break; } if (isset($Data[$name])) { if (is_array($Data[$name])) { foreach ($Data[$name] as $key => $val) { $Data[$key] = ($isEncode) ? ((function_exists($function)) ? ($function($val)) : ($val)) : ($val); } return $Data[$name]; } else { $value = ($isEncode) ? ((function_exists($function)) ? ($function($Data[$name])) : ($Data[$name])) : ($Data[$name]); return (!is_null($value)) ? ($value) : (($null) ? ($null) : ('')); } } else { return $null; } } /** * 将字符编码转换到utf8 * @param string $string 欲转换的字符串 * @return string */ static public function toUTF8($string = '') { if (!empty($string)) { $encoding = mb_detect_encoding($string, array('ASCII', 'UTF-8', 'GB2312', 'GBK', 'BIG5')); if ($encoding != 'UTF-8') { return iconv($encoding, 'UTF-8', $string); } return $string; } return false; } /** * 判断是否为get请求 * @return bool */ static public function isGET() { if (self::Receive('server.REQUEST_METHOD') == 'GET') { return true; } return false; } /** * 判断是否为POST请求 * @return bool */ static public function isPOST() { if (self::Receive('server.REQUEST_METHOD') == 'POST') { return true; } return false; } /** * 判断是否为Ajax请求 * @return bool */ static public function isAjax() { if (isset($_SERVER["HTTP_X_REQUESTED_WITH"])){ if(strtolower($_SERVER["HTTP_X_REQUESTED_WITH"]) == 'xmlhttprequest'){ return true; } } else { if(strpos('application/json',self::Receive('server.HTTP_ACCEPT'))){ return true; } return false; } return false; } /** * 判断是否为cli运行模式 * @return bool */ static public function isCli() { if (Running::$runMode == 'cli') { return true; } return false; } /** * 判断是否为windows * @return bool */ static public function isWin() { if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') { return true; } return false; } /** * 生成随机字符串 * @param int $len 字符长度 * @param bool $lower 是否转小写 * @return int|mixed|string */ static public function RandStr($len = 8, $lower = false) { $str = null; $strPol = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz"; $max = strlen($strPol) - 1; for ($i = 0; $i < $len; $i++) { $str .= $strPol[rand(0, $max)]; //rand($min,$max)生成介于min和max两个数之间的一个随机整数 } return ($lower) ? strtolower($str) : $str; } /** * 通过一个文本影响加密字符 * @param string $pwd 影响密码 * @param string $str 欲加密的内容 * @return string */ static public function impact($pwd,$str='') { return md5(md5(base64_encode($pwd)) . md5($str)); } /** * 获取Public路径 * @return string */ static public function getPublic() { $scriptName = str_replace('\\', '/', dirname($_SERVER['SCRIPT_NAME'])); if (empty($scriptName)) $scriptName = '/'; if (substr($scriptName, -1) != '/') $scriptName .= '/'; return rtrim($scriptName) . 'Public/'; } }
php
Apache-2.0
2ba403cd277680a050c457d39db2aef652fb8e8f
2026-01-05T04:52:44.635355Z
false
xcg340122/PHP300Framework2x
https://github.com/xcg340122/PHP300Framework2x/blob/2ba403cd277680a050c457d39db2aef652fb8e8f/Framework/Library/Process/Log.class.php
Framework/Library/Process/Log.class.php
<?php namespace Framework\Library\Process; use \Framework\Library\Interfaces\LogInterface as LogInterfaces; /** * 日志处理器 * Class Log * @package Framework\Library\Process */ class Log implements LogInterfaces { /** * @var string 日志文件后缀 */ public $extend = '.log'; /** * 写出动作(划分日期和大小) * @param $fileName * @param $Content * @param int $count */ private function Write($fileName, $Content, $count = 0) { $fileExt = $count > 0 ? '(' . $count . ')' : ''; $fileLine = $fileName . '_' . date('Y-m-d', time()) . $fileExt; $fileNames = $fileLine . $this->extend; if (file_exists($fileNames)) { $size = number_format(filesize($fileNames) / 1024 / 1024, 3); if ($size > 3) { $number = intval(substr($fileLine, -2, 1)) + 1; $this->Write($fileName, $Content, $number); } else { file_put_contents($fileNames, $Content, FILE_APPEND); } } else { file_put_contents($fileNames, $Content, FILE_APPEND); } } /** * 记录动作 * @param $LogPath * @param $fileName * @param $Log * @return bool|mixed */ public function Record($LogPath, $fileName, $Log) { if (strpos($LogPath, '/') === false) $LogPath = Running::$framworkPath . '/Project/runtime/' . $LogPath . '/log'; if (!empty($Log)) { if (!file_exists($LogPath)) { Structure::createDir($LogPath); } $Log = "[" . date('Y-m-d H:i:s') . "]\r\n$Log\r\n------------------\r\n\r\n "; $this->Write($LogPath . '/' . $fileName, $Log); return true; } return false; } }
php
Apache-2.0
2ba403cd277680a050c457d39db2aef652fb8e8f
2026-01-05T04:52:44.635355Z
false
xcg340122/PHP300Framework2x
https://github.com/xcg340122/PHP300Framework2x/blob/2ba403cd277680a050c457d39db2aef652fb8e8f/Framework/Library/Process/Router.class.php
Framework/Library/Process/Router.class.php
<?php namespace Framework\Library\Process; use Framework\App; use Framework\Library\Interfaces\RouterInterface as RouterInterfaces; /** * 系统路由 * Class Router * @package Framework\Library\Process */ class Router implements RouterInterfaces { /** * @var string 用户请求地址 */ static public $requestUrl = ''; /** * @var array 路由配置信息 */ private $RouteConfig = []; /** * 初始化构造 * Router constructor. */ public function __construct() { if(Running::$runMode != 'cli'){ $this->RouteConfig = Config::$AppConfig['router']; self::$requestUrl = !empty($_SERVER['PATH_INFO']) ? $_SERVER['PATH_INFO'] : $_SERVER['REQUEST_URI']; $this->Route(); $this->Matching(); $this->TraditionUrl(); } } /** * 默认路由 * @return mixed|void */ public function Route() { if (strpos(self::$requestUrl, '?')) { preg_match_all('/^\/(.*)\?/', self::$requestUrl, $Url); } else { preg_match_all('/^\/(.*)/', self::$requestUrl, $Url); } if (empty($Url[1][0])) return; $Url = $Url[1][0]; $Url = explode('/', $Url); App::$app->get('Visit')->bind($Url); } /** * 路由匹配 */ private function Matching() { if (self::$requestUrl == '') { $Url = '/'; } else { $Url = '/' . ucwords(Visit::$param['Project']) . '/' . ucwords(Visit::$param['Controller']) . '/' . Visit::$param['Function']; } $Url = strtolower($Url); if (count($this->RouteConfig) > 0 && isset($this->RouteConfig[$Url])) { $function = $this->RouteConfig[$Url]; if (gettype($function) == 'object') { App::$app->get('ReturnHandle')->Output($function()); die(); } } } /** * 传统URL请求匹配 */ private function TraditionUrl() { $Project = get(Visit::$request['Project']); $Controller = get(Visit::$request['Controller']); $Function = get(Visit::$request['Function']); if (!empty($Project)) { $list = Structure::$ProjectList; $ins = ['model','view']; foreach ($list as $key=>$val){ if(in_array($val,$ins)){ unset($list[$key]); } } if(in_array($Project,$list)){ Visit::$param['Project'] = $Project; }else{ App::$app->get('LogicExceptions')->readErrorFile([ 'message' => '抱歉,您请求的实例不存在!(请检查您的GET参数'.Visit::$request['Project'].')' ]); } } if (!empty($Controller)) { Visit::$param['Controller'] = $Controller; } if (!empty($Function)) { Visit::$param['Function'] = $Function; } } }
php
Apache-2.0
2ba403cd277680a050c457d39db2aef652fb8e8f
2026-01-05T04:52:44.635355Z
false
xcg340122/PHP300Framework2x
https://github.com/xcg340122/PHP300Framework2x/blob/2ba403cd277680a050c457d39db2aef652fb8e8f/Framework/Library/Process/Structure.class.php
Framework/Library/Process/Structure.class.php
<?php namespace Framework\Library\Process; use Framework\App; /** * 系统结构加载器 * Class Structure * @package Framework\library\_class */ class Structure { /** * @var array 应用列表 */ static public $ProjectList = []; /** * @var string 最后读入的文件 */ static public $endfile = null; /** * @var string 后缀信息 */ private $extend; /** * 初始化构造 * Structure constructor. */ public function __construct() { spl_autoload_register([&$this, '__autoload']); $this->getProjectList(); $this->RunTimeInit(); } /** * 获取应用列表 */ public function getProjectList() { $getPath = Running::$framworkPath . '/Project/'; $Project = $this->getDir($getPath); if (is_array($Project) && count($Project) > 0) { $array = ['runtime','config']; foreach ($Project as $value) { if (is_dir($getPath . $value) && !in_array($value, $array)) { self::$ProjectList[] = $value; } } } } /** * 获取目录 * @param $path * @return array|bool */ static public function getDir($path) { if (is_dir($path)) { return array_merge(array_diff(scandir($path), array('.', '..'))); } return false; } /** * 初始化结构信息 */ private function RunTimeInit() { $this->checkPower(Running::$framworkPath . 'tmp'); $getPath = Running::$framworkPath . 'Project/'; $CreateDefaultDir = ['log']; if (is_array(self::$ProjectList) && count(self::$ProjectList) > 0) { foreach (self::$ProjectList as $value) { foreach ($CreateDefaultDir as $default) { self::createDir($getPath . 'runtime/' . $value . '/' . $default); } } } require App::$app->corePath . 'Library/Common/helper.php'; } /** * 遍历创建目录 * @param $path */ static public function createDir($path) { if (!is_dir($path)) { self::createDir(dirname($path)); if (mkdir($path, 0777) === false) { die('PHP300:No written permission -> (PATH:' . $path . ')'); } } } /** * 自动加载实现 * @param string $class 加载对象 */ public function __autoload($class) { $class = str_replace('\\', '/', $class); $istrpos = strpos($class, '/Interfaces'); $framworkPath = $istrpos ? App::$app->corePath : Running::$framworkPath; $this->extend = $istrpos ? '.php' : '.class.php'; $fileObj = strpos($class, 'App/') !== false ? $framworkPath . str_replace('App/', 'Project/', $class) . $this->extend : $framworkPath . str_replace('Framework/', '', $class) . $this->extend; if (file_exists($fileObj)) { self::$endfile = $fileObj; include_once($fileObj); } else { Running::$iserror = true; if (strpos($fileObj, 'Project/')) { $this->getStaticTpl(); $error = [ 'message' => '您请求的方法不存在' ]; } else { $error = [ 'file' => $fileObj, 'message' => '您引用了一个不存在的文件!' ]; } App::$app->get('LogicExceptions')->readErrorFile($error); } } /** * 寻找静态模板 */ public function getStaticTpl() { $file = Running::$framworkPath.'Project/view'.Router::$requestUrl; if (file_exists($file) && is_file($file)) { die(View('', $file)->get()); } } /** * 检查权限 * @param $path */ private function checkPower($path) { if (Tool::isWin() === false && file_exists($path) === false) { if (file_put_contents($path, '') === false) { die('PHP300Framework Adequate privileges are required to run!(' . $path . ')'); } else { unlink($path); } } } }
php
Apache-2.0
2ba403cd277680a050c457d39db2aef652fb8e8f
2026-01-05T04:52:44.635355Z
false
xcg340122/PHP300Framework2x
https://github.com/xcg340122/PHP300Framework2x/blob/2ba403cd277680a050c457d39db2aef652fb8e8f/Framework/Library/Process/Visit.class.php
Framework/Library/Process/Visit.class.php
<?php namespace Framework\Library\Process; use Framework\App; use Framework\Library\Interfaces\VisitInterface as VisitInterfaces; /** * 访问处理器 * Class Visit * @package Framework\Library\Process */ class Visit implements VisitInterfaces { /** * @var array 访问配置参数 */ static public $param; /** * @var array 默认请求参数 */ static public $request; /** * 初始化构造 * Visit constructor. */ public function __construct() { $VisitConfig = App::$app->get('Config')->get('frame'); if (isset($VisitConfig['Visit'])) { self::$param = $VisitConfig['Visit']; } if (isset($VisitConfig['Parameter'])) { self::$request = $VisitConfig['Parameter']; } $VisitConfig = Config::$AppConfig['safe']; $origin = isset($_SERVER['HTTP_ORIGIN']) ? $_SERVER['HTTP_ORIGIN'] : ''; if (!empty($origin)) { if (in_array($origin, $VisitConfig['ajax_domain'])) { header('Access-Control-Allow-Origin:' . $origin); } } } /** * 合并访问对象 * @return string */ static public function mergeParam() { App::$app->get('Router'); return self::$param['namespace'] . '\\' . strtolower(self::$param['Project']) . '\\' . ucwords(self::$param['Controller']); } /** * 获取对象方法 * @return mixed */ static public function getfunction() { if (empty(self::$param['Function'])) { App::$app->get('LogicExceptions')->readErrorFile([ 'file' => Structure::$endfile, 'message' => '无法执行空方法!' ]); } return self::$param['Function']; } /** * 设定CLI模式参数 * @return bool */ static function setCliParam() { if (isset($_SERVER['argv'])) { $param = $_SERVER['argv']; if (count($param) > 3) { foreach ($param as $key => $value) { if ($key > 0) { $param[($key - 1)] = $value; } } unset($param[3]); App::$app->get('Visit')->bind($param); } else { if (count($param) === 1) { return true; } die('PHP300::Inadequacy of parameters!'); } } else { die('PHP300:server.argv not found'); } return false; } /** * 绑定数默认实例 * @param $param */ public function bind($param) { if (is_array($param)) { $count = count($param); switch ($count) { case 1: self::$param['Controller'] = $param[0]; break; case 2: self::$param['Controller'] = $param[0]; self::$param['Function'] = $param[1]; break; case 3: $banList = ['model','config','runtime','view']; if(!in_array(strtolower($param[0]),$banList)){ self::$param['Project'] = $param[0]; self::$param['Controller'] = $param[1]; self::$param['Function'] = $param[2]; } break; } if (isset(self::$param['Function'])) { self::$param['Function'] = str_replace(self::$param['extend'], '', self::$param['Function']); } } } }
php
Apache-2.0
2ba403cd277680a050c457d39db2aef652fb8e8f
2026-01-05T04:52:44.635355Z
false
xcg340122/PHP300Framework2x
https://github.com/xcg340122/PHP300Framework2x/blob/2ba403cd277680a050c457d39db2aef652fb8e8f/Framework/Library/Process/ReturnHandle.class.php
Framework/Library/Process/ReturnHandle.class.php
<?php namespace Framework\Library\Process; /** * 返回值处理器 * Class ReturnHandle * @package Framework\Library\Process */ class ReturnHandle { /** * 处理返回值输出 * @param string $Obj 反馈的数据信息 */ public function Output($Obj = '') { if(is_object($Obj) || is_array($Obj)){ header('content-type:application/json;charset=utf-8'); echo json_encode($Obj); }else{ echo $Obj; } } }
php
Apache-2.0
2ba403cd277680a050c457d39db2aef652fb8e8f
2026-01-05T04:52:44.635355Z
false
xcg340122/PHP300Framework2x
https://github.com/xcg340122/PHP300Framework2x/blob/2ba403cd277680a050c457d39db2aef652fb8e8f/Framework/Library/Process/Drive/Db/PDO.php
Framework/Library/Process/Drive/Db/PDO.php
<?php namespace Framework\Library\Process\Drive\Db; use Framework\App; use Framework\Library\Interfaces\DbInterface as DbInterfaces; use Framework\Library\Process\Running; /** * PDO Driver * Class PDO */ class Pdo implements DbInterfaces { /** * @var string 数据错误信息 */ public $dbErrorMsg = 'SQL IN WRONG: '; /** * @var int 获取方式 */ public $fetchMethod = \PDO::FETCH_OBJ; /** * @var \PDO 实例对象 */ protected $pdo; /** * @var bool|\PDORow|array 结果集 */ protected $result = false; /** * @var int 影响条数 */ protected $total; /** * @var null|string 操作表名 */ protected $tableName = NULL; /** * @var array debug */ protected $queryDebug = []; /** * @var string 数据主键 */ protected $key = ''; /** * @var bool 是否缓存数据 */ protected $iscache = false; /** * @var array 数据表信息 */ protected $data = []; /** * @var string 数据库名 */ protected $database = ''; /** * @var string 表前缀 */ protected $tabprefix = ''; /** * 获取异常信息 * @return mixed */ public function getError() { return $this->pdo->errorInfo(); } /** * 连接数据库 * @param array $config * @return bool|mixed|\PDO */ public function connect($config = []) { if (count($config) == 0) { return false; } try { $dsn = !empty($config['dsn']) ? $config['dsn'] : "mysql:host=" . $config['host'] . ";port=" . $config['port'] . ";dbname=" . $config['database']; $opt = array( \PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION, \PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES '" . $config['char'] . "'" ); $this->pdo = new \PDO($dsn, $config['username'], $config['password'], $opt); $this->database = $config['database']; if(!empty($config['tabprefix'])){ $this->tabprefix = $config['tabprefix']; } return $this->pdo; } catch (\PDOException $ex) { exit($this->dbErrorMsg . $ex->getMessage()); } } /** * 操作多数据库连接 * @param $link * @return $this */ public function setlink($link) { $this->pdo = $link; return $this; } /** * 销毁连接 * @return bool */ public function disconnect() { $this->pdo = NULL; return true; } /** * 获取所有记录 * @return bool */ public function get() { return $this->result; } /** * 获取默认记录 * @return array|mixed|null */ public function find() { if ($this->result) { return count($this->result) > 0 ? $this->result[0] : NULL; } return NULL; } /** * debug * @return array */ public function debug() { return $this->queryDebug; } /** * 获取影响的条数 * @return mixed */ public function total() { return $this->total; } /** * 执行SQL * @param $queryString * @param bool $select * @return $this */ public function query($queryString, $select = false) { try { $qry = $this->pdo->prepare($queryString); $qry->execute(); $qry->setFetchMode($this->fetchMethod); if ($this->startsWith(strtolower($queryString), "select")) { $this->result = $qry->fetchAll(); } $this->total = $qry->rowCount(); $this->queryDebug = ['string' => $queryString, 'total' => $this->total]; $this->handleres($queryString); } catch (\PDOException $ex) { $this->handleres($queryString, true . $ex); } return $this; } /** * If string starts with * * @param $haystack * @param $needle * @return bool */ protected function startsWith($haystack, $needle) { return $needle === "" || strrpos($haystack, $needle, -strlen($haystack)) !== FALSE; } /** * 处理结果 * @param $sql * @param bool $iserror * @param array $ex */ private function handleres($sql, $iserror = false, $ex = []) { /** * @var \PDOException $ex */ $errorMsg = ''; if ($iserror) { $status = 'error'; $errorMsg = $ex->getMessage(); } else { $status = 'success'; } $Logs = "[{$status}] " . $sql; if (isset($errorMsg)) { $Logs .= "\r\n[message] " . $errorMsg; } App::$app->get('Log')->Record(Running::$framworkPath . '/Project/runtime/datebase', 'sql', $Logs); if ($iserror) { $message = $errorMsg . ' (SQL:' . $sql . ')'; App::$app->get('LogicExceptions')->readErrorFile([ 'type' => 'DataBase Error', 'message' => $message ]); } } /** * 选择数据表 * @param $tableName * @return $this|bool */ public function table($tableName = '') { if (!empty($tableName)) { $this->tableName = '`' . $this->tabprefix . $tableName . '`'; $this->getTableInfo(); return $this; } else { App::$app->get('LogicExceptions')->readErrorFile([ 'file' => __FILE__, 'message' => 'Need to fill in Table Value!', ]); } return false; } /** * 返回数据表信息 * @return array|bool */ protected function getTableInfo() { if ($this->tableName == '') { App::$app->get('LogicExceptions')->readErrorFile([ 'message' => '尚未设定操作的数据表名称' ]); } else { $queryString = str_replace('`', '', "select COLUMN_NAME,DATA_TYPE,COLUMN_DEFAULT,COLUMN_KEY,COLUMN_COMMENT from information_schema.COLUMNS where table_name = '" . $this->tableName . "';"); $qry = $this->pdo->prepare($queryString); $qry->execute(); $qry->setFetchMode(\PDO::FETCH_ASSOC); $this->data = $qry->fetchAll(); if ($this->data) { foreach ($this->data as $key => $value) { if ($this->data[$key]['COLUMN_KEY'] == 'PRI') { $this->key = $this->data[$key]['COLUMN_NAME']; break; } return $this->data; } return false; } } return false; } /** * 查询数据 * @param array $qryArray * @return $this|bool */ public function select($qryArray = []) { $field = ''; $join = ''; $where = ''; $order = ''; $group = ''; $limit = ''; if (isset($qryArray['field'])) { if(is_array($qryArray['field'])){ if(isset($qryArray['field']['NOT'])){ if(is_array($qryArray['field']['NOT'])){ $field_arr = $this->getField(); if(is_array($field_arr)){ foreach ($field_arr as $key=>$value) { if(!in_array($value['COLUMN_NAME'] , $qryArray['field']['NOT'])){ $field .= '`'.$value['COLUMN_NAME'] . '`,'; } } $field = rtrim($field,'.,'); } } }else{ foreach ($qryArray['field'] as $key=>$value){ $field .= $this->inlon($value); } $field = rtrim($field,'.,'); } }else{ $field = $qryArray['field']; } } if (empty($field)) $field = ' * '; if (isset($qryArray['join'])) { $join = is_array($qryArray['join']) ? ' '.implode(' ', $qryArray['join']) : ' '.$qryArray['join']; } if (isset($qryArray['where'])) { $where = $this->structureWhere($qryArray['where']); } if (isset($qryArray['orderby'])) { $order = is_array($qryArray['orderby']) ? implode(',', $qryArray['orderby']) : $qryArray['orderby']; $order = ' ORDER BY ' . $order; } if (isset($qryArray['groupby'])) { $group = is_array($qryArray['groupby']) ? implode(',', $qryArray['groupby']) : $qryArray['groupby']; $group = ' GROUP BY ' . $group; } if (isset($qryArray['limit'])) { $limit = is_array($qryArray['limit']) ? implode(',', $qryArray['limit']) : $qryArray['limit']; $limit = ' LIMIT ' . $limit; } $queryString = 'SELECT ' . $field . ' FROM ' . $this->tableName . $join . $where . $group . $order . $limit; try { $qry = $this->pdo->prepare($queryString); $qry->execute(); $qry->setFetchMode($this->fetchMethod); $this->result = $qry->fetchAll(); $this->total = $qry->rowCount(); $this->queryDebug = ['string' => $queryString, 'affectedRows' => $this->total]; $this->handleres($queryString); return $this; } catch (\PDOException $ex) { $this->handleres($queryString, true, $ex); } return false; } /** * 条件构造 * @param array $whereData * @return string */ private function structureWhere($whereData = []) { if(empty($whereData)){ return ''; } $where = ' WHERE '; if (is_array($whereData)) { foreach ($whereData as $key => $value) { if (is_array($value) && count($value) > 1) { $value[1] = addslashes($value[1]); switch (strtolower($value[0])) { case 'in': $key = $this->inlon($key); $key = rtrim($key,'.,'); $where .= $key . ' IN(' . $value[1] . ') AND '; break; case 'string': $where .= $key . $value[1] . ' AND '; break; default: $value[1] = is_numeric($value[1]) ? $value[1] : "'" . $value[1] . "'"; $key = $this->inlon($key); $key = rtrim($key,'.,'); $where .= $key . ' ' . $value[0] . ' ' . $value[1] . ' AND '; break; } } else { $value = addslashes($value); $value = is_numeric($value) ? $value : "'" . $value . "'"; $key = $this->inlon($key); $key = rtrim($key,'.,'); $where .= $key . '=' . $value . ' AND '; } } return rtrim($where, '. AND '); } return $where . $whereData; } /** * 追加字段标识符 * @param $key * @return string */ private function inlon($key) { $val_arr = explode('.',$key); if(count($val_arr) > 1){ $str = ''; foreach ($val_arr as $values){ $str .= '`'.$values.'`.'; } if(!empty($str)){ $str = rtrim($str, '.'); } return $str . ','; }else{ return '`'.$key . '`,'; } } /** * 插入数据(别名) * @param array $dataArray * @return bool */ public function add($dataArray = []) { return $this->insert($dataArray); } /** * 插入数据 * @param array $dataArray * @return bool|mixed */ public function insert($dataArray = []) { if (is_array($dataArray) && count($dataArray) > 0) { $v_key = ''; $v_value = ''; foreach ($dataArray as $key => $value) { $v_key .= '`' . $key . '`,'; $v_value .= is_int($value) ? $value . ',' : "'{$value}',"; } $v_key = rtrim($v_key, '.,'); $v_value = rtrim($v_value, '.,'); $queryString = 'INSERT INTO ' . $this->tableName . ' (' . $v_key . ') VALUES(' . $v_value . ');'; try { $this->pdo->exec($queryString); $lastInsertedId = $this->pdo->lastInsertId(); $this->queryDebug = ['string' => $queryString, 'value' => $value, 'insertedid' => $lastInsertedId]; $this->handleres($queryString); return $lastInsertedId; } catch (\PDOException $ex) { $this->handleres($queryString, true, $ex); } } return false; } /** * 修改数据(别名) * @param array $dataArray * @param string $where * @return bool */ public function save($dataArray = [], $where = '') { return $this->update($dataArray, $where); } /** * 修改数据 * @param array $dataArray * @param array $where * @return bool */ public function update($dataArray = [], $where = []) { if (is_array($dataArray) && count($dataArray) > 0) { $updata = ''; foreach ($dataArray as $key => $value) { $value = is_int($value) ? $value : "'{$value}'"; $updata .= "`$key`={$value},"; } if (!empty($where)) $where = $this->structureWhere($where); $queryString = 'UPDATE ' . $this->tableName . ' SET ' . rtrim($updata, '.,') . $where; try { $this->total = $this->pdo->exec($queryString); $this->queryDebug = ['string' => $queryString, 'update' => $updata, 'affectedRows' => $this->total]; $this->handleres($queryString); return $this->total; } catch (\PDOException $ex) { $this->handleres($queryString, true, $ex); } } return false; } /** * 删除数据(别名) * @param array $where * @return bool */ public function del($where = []) { return $this->delete($where); } /** * 删除数据 * @param array|string $where * @return bool|int */ public function delete($where = []) { if (!empty($where)) $where = $this->structureWhere($where); $queryString = 'DELETE FROM ' . $this->tableName . $where; try { $this->total = $this->pdo->exec($queryString); $this->queryDebug = ['string' => $queryString, 'affectedRows' => $this->total]; $this->handleres($queryString); return $this->total; } catch (\PDOException $ex) { $this->handleres($queryString, true, $ex); } return false; } /** * 获取数据表主键 * @return string */ public function getkey() { return $this->key; } /** * 获取所有字段信息 * @return array */ public function getField() { return $this->data; } /** * 获取所有数据表 * @return array|bool|null */ public function getTables() { $queryString = "select table_name from information_schema.tables where table_schema='" . $this->database . "' and table_type='base table';"; $qry = $this->pdo->prepare($queryString); $qry->execute(); $qry->setFetchMode(\PDO::FETCH_ASSOC); $list = $qry->fetchAll(); if (is_array($list)) { $_list = []; foreach ($list as $key => $value) { $_list[] = $list[$key]['table_name']; } return $_list; } return $list; } }
php
Apache-2.0
2ba403cd277680a050c457d39db2aef652fb8e8f
2026-01-05T04:52:44.635355Z
false
xcg340122/PHP300Framework2x
https://github.com/xcg340122/PHP300Framework2x/blob/2ba403cd277680a050c457d39db2aef652fb8e8f/Framework/Library/Process/Drive/Db/Mysqli.php
Framework/Library/Process/Drive/Db/Mysqli.php
<?php namespace Framework\Library\Process\Drive\Db; use Framework\App; use Framework\Library\Interfaces\DbInterface as DbInterfaces; use Framework\Library\Process\Running; use Framework\Library\Process\Tool; /** * Mysqli Driver * Class Mysqli */ class Mysqli implements DbInterfaces { /** * @var string 操作表 */ public $tableName = ''; /** * @var null|\mysqli 连接资源 */ public $link = null; /** * @var int 对象ID */ public $queryId; /** * @var bool|\mysqli_result|array 结果集 */ protected $result = false; /** * @var bool 调试信息 */ protected $queryDebug = false; /** * @var int 影响条数 */ protected $total; /** * @var string 数据主键 */ protected $key = ''; /** * @var bool 是否缓存数据 */ protected $iscache = false; /** * @var array 数据表信息 */ protected $data = []; /** * @var string 数据库名 */ protected $database = ''; /** * @var string 表前缀 */ protected $tabPrefix = ''; /** * 获取错误信息 * @return string|null */ public function getError() { if (is_resource($this->link)) { return mysqli_error($this->link); } return 'Invalid resources'; } /** * 连接数据库 * @param array $config * @return bool|mixed|\mysqli|null */ public function connect($config = []) { $this->link = @mysqli_connect($config['host'], $config['username'], $config['password'], $config['database'], $config['port']); if ($this->link != null) { $this->database = $config['database']; mysqli_query($this->link, 'set names ' . $config['char']); if (!empty($config['tabprefix'])) { $this->tabPrefix = $config['tabprefix']; } return $this->link; } else { App::$app->get('LogicExceptions')->readErrorFile([ 'file' => __FILE__, 'message' => 'Mysql Host[ ' . $config['host'] . ' ] :: ' . Tool::toUTF8(mysqli_connect_error()) ]); } return false; } /** * 操作多数据库连接 * @param $link * @return $this */ public function setlink($link) { $this->link = $link; return $this; } /** * 关闭数据库 */ public function disconnect() { mysqli_close($this->link); } /** * 获取所有记录 * @return bool */ public function get() { return $this->result; } /** * 获取默认记录 * @return null|array */ public function find() { if ($this->result) { return count($this->result) > 0 ? $this->result[0] : NULL; } return NULL; } /** * debug * @return bool|mixed */ public function debug() { return $this->queryDebug; } /** * 获取影响条数 * @return mixed */ public function total() { return $this->total; } /** * 设定查询表 * @param string $tabName * @return $this|bool|mixed */ public function table($tabName = '') { if (!empty($tabName)) { $this->tableName = '`' . $this->tabPrefix . $tabName . '`'; $this->getTableInfo(); return $this; } else { App::$app->get('LogicExceptions')->readErrorFile([ 'file' => __FILE__, 'message' => 'Need to fill in Table Value!', ]); } return false; } /** * 返回数据表信息 * @return bool|\mysqli_result */ protected function getTableInfo() { if ($this->tableName == '') { App::$app->get('LogicExceptions')->readErrorFile([ 'message' => '尚未设定操作的数据表名称' ]); } else { $string = str_replace('`', '', "SELECT COLUMN_NAME,DATA_TYPE,COLUMN_DEFAULT,COLUMN_KEY,COLUMN_COMMENT FROM information_schema.COLUMNS WHERE table_name = '" . $this->tableName . "';"); $info = mysqli_query($this->link, $string); if ($info !== false) { $this->data = mysqli_fetch_all($info, MYSQLI_ASSOC); foreach ($this->data as $key => $value) { if ($this->data[$key]['COLUMN_KEY'] == 'PRI') { $this->key = $this->data[$key]['COLUMN_NAME']; break; } return $info; } return false; } } return false; } /** * 插入数据 * @param array $qryArray * @return $this */ public function select($qryArray = []) { $field = ''; $join = ''; $where = ''; $order = ''; $group = ''; $limit = ''; if (isset($qryArray['field'])) { if (is_array($qryArray['field'])) { if (isset($qryArray['field']['NOT'])) { if (is_array($qryArray['field']['NOT'])) { $field_arr = $this->getField(); if (is_array($field_arr)) { foreach ($field_arr as $key => $value) { if (!in_array($value['COLUMN_NAME'], $qryArray['field']['NOT'])) { $field .= '`' . $value['COLUMN_NAME'] . '`,'; } } $field = rtrim($field, '.,'); } } } else { foreach ($qryArray['field'] as $key => $value) { $field .= $this->inlon($value); } $field = rtrim($field, '.,'); } } else { $field = $qryArray['field']; } } if (empty($field)) $field = ' * '; if (isset($qryArray['join'])) { $join = is_array($qryArray['join']) ? ' ' . implode(' ', $qryArray['join']) : ' ' . $qryArray['join']; } if (isset($qryArray['where'])) { $where = $this->structureWhere($qryArray['where']); } if (isset($qryArray['orderby'])) { $order = is_array($qryArray['orderby']) ? implode(',', $qryArray['orderby']) : $qryArray['orderby']; $order = ' ORDER BY ' . $order; } if (isset($qryArray['groupby'])) { $group = is_array($qryArray['groupby']) ? implode(',', $qryArray['groupby']) : $qryArray['groupby']; $group = ' GROUP BY ' . $group; } if (isset($qryArray['limit'])) { $limit = is_array($qryArray['limit']) ? implode(',', $qryArray['limit']) : $qryArray['limit']; $limit = ' LIMIT ' . $limit; } if (isset($qryArray['page'])) { $page = 1; $limit = 10; if (is_numeric($qryArray['page'])) { $page = $qryArray['page']; } if (is_array($qryArray['page'])) { if (isset($qryArray['page'][0]) && isset($qryArray['page'][1])) { $page = is_numeric($qryArray['page'][0]) ? $qryArray['page'][0] : 1; $limit = is_numeric($qryArray['page'][1]) ? $qryArray['page'][1] : 10; } } $start = ($page - 1) * $limit; $limit = ' LIMIT ' . $start . ',' . $limit; } $queryString = 'SELECT ' . $field . ' FROM ' . $this->tableName . $join . $where . $group . $order . $limit; $res = $this->query($queryString, true); if ($res) { $this->result = mysqli_fetch_all($res, MYSQLI_ASSOC); } $this->total = $this->affectedRows(); $this->queryDebug = ['string' => $queryString, 'affectedRows' => $this->total]; return $this; } /** * 条件构造 * @param array $whereData * @return string */ private function structureWhere($whereData = []) { if (empty($whereData)) { return ''; } $where = ' WHERE '; if (is_array($whereData)) { foreach ($whereData as $key => $value) { if (is_array($value) && count($value) > 1) { $value[1] = mysqli_real_escape_string($this->link, $value[1]); switch (strtolower($value[0])) { case 'in': $key = $this->inlon($key); $key = rtrim($key, '.,'); $where .= $key . ' IN(' . $value[1] . ') AND '; break; case 'string': $where .= $key . $value[1] . ' AND '; break; default: $value[1] = is_numeric($value[1]) ? $value[1] : "'" . $value[1] . "'"; $key = $this->inlon($key); $key = rtrim($key, '.,'); $where .= $key . ' ' . $value[0] . ' ' . $value[1] . ' AND '; break; } } else { $value = mysqli_real_escape_string($this->link, $value); $value = is_numeric($value) ? $value : "'" . $value . "'"; $key = $this->inlon($key); $key = rtrim($key, '.,'); $where .= $key . '=' . $value . ' AND '; } } return rtrim($where, '. AND '); } return $where . $whereData; } /** * 追加字段标识符 * @param $key * @return string */ private function inlon($key) { $val_arr = explode('.', $key); if (count($val_arr) > 1) { $str = ''; foreach ($val_arr as $values) { $str .= '`' . $values . '`.'; } if(!empty($str)){ $str = rtrim($str, '.'); } return $str . ','; } else { return '`' . $key . '`,'; } } /** * 执行SQL * @param string $queryString * @param bool $select * @return $this|bool|\mysqli_result */ public function query($queryString = '', $select = false) { if ($this->link != null) { $this->queryId = mysqli_query($this->link, $queryString); $errorMsg = ''; if ($this->queryId === false) { $status = 'error'; $errorMsg = mysqli_error($this->link); } else { $status = 'success'; } $Logs = "[{$status}] " . $queryString; if (!empty($errorMsg)) { $Logs .= "\r\n[message] " . $errorMsg; } App::$app->get('Log')->Record(Running::$framworkPath . '/Project/runtime/datebase', 'sql', $Logs); if ($this->queryId === false) { $message = $errorMsg . ' (SQL:' . $queryString . ')'; App::$app->get('LogicExceptions')->readErrorFile([ 'type' => 'DataBase Error', 'message' => $message ]); } if ($this->startsWith(strtolower($queryString), "select") && $select === false) { $this->result = mysqli_fetch_all($this->queryId, MYSQLI_ASSOC); return $this; } return $this->queryId; } else { App::$app->get('LogicExceptions')->readErrorFile([ 'message' => '数据库连接失败或尚未连接' ]); } return false; } /** * If string starts with * * @param $haystack * @param $needle * @return bool */ protected function startsWith($haystack, $needle) { return $needle === "" || strrpos($haystack, $needle, -strlen($haystack)) !== FALSE; } /** * 返回影响记录 * @return int */ public function affectedRows() { return mysqli_affected_rows($this->link); } /** * 插入数据(别名) * @param array $dataArray * @return bool */ public function add($dataArray = []) { return $this->insert($dataArray); } /** * 插入数据 * @param array $dataArray * @return bool */ public function insert($dataArray = []) { $value = ''; if (is_array($dataArray) && count($dataArray) > 0) { $v_key = ''; $v_value = ''; foreach ($dataArray as $key => $value) { $v_key .= '`' . $key . '`,'; $v_value .= is_int($value) ? $value . ',' : "'{$value}',"; } $v_key = rtrim($v_key, '.,'); $v_value = rtrim($v_value, '.,'); $queryString = 'INSERT INTO ' . $this->tableName . ' (' . $v_key . ') VALUES(' . $v_value . ');'; $res = $this->query($queryString, true); $this->queryDebug = ['string' => $queryString, 'value' => $value, 'insertedId' => $this->insert_id()]; return $res === false ? false : $this->queryDebug['insertedId']; } return false; } /** * 获取最后插入的ID * @return int|string */ public function insert_id() { return mysqli_insert_id($this->link); } /** * 修改数据(别名) * @param array $dataArray * @param string $where * @return bool */ public function save($dataArray = [], $where = '') { return $this->update($dataArray, $where); } /** * 修改数据 * @param array $dataArray * @param string $where * @return bool|int */ public function update($dataArray = [], $where = '') { if (is_array($dataArray) && count($dataArray) > 0) { $updata = ''; foreach ($dataArray as $key => $value) { $value = is_int($value) ? $value : "'{$value}'"; $updata .= "`$key`={$value},"; } if (!empty($where)) $where = $this->structureWhere($where); $queryString = 'UPDATE ' . $this->tableName . ' SET ' . rtrim($updata, '.,') . $where; $res = $this->query($queryString, true); $this->total = $this->affectedRows(); $this->queryDebug = ['string' => $queryString, 'update' => $updata, 'affectedRows' => $this->total]; return $res === false ? false : $this->total; } return false; } /** * 删除数据(别名) * @param array $where * @return bool */ public function del($where = []) { return $this->delete($where); } /** * 删除数据 * @param array $where * @return bool|int|mixed */ public function delete($where = []) { if (!empty($where)) $where = $this->structureWhere($where); $queryString = 'DELETE FROM ' . $this->tableName . $where; $res = $this->query($queryString, true); $this->total = $this->affectedRows(); $this->queryDebug = ['string' => $queryString, 'affectedRows' => $this->total]; return $res === false ? false : $this->total; } /** * 获取数据表主键 * @return string */ public function getkey() { return $this->key; } /** * 获取所有字段信息 * @return array */ public function getField() { return $this->data; } /** * 获取所有数据表 * @return array|bool|null */ public function getTables() { $res = mysqli_query($this->link, "SELECT table_name FROM information_schema.tables WHERE table_schema='" . $this->database . "' AND table_type='base table';"); if ($res !== false) { $list = mysqli_fetch_all($res, MYSQLI_ASSOC); if (is_array($list)) { $_list = []; foreach ($list as $key => $value) { $_list[] = $list[$key]['table_name']; } return $_list; } return $list; } return false; } }
php
Apache-2.0
2ba403cd277680a050c457d39db2aef652fb8e8f
2026-01-05T04:52:44.635355Z
false
xcg340122/PHP300Framework2x
https://github.com/xcg340122/PHP300Framework2x/blob/2ba403cd277680a050c457d39db2aef652fb8e8f/Framework/Library/Process/Drive/Cache/Redis.php
Framework/Library/Process/Drive/Cache/Redis.php
<?php namespace Framework\Library\Process\Drive\Cache; use \Framework\Library\Interfaces\CacheInterface as CacheInterfaces; /** * Class Redis * @package Framework\Library\Process\Drive\Cache */ class Redis implements CacheInterfaces { /** * 建立连接 * @var null */ protected $link = null; /** * 实例对象 * @var */ private $obj; /** * 构造方法 * Memcache constructor. */ public function __construct() { $this->obj = new \Redis(); } /** * 连接缓存服务器 * @param string $ip 服务器IP * @param int|string $port 服务器端口 * @param array $auth 授权信息 * @return mixed|void */ public function connect($ip, $port, $auth = []) { $this->obj->connect($ip, $port); if (!empty($auth['password'])) { $this->obj->auth($auth['password']); } } /** * 获取一个缓存标识 * @param $key * @return mixed */ public function get($key) { if (!empty($key)) { return $this->obj->get($key); } return false; } /** * 设定一个缓存标识 * @param $key * @param $value * @param bool $iszip * @param int $expire * @return bool|mixed */ public function set($key, $value, $iszip = false, $expire = 3600) { return $this->obj->set($key, $value, $expire); } /** * 删除一个标识 * @param $key * @param int $timeout * @return bool|int|mixed */ public function delete($key, $timeout = 0) { if (!empty($key)) { return $this->obj->delete($key); } return false; } /** * 替换标识 * @param $key * @param $value * @param bool $iszip * @param int $expire * @return mixed|string */ public function replace($key, $value, $iszip = false, $expire = 3600) { return $this->obj->getSet($key, $value); } /** * 检测key是否存在 * @param $key * @return bool */ public function exists($key) { return $this->obj->exists($key); } /** * 重置所有标识 */ public function flush() { return $this->obj->flushAll(); } /** * 减少标识的值 * @param $key * @param int $number * @return mixed */ public function decrement($key, $number = 1) { return $this->obj->decrBy($key, $number); } /** * 增加标识的值 * @param $key * @param int $number * @return mixed */ public function increment($key, $number = 1) { return $this->obj->incrBy($key, $number); } /** * 获得版本号 * @return mixed */ public function getVersion() { $info = $this->getStats(); return $info['redis_version']; } /** * 获取服务器统计信息 * @return mixed */ public function getStats() { return $this->obj->info(); } /** * 关闭与缓存服务器的连接 */ public function close() { $this->obj->close(); } }
php
Apache-2.0
2ba403cd277680a050c457d39db2aef652fb8e8f
2026-01-05T04:52:44.635355Z
false
xcg340122/PHP300Framework2x
https://github.com/xcg340122/PHP300Framework2x/blob/2ba403cd277680a050c457d39db2aef652fb8e8f/Framework/Library/Process/Drive/Cache/Memcache.php
Framework/Library/Process/Drive/Cache/Memcache.php
<?php namespace Framework\Library\Process\Drive\Cache; use \Framework\Library\Interfaces\CacheInterface as CacheInterfaces; /** * Class Memcache * @package Framework\Library\Process\Drive\Cache */ class Memcache implements CacheInterfaces { /** * 建立连接 * @var null */ protected $link = null; /** * 实例对象 * @var */ private $obj; /** * 构造方法 * Memcache constructor. */ public function __construct() { $this->obj = new \Memcache(); } /** * 连接缓存服务器 * @param string $ip 服务器IP * @param int|string $port 服务器端口 * @param array $auth 授权信息 * @return mixed|void */ public function connect($ip, $port, $auth = []) { $this->obj->connect($ip, $port); } /** * 获取一个缓存标识 * @param $key * @return mixed */ public function get($key) { if (!empty($key)) { return $this->obj->get($key); } return false; } /** * 设定一个缓存标识 * @param string $key 缓存key * @param string|array $value 缓存value * @param bool $iszip 是否压缩 * @param int $expire 缓存周期 * @return bool|mixed */ public function set($key, $value, $iszip = false, $expire = 3600) { return $this->obj->add($key, $value, $iszip, $expire); } /** * 删除一个标识 * @param string $key 缓存key * @param int $timeout * @return bool|mixed */ public function delete($key, $timeout = 0) { if (!empty($key)) { return $this->obj->delete($key, $timeout); } return false; } /** * 替换标识 * @param $key * @param $value * @param bool $iszip * @param int $expire * @return bool|mixed */ public function replace($key, $value, $iszip = false, $expire = 3600) { return $this->obj->replace($key, $value, $iszip, $expire); } /** * 检测key是否存在 * @param $key * @return bool */ public function exists($key) { $data = $this->get($key); return $data !== false; } /** * 重置所有标识 */ public function flush() { return $this->obj->flush(); } /** * 减少标识的值 * @param $key * @param int $number * @return mixed */ public function decrement($key, $number = 1) { return $this->obj->decrement($key, $number); } /** * 增加标识的值 * @param $key * @param int $number * @return mixed */ public function increment($key, $number = 1) { return $this->obj->increment($key, $number); } /** * 获得版本号 * @return mixed */ public function getVersion() { return $this->obj->getVersion(); } /** * 获取服务器统计信息 * @return mixed */ public function getStats() { return $this->obj->getStats(); } /** * 关闭与缓存服务器的连接 */ public function close() { $this->obj->close(); } }
php
Apache-2.0
2ba403cd277680a050c457d39db2aef652fb8e8f
2026-01-05T04:52:44.635355Z
false
xcg340122/PHP300Framework2x
https://github.com/xcg340122/PHP300Framework2x/blob/2ba403cd277680a050c457d39db2aef652fb8e8f/Framework/Library/Process/Drive/Cache/File.php
Framework/Library/Process/Drive/Cache/File.php
<?php namespace Framework\Library\Process\Drive\Cache; use Framework\Library\Process\Running; /** * 文件缓存类 * Class File * @package Framework\Library\Process\Drive\Cache */ class File { /** * 缓存目录 * @var string */ private $cache_dir = ''; /** * 构造方法 * File constructor. * @param array $options */ public function __construct(array $options = array()) { $this->cache_dir = Running::$framworkPath.'/Project/runtime/tmp'; $available_options = array('cache_dir'); foreach ($available_options as $name) { if (isset($options[$name])) { $this->$name = $options[$name]; } } } /** * 获取缓存 * @param $id * @return bool|mixed */ public function get($id) { $file_name = $this->getFileName($id); if (!is_file($file_name) || !is_readable($file_name)) { return false; } $lines = file($file_name); $lifetime = array_shift($lines); $lifetime = (int)trim($lifetime); if ($lifetime !== 0 && $lifetime < time()) { @unlink($file_name); return false; } $serialized = join('', $lines); $data = unserialize($serialized); return $data; } /** * 获取文件名称 * @param $id * @return string */ protected function getFileName($id) { $directory = $this->getDirectory($id); $hash = sha1($id, false); $file = $directory . DIRECTORY_SEPARATOR . $hash . '.cache'; return $file; } /** * 获取目录 * @param $id * @return string */ protected function getDirectory($id) { $hash = sha1($id, false); $dirs = array( $this->getCacheDirectory(), substr($hash, 0, 2), substr($hash, 2, 2) ); return join(DIRECTORY_SEPARATOR, $dirs); } /** * 获取缓存目录 * @return string */ protected function getCacheDirectory() { return $this->cache_dir; } /** * 删除缓存 * @param $id * @return bool */ public function delete($id) { $file_name = $this->getFileName($id); if(is_file($file_name)){ return unlink($file_name); } return false; } /** * 保存缓存 * @param $id * @param $data * @param int $lifetime * @return bool */ public function set($id, $data, $lifetime = 3600) { $dir = $this->getDirectory($id); if (!is_dir($dir)) { if (!mkdir($dir, 0755, true)) { return false; } } $file_name = $this->getFileName($id); $lifetime = time() + $lifetime; $serialized = serialize($data); $result = file_put_contents($file_name, $lifetime . PHP_EOL . $serialized); if ($result === false) { return false; } return true; } }
php
Apache-2.0
2ba403cd277680a050c457d39db2aef652fb8e8f
2026-01-05T04:52:44.635355Z
false
xcg340122/PHP300Framework2x
https://github.com/xcg340122/PHP300Framework2x/blob/2ba403cd277680a050c457d39db2aef652fb8e8f/Framework/Library/Interfaces/LogInterface.php
Framework/Library/Interfaces/LogInterface.php
<?php namespace Framework\Library\Interfaces; /** * 日志接口 * Interface LogInterface * @package Framework\Library\Interfaces */ interface LogInterface { /** * 写出日志 * @param string $LogPath 日志文件路径 * @param string $fileName 日志文件名 * @param string $Log 日志内容 * @return mixed */ public function Record($LogPath, $fileName, $Log); }
php
Apache-2.0
2ba403cd277680a050c457d39db2aef652fb8e8f
2026-01-05T04:52:44.635355Z
false
xcg340122/PHP300Framework2x
https://github.com/xcg340122/PHP300Framework2x/blob/2ba403cd277680a050c457d39db2aef652fb8e8f/Framework/Library/Interfaces/RouterInterface.php
Framework/Library/Interfaces/RouterInterface.php
<?php namespace Framework\Library\Interfaces; /** * 路由接口 * Interface RouterInterface * @package Framework\Library\Interfaces */ interface RouterInterface { /** * 路由方法 * @return mixed */ public function Route(); }
php
Apache-2.0
2ba403cd277680a050c457d39db2aef652fb8e8f
2026-01-05T04:52:44.635355Z
false
xcg340122/PHP300Framework2x
https://github.com/xcg340122/PHP300Framework2x/blob/2ba403cd277680a050c457d39db2aef652fb8e8f/Framework/Library/Interfaces/CacheInterface.php
Framework/Library/Interfaces/CacheInterface.php
<?php namespace Framework\Library\Interfaces; /** * 缓存接口 * Interface CacheInterface * @package Framework\Library\Interfaces */ interface CacheInterface { /** * 连接缓存服务器 * @param string $ip 服务器IP * @param string|int $port 服务器端口 * @param array $auth 授权信息 * @return mixed */ public function connect($ip, $port, $auth = []); /** * 获取一个缓存标识 * @param string $key 获取的键名称 * @return mixed|string|array */ public function get($key); /** * 设定一个缓存标识 * @param string $key 键名称 * @param string|array $value 设置的值内容 * @param bool $isZip 是否启用压缩 * @param int $expire 缓存的周期 * @return mixed|bool */ public function set($key, $value, $isZip = false, $expire = 3600); /** * 删除一个标识 * @param string $key 删除的键名称 * @param int $timeout 延迟删除(默认为0立即删除) * @return mixed|bool */ public function delete($key, $timeout = 0); /** * 替换标识 * @param string $key 替换的键名称 * @param string|array $value 替换的值内容 * @param bool $isZip 是否启用压缩 * @param int $expire 缓存的周期 * @return mixed|bool */ public function replace($key, $value, $isZip = false, $expire = 3600); /** * 检查值是否存在 * @param string $key 检查的键名称 * @return mixed|bool */ public function exists($key); /** * 重置所有标识 * @return mixed */ public function flush(); /** * 减少标识的值 * @param string $key 减少的键名称 * @param int $number * @return mixed */ public function decrement($key, $number = 1); /** * 增加标识的值 * @param string $key 增加的键名称 * @param int $number * @return mixed */ public function increment($key, $number = 1); /** * 获得版本号 * @return mixed|string */ public function getVersion(); /** * 获取服务器统计信息 * @return mixed */ public function getStats(); /** * 关闭与缓存服务器的连接 * @return mixed */ public function close(); }
php
Apache-2.0
2ba403cd277680a050c457d39db2aef652fb8e8f
2026-01-05T04:52:44.635355Z
false
xcg340122/PHP300Framework2x
https://github.com/xcg340122/PHP300Framework2x/blob/2ba403cd277680a050c457d39db2aef652fb8e8f/Framework/Library/Interfaces/ConfigInterface.php
Framework/Library/Interfaces/ConfigInterface.php
<?php namespace Framework\Library\Interfaces; /** * 配置处理接口 * Interface ConfigInterface * @package Framework\Library\Interfaces */ interface ConfigInterface { /** * 读取配置 * @param string $keys 获取的键名称 * @return mixed|string|array */ public function get($keys); /** * 设置数据 * @param string $key 设置的键名称 * @param string|array $val 设置的值内容 * @return mixed|string|array */ public function set($key, $val); }
php
Apache-2.0
2ba403cd277680a050c457d39db2aef652fb8e8f
2026-01-05T04:52:44.635355Z
false
xcg340122/PHP300Framework2x
https://github.com/xcg340122/PHP300Framework2x/blob/2ba403cd277680a050c457d39db2aef652fb8e8f/Framework/Library/Interfaces/SessionInterface.php
Framework/Library/Interfaces/SessionInterface.php
<?php namespace Framework\Library\Interfaces; /** * Session接口 * Interface SessionInterface * @package Framework\Library\Interfaces */ interface SessionInterface { /** * 启动session * @return mixed */ public function start(); /** * 获取session * @param string $name 获取的键名称 * @return mixed|string|array */ public function get($name=''); /** * 设置session * @param string $name 设置的键名称 * @param string|array $value 设置的值 * @return mixed */ public function set($name='php300',$value=''); /** * 删除session * @param string $name 删除的键名称 * @return mixed */ public function del($name=''); }
php
Apache-2.0
2ba403cd277680a050c457d39db2aef652fb8e8f
2026-01-05T04:52:44.635355Z
false
xcg340122/PHP300Framework2x
https://github.com/xcg340122/PHP300Framework2x/blob/2ba403cd277680a050c457d39db2aef652fb8e8f/Framework/Library/Interfaces/VisitInterface.php
Framework/Library/Interfaces/VisitInterface.php
<?php namespace Framework\Library\Interfaces; /** * 访问处理接口 * Interface VisitInterface * @package Framework\Library\Interfaces */ interface VisitInterface { /** * 绑定数默认实例 * @param array $param 配置数组 * @return mixed */ public function bind($param); }
php
Apache-2.0
2ba403cd277680a050c457d39db2aef652fb8e8f
2026-01-05T04:52:44.635355Z
false
xcg340122/PHP300Framework2x
https://github.com/xcg340122/PHP300Framework2x/blob/2ba403cd277680a050c457d39db2aef652fb8e8f/Framework/Library/Interfaces/DbInterface.php
Framework/Library/Interfaces/DbInterface.php
<?php namespace Framework\Library\Interfaces; use Framework\Library\Process\Db; /** * 数据基础模型接口 * Interface DbInterface * @package Framework\Library\Interfaces */ interface DbInterface { /** * 获取错误信息 * @return mixed */ public function getError(); /** * 连接数据库 * @param array $config 配置信息 * @return mixed */ public function connect($config = []); /** * 执行SQL * @param string $queryString 执行的SQL语句 * @param bool $select 是否系统查询 * @return mixed|self */ public function query($queryString, $select = false); /** * 设置表 * @param string $tabName 表名称 * @return self */ public function table($tabName); /** * 查询数据 * @param array $qryArray 条件信息 * @return self */ public function select($qryArray = []); /** * 新增数据 * @param array $dataArray 插入的数据 * @return bool|int */ public function insert($dataArray = []); /** * 新增数据 * @param array $dataArray 插入的数据 * @return bool|int */ public function add($dataArray = []); /** * 修改数据 * @param array $dataArray 修改的数据 * @param array|string $where 修改条件 * @return mixed|bool|int */ public function update($dataArray = [], $where = []); /** * 修改数据 * @param array $dataArray 修改的数据 * @param array|string $where 修改条件 * @return mixed|int */ public function save($dataArray = [], $where = []); /** * 删除数据 * @param array|string $where 删除的条件 * @return bool */ public function delete($where = []); /** * 删除数据 * @param array|string $where 删除的条件 * @return bool */ public function del($where = []); /** * 打印调试信息 * @return mixed|array */ public function debug(); /** * 获取单条记录 * @return mixed|array */ public function find(); /** * 获取多条记录 * @return mixed|array */ public function get(); /** * 获取影响的条数 * @return int */ public function total(); }
php
Apache-2.0
2ba403cd277680a050c457d39db2aef652fb8e8f
2026-01-05T04:52:44.635355Z
false
xcg340122/PHP300Framework2x
https://github.com/xcg340122/PHP300Framework2x/blob/2ba403cd277680a050c457d39db2aef652fb8e8f/Framework/Library/Interfaces/ViewInterface.php
Framework/Library/Interfaces/ViewInterface.php
<?php namespace Framework\Library\Interfaces; /** * 视图接口 * Interface ViewInterface * @package Framework\Library\Interfaces */ interface ViewInterface { /** * 初始化视图 * @return mixed */ public function init(); /** * 设定操作文件 * @param string $fileName 文件名称 * @return mixed */ public function set($fileName); /** * 获取渲染内容 * @return mixed|string */ public function get(); /** * 获取视图原型 * @return mixed|object */ public function getView(); /** * 赋值变量 * @param null|array $data 设置的变量数组 * @return mixed|self */ public function data($data = null); }
php
Apache-2.0
2ba403cd277680a050c457d39db2aef652fb8e8f
2026-01-05T04:52:44.635355Z
false
xcg340122/PHP300Framework2x
https://github.com/xcg340122/PHP300Framework2x/blob/2ba403cd277680a050c457d39db2aef652fb8e8f/Framework/Library/Interfaces/LogicExceptionsInterface.php
Framework/Library/Interfaces/LogicExceptionsInterface.php
<?php namespace Framework\Library\Interfaces; /** * 异常处理接口 * Interface LogicExceptionsInterface * @package Framework\Library\Interfaces */ interface LogicExceptionsInterface { /** * 挂载异常钩子 */ public function Mount(); }
php
Apache-2.0
2ba403cd277680a050c457d39db2aef652fb8e8f
2026-01-05T04:52:44.635355Z
false
xcg340122/PHP300Framework2x
https://github.com/xcg340122/PHP300Framework2x/blob/2ba403cd277680a050c457d39db2aef652fb8e8f/Framework/Library/Common/helper.php
Framework/Library/Common/helper.php
<?php /** * 自定义dump * @param string $vars 打印的变量 * @param string $label 追加标签 * @param bool $return 是否直接返回 * @return null|string */ function dump($vars, $label = '', $return = false) { if (ini_get('html_errors')) { $content = "<pre>\n"; if (!empty($label)) { $content .= "<strong>{$label} :</strong>\n"; } $content .= htmlspecialchars(print_r($vars, true)); $content .= "\n</pre>\n"; } else { $content = $label . " :\n" . print_r($vars, true); } if ($return) { return $content; } echo $content; return null; } /** * 数据模型操作 * @param string $table 操作的表名 * @param null|array $config 操作的配置对象 * @return \Framework\Library\Interfaces\DbInterface|bool|null */ function Db($table = '', $config = null) { /** * @var \Framework\Library\Process\Db|\Framework\Library\Process\Drive\Db\Mysqli $link */ $Db = \Framework\App::$app->get('Db')->getlink(); if (is_array($Db) && count($Db) > 0) { if (is_null($config)) { $link = current($Db); $link = $link['obj']->setlink($link['link']); } if (!empty($Db[$config])){ $link = $Db[$config]['obj']->setlink($Db[$config]['link']); } if (isset($link)) { if (empty($table)) return $link; return $link->table($table); } return false; } else { \Framework\App::$app->get('LogicExceptions')->readErrorFile([ 'message' => "您操作了数据库,但是没有发现有效的数据库配置!" ]); return null; } } /** * 读取配置信息 * @param string $configName 配置名称 * @return \Framework\Library\Interfaces\ConfigInterface|bool */ function Config($configName) { if (empty($configName)) return false; return \Framework\App::$app->get('Config')->get($configName); } /** * 缓存模型操作 * @return \Framework\Library\Interfaces\CacheInterface|bool */ function Cache() { $Cache = \Framework\App::$app->get('Cache'); return $Cache->init()->getObj(); } /** * 渲染视图信息 * @param string $fileName 模板文件名 * @param string $dir 其他模板文件 * @return \Framework\Library\Interfaces\ViewInterface|bool */ function View($fileName = '', $dir = '') { /** * @var \Framework\Library\Process\View $Object */ $Object = \Framework\App::$app->get('View')->init(); if (empty($fileName) && empty($dir)) return $Object; if (empty($dir) && !empty($fileName)) { $ViewPath = \Framework\Library\Process\Running::$framworkPath . 'Project/view'; $fileName = $ViewPath . '/' . $fileName . '.html'; } else { $fileName = $dir; } if (!file_exists($fileName)) { $fileName = str_replace('\\', '/', $fileName); \Framework\App::$app->get('LogicExceptions')->readErrorFile([ 'file' => __FILE__, 'message' => "[$fileName] 请检查您的模板是否存在!", ]); } $Object->set($fileName); return $Object; } /** * 获取GET值 * @param $value * @param string $null * @return string|int|null */ function get($value, $null = '') { return \Framework\Library\Process\Tool::Receive('get.' . $value, $null); } /** * 获取POST值 * @param $value * @param string $null * @return string|int|null */ function post($value, $null = '') { return \Framework\Library\Process\Tool::Receive('post.' . $value, $null); } /** * 动态载入扩展 * @param string $name 扩展文件名称(可传递数组) * @param int $type 是否为包(0=扩展文件,1=扩展包) * @return bool */ function extend($name, $type = 0) { $Extend = \Framework\App::$app->get('Extend'); if (!empty($name) && is_array($name)) { foreach ($name as $value) { if ($type == 1) { $Extend->addPackage($value); } else { $Extend->addClass($value); } } return true; } if ($type == 1) { return $Extend->addPackage($name); } return $Extend->addClass($name); } /** * 获取系统应用实例对象 * @return \Framework\App|Object */ function getApp() { return \Framework\App::$app; } /** * 展示成功状态页 * @param string $msg 提示内容 * @param string $url 跳转的地址 * @param int $seconds 跳转的秒数 * @param string $title 提示页标题 */ function Success($msg = '操作成功', $url = '', $seconds = 3, $title = '系统提示') { \Framework\App::$app->get('LogicExceptions')->displayed('success', [ 'title' => $title, 'second' => $seconds, 'url' => $url, 'message' => $title, 'describe' => $msg ]); } /** * 展示成功状态页 * @param string $msg 提示内容 * @param string $url 跳转的地址 * @param int $seconds 跳转的秒数 * @param string $title 提示页标题 */ function Error($msg = '操作异常', $url = '', $seconds = 3, $title = '系统提示') { \Framework\App::$app->get('LogicExceptions')->displayed('error', [ 'title' => $title, 'second' => $seconds, 'url' => $url, 'message' => $title, 'describe' => $msg ]); } /** * Session操作 * @return \Framework\Library\Interfaces\SessionInterface */ function Session() { $Session = \Framework\App::$app->get('Session'); $Session->start(); return $Session; } /** * 操作cookie * @param string $name key名称 * @param string $val value值 * @param string $expire 过期时间 * @return bool|null|string */ function Cookie($name = '', $val = '', $expire = '0') { $prefix = 'PHP300_'; if ($name === '') { return $_COOKIE; } if ($name != '' && $val === '') { return (!empty($_COOKIE[$prefix . $name])) ? ($_COOKIE[$prefix . $name]) : (NULL); } if ($name && $val) { return setcookie($prefix . $name, $val, $expire); } if ($name && is_null($val)) { return setcookie($prefix . $name, $val, time() - 1); } if (is_null($name) && is_null($val)) { $_COOKIE = NULL; } return false; } /** * 操作日志 * @param string $logs 日志内容 * @param string $name 日志文件名称 * @param string $path 日志文件文件夹 * @return bool */ function logs($logs = '', $name = 'logs', $path = 'MyLog') { if (!empty($logs)) { return \Framework\App::$app->get('Log')->Record($path, $name, $logs); } return false; }
php
Apache-2.0
2ba403cd277680a050c457d39db2aef652fb8e8f
2026-01-05T04:52:44.635355Z
false
Froiden/laravel-rest-api
https://github.com/Froiden/laravel-rest-api/blob/45e05076f8fc7918d70631369b02ed7168a6cb5d/src/ApiResponse.php
src/ApiResponse.php
<?php namespace Froiden\RestAPI; use Froiden\RestAPI\Exceptions\ApiException; class ApiResponse { /** * Response message * * @var string */ private $message = null; /** * Data to send in response * * @var array */ private $data = null; /** * Get response message * * @return string */ public function getMessage() { return $this->message; } /** * Set response message * * @param string $message */ public function setMessage($message) { $this->message = $message; } /** * Get response data * * @return array */ public function getData() { return $this->data; } /** * Set response data * * @param array $data */ public function setData($data) { $this->data = $data; } /** * Make new success response * @param string $message * @param array $data * @return \Response */ public static function make($message = null, $data = null, $meta = null) { $response = []; if (!empty($message)) { $response["message"] = $message; } if ($data !== null && is_array($data)){ $response["data"] = $data; } if ($meta !== null && is_array($meta)){ $response["meta"] = $meta; } $returnResponse = \Response::make($response); return $returnResponse; } /** * Handle api exception an return proper error response * @param ApiException $exception * @return \Illuminate\Http\Response * @throws ApiException */ public static function exception(ApiException $exception) { $returnResponse = \Response::make($exception->jsonSerialize()); $returnResponse->setStatusCode($exception->getStatusCode()); return $returnResponse; } }
php
MIT
45e05076f8fc7918d70631369b02ed7168a6cb5d
2026-01-05T04:52:55.517023Z
false
Froiden/laravel-rest-api
https://github.com/Froiden/laravel-rest-api/blob/45e05076f8fc7918d70631369b02ed7168a6cb5d/src/ApiModel.php
src/ApiModel.php
<?php namespace Froiden\RestAPI; use Carbon\Carbon; use Closure; use DateTimeInterface; use Froiden\RestAPI\Exceptions\RelatedResourceNotFoundException; use Froiden\RestAPI\Exceptions\ResourceNotFoundException; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Relations\BelongsTo; use Illuminate\Database\Eloquent\Relations\BelongsToMany; use Illuminate\Database\Eloquent\Relations\HasMany; use Illuminate\Database\Eloquent\Relations\HasOne; use Illuminate\Database\Eloquent\Relations\Relation; use Illuminate\Support\Str; class ApiModel extends Model { /** * List of fields that are visible by default. Only these fields * are selected and returned from database * * @var array */ protected $default = ["id"]; /** * List of fields that are always hidden. Unless modified, these * fields are not visible when object is serialised. To comply with * Rest architecture, its recommended to hide all relation fields * (like, user_id, student_id) * * @var array */ protected $hidden = ["created_at", "updated_at", "pivot"]; /** * List of fields on which filters are allowed to be applied. For security * reasons we cannot allow filters to be allowed on arbitrary fields * @var array */ protected $filterable = ["id"]; /** * List of relation attributes found during parsing of request, to be used during saving action * @var array */ protected $relationAttributes = []; protected $guarded = []; /** * Raw attributes as sent in request. To be used in setters of various attributes * @var array */ protected $raw = []; //region Metadata functions /** * Name of table of this model * * @return string */ public static function getTableName() { return (new static)->table; } /** * Date fields in this model * * @return array */ public static function getDateFields() { return (new static)->dates; } /** * List of custom fields (attributes) that are appended by default * ($appends array) * * @return array */ public static function getAppendFields() { return (new static)->appends; } /** * List of fields to display by default ($defaults array) * * @return array */ public static function getDefaultFields() { return (new static)->default; } /** * Return the $relationKeys array * * @return mixed */ public static function getRelationKeyFields() { return (new static)->relationKeys; } /** * Returns list of fields on which filter is allowed to be applied * * @return array */ public static function getFilterableFields() { return (new static)->filterable; } /** * Checks if given relation exists on the model * * @param $relation * @return bool */ public static function relationExists($relation) { // Check if relation name in modal is in camel case or not if (config("api.relation_case", 'snakecase') === 'camelcase') { return (method_exists(new static(), $relation) ?? false) || (method_exists(new static(), Str::camel($relation)) ?? false); } return method_exists(new static(), $relation); } //endregion /** * Prepare a date for array / JSON serialization. Override base method in Model to suite our needs * * @param \DateTime $date * @return string */ protected function serializeDate(\DateTimeInterface $date) { return $date->format("c"); } /** * Return a timestamp as DateTime object. * * @param mixed $value * @return \Carbon\Carbon */ protected function asDateTime($value) { // If this value is already a Carbon instance, we shall just return it as is. // This prevents us having to re-instantiate a Carbon instance when we know // it already is one, which wouldn't be fulfilled by the DateTime check. if ($value instanceof Carbon) { return $value; } // If the value is already a DateTime instance, we will just skip the rest of // these checks since they will be a waste of time, and hinder performance // when checking the field. We will just return the DateTime right away. if ($value instanceof DateTimeInterface) { return new Carbon( $value->format('Y-m-d H:i:s.u'), $value->getTimeZone() ); } // If this value is an integer, we will assume it is a UNIX timestamp's value // and format a Carbon object from this timestamp. This allows flexibility // when defining your date fields as they might be UNIX timestamps here. if (is_numeric($value)) { return Carbon::createFromTimestamp($value); } // If the value is in simply year, month, day format, we will instantiate the // Carbon instances from that format. Again, this provides for simple date // fields on the database, while still supporting Carbonized conversion. if (preg_match('/^(\d{4})-(\d{1,2})-(\d{1,2})$/', $value)) { return Carbon::createFromFormat('Y-m-d', $value)->startOfDay(); } // Parse ISO 8061 date if (preg_match('/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})\\+(\d{2}):(\d{2})$/', $value)) { return Carbon::createFromFormat('Y-m-d\TH:i:s+P', $value); } elseif (preg_match('/^(\d{4})-(\d{1,2})-(\d{1,2}T(\d{2}):(\d{2}):(\d{2})\\.(\d{1,3})Z)$/', $value)) { return Carbon::createFromFormat('Y-m-d\TH:i:s.uZ', $value); } // Finally, we will just assume this date is in the format used by default on // the database connection and use that format to create the Carbon object // that is returned back out to the developers after we convert it here. return Carbon::createFromFormat($this->getDateFormat(), $value); } /** * Eagerly load the relationship on a set of models. * * @param array $models * @param string $name * @param \Closure $constraints * @return array */ protected function loadRelation(array $models, $name, Closure $constraints) { // First we will "back up" the existing where conditions on the query so we can // add our eager constraints. Then we will merge the wheres that were on the // query back to it in order that any where conditions might be specified. $relation = $this->getRelation($name); $relation->addEagerConstraints($models); call_user_func($constraints, $relation); $models = $relation->initRelation($models, $name); // Once we have the results, we just match those back up to their parent models // using the relationship instance. Then we just return the finished arrays // of models which have been eagerly hydrated and are readied for return. $results = $relation->getEager(); return $relation->match($models, $results, $name); } /** * Fill the model with an array of attributes. * * @param array $attributes * @param bool $relations If the attributes also contain relations * @return Model */ public function fill(array $attributes = []) { $this->raw = $attributes; $excludes = config("api.excludes"); foreach ($attributes as $key => $attribute) { // Guarded attributes should be removed if (in_array($key, $excludes)) { unset($attributes[$key]); } else if (method_exists($this, $key) && ((is_array($attribute) || is_null($attribute)))) { // Its a relation $this->relationAttributes[$key] = $attribute; // For belongs to relation, while filling, we need to set relation key. $relation = call_user_func([$this, $key]); if ($relation instanceof BelongsTo) { $primaryKey = $relation->getRelated()->getKeyName(); if ($attribute !== null) { // If key value is not set in request, we create new object if (!isset($attribute[$primaryKey])) { throw new RelatedResourceNotFoundException('Resource for relation "' . $key . '" not found'); } else { $model = $relation->getRelated()->find($attribute[$primaryKey]); if (!$model) { // Resource not found throw new ResourceNotFoundException(); } } } $relationKey = $relation->getForeignKeyName(); $this->setAttribute($relationKey, ($attribute === null) ? null : $model->getKey()); } unset($attributes[$key]); } } return parent::fill($attributes); } public function save(array $options = []) { // Belongs to relation needs to be set before, because we need the parent's Id foreach ($this->relationAttributes as $key => $relationAttribute) { /** @var Relation $relation */ $relation = call_user_func([$this, $key]); if ($relation instanceof BelongsTo) { $primaryKey = $relation->getRelated()->getKeyName(); if ($relationAttribute !== null) { // If key value is not set in request, we create new object if (!isset($relationAttribute[$primaryKey])) { throw new RelatedResourceNotFoundException('Resource for relation "' . $key . '" not found'); } else { $model = $relation->getRelated()->find($relationAttribute[$primaryKey]); if (!$model) { // Resource not found throw new RelatedResourceNotFoundException('Resource for relation "' . $key . '" not found'); } } } $relationKey = $relation->getForeignKeyName(); $this->setAttribute($relationKey, ($relationAttribute === null) ? null : $model->getKey()); unset($this->relationAttributes[$key]); } } parent::save($options); // Fill all other relations foreach ($this->relationAttributes as $key => $relationAttribute) { /** @var Relation $relation */ $relation = call_user_func([$this, $key]); $primaryKey = $relation->getRelated()->getKeyName(); if ($relation instanceof HasOne || $relation instanceof HasMany) { if ($relation instanceof HasOne) { $relationAttribute = [$relationAttribute]; } $relationKey = explode(".", $relation->getQualifiedParentKeyName())[1]; foreach ($relationAttribute as $val) { if ($val !== null) { if (!isset($val[$primaryKey])) { throw new RelatedResourceNotFoundException('Resource for relation "' . $key . '" not found'); } else { /** @var Model $model */ $model = $relation->getRelated()->find($val[$primaryKey]); if (!$model) { // Resource not found throw new RelatedResourceNotFoundException('Resource for relation "' . $key . '" not found'); } // Only update relation key to attach $model to $this object $model->{$relationKey} = $this->getKey(); $model->save(); } } } } else if ($relation instanceof BelongsToMany) { $relatedIds = []; // Value is an array of related models foreach ($relationAttribute as $val) { if ($val !== null) { if (!isset($val[$primaryKey])) { throw new RelatedResourceNotFoundException('Resource for relation "' . $key . '" not found'); } else { /** @var Model $model */ $model = $relation->getRelated()->find($val[$primaryKey]); if (!$model) { // Resource not found throw new RelatedResourceNotFoundException('Resource for relation "' . $key . '" not found'); } } } if ($val !== null) { if(isset($val['pivot'])) { // We have additional fields other than primary key // that need to be saved to pivot table /* [ { "id": 12, // Primary key "pivot": { "count": 8 // Pivot table column } } ] */ $relatedIds[$model->getKey()] = $val['pivot']; } else { // We just have ids $relatedIds[] = $model->getKey(); } } } $relation->sync($relatedIds); } } } }
php
MIT
45e05076f8fc7918d70631369b02ed7168a6cb5d
2026-01-05T04:52:55.517023Z
false
Froiden/laravel-rest-api
https://github.com/Froiden/laravel-rest-api/blob/45e05076f8fc7918d70631369b02ed7168a6cb5d/src/api.php
src/api.php
<?php return [ /** * Default number of records to return when no limit is specified */ 'defaultLimit' => 10, /** * Maximum number of records to return in single request. This limit is used * when user enters large number in limit parameter of the request */ 'maxLimit' => 1000, /* * Add allow cross origin headers. It is recommended by APIs to allow cross origin * requests. But, you can disable it. */ 'cors' => true, /** * Which headers are allowed in CORS requests */ 'cors_headers' => ['Authorization', 'Content-Type'], /** * List of fields that should not be considered while saving a model */ 'excludes' => ['_token'], /** * Prefix for all the routes */ 'prefix' => 'api', /** * Default version for the API. Set null to disable versions */ 'default_version' => 'v1', /** * Relation method name case snakecase|camelcase default it is snakecase */ 'relation_case' => 'snakecase' ];
php
MIT
45e05076f8fc7918d70631369b02ed7168a6cb5d
2026-01-05T04:52:55.517023Z
false
Froiden/laravel-rest-api
https://github.com/Froiden/laravel-rest-api/blob/45e05076f8fc7918d70631369b02ed7168a6cb5d/src/RequestParser.php
src/RequestParser.php
<?php namespace Froiden\RestAPI; use Froiden\RestAPI\Exceptions\Parse\InvalidLimitException; use Froiden\RestAPI\Exceptions\Parse\InvalidFilterDefinitionException; use Froiden\RestAPI\Exceptions\Parse\InvalidOrderingDefinitionException; use Froiden\RestAPI\Exceptions\Parse\MaxLimitException; use Froiden\RestAPI\Exceptions\Parse\NotAllowedToFilterOnThisFieldException; use Illuminate\Database\Eloquent\Relations\BelongsTo; use Illuminate\Database\Eloquent\Relations\HasMany; use Illuminate\Database\Eloquent\Relations\HasOne; use Illuminate\Support\Str; class RequestParser { /** * Checks if fields are specified correctly */ const FIELDS_REGEX = "/([a-zA-Z0-9\\_\\-\\:\\.\\(\\)]+(?'curly'\\{((?>[^{}]+)|(?&curly))*\\})?+)/"; /** * Extracts fields parts */ const FIELD_PARTS_REGEX = "/([^{.]+)(.limit\\(([0-9]+)\\)|.offset\\(([0-9]+)\\)|.order\\(([A-Za-z_]+)\\))*(\\{((?>[^{}]+)|(?R))*\\})?/i"; /** * Checks if filters are correctly specified */ const FILTER_REGEX = "/(\\((?:[\\s]*(?:and|or)?[\\s]*[\\w\\.]+[\\s]+(?:eq|ne|gt|ge|lt|le|lk)[\\s]+(?:\\\"(?:[^\\\"\\\\]|\\\\.)*\\\"|\\d+(,\\d+)*(\\.\\d+(e\\d+)?)?|null)[\\s]*|(?R))*\\))/i"; /** * Extracts filter parts */ const FILTER_PARTS_REGEX = "/([\\w\\.]+)[\\s]+(?:eq|ne|gt|ge|lt|le|lk)[\\s]+(?:\"(?:[^\"\\\\]|\\\\.)*\"|\\d+(?:,\\d+)*(?:\\.\\d+(?:e\\d+)?)?|null)/i"; /** * Checks if ordering is specified correctly */ const ORDER_FILTER = "/[\\s]*([\\w\\.]+)(?:[\\s](?!,))*(asc|desc|)/i"; /** * Full class reference to model this controller represents * * @var string */ protected $model = null; /** * Table name corresponding to the model this controller is handling * * @var string */ private $table = null; /** * Primary key of the model * * @var string */ private $primaryKey = null; /** * Fields to be returned in response. This does not include relations * * @var array */ private $fields = []; /** * Relations to be included in the response * * @var array */ private $relations = []; /** * Number of results requested per page * * @var int */ private $limit = 10; /** * Offset from where fetching should start * * @var int */ private $offset = 0; /** * Ordering string * * @var int */ private $order = null; /** * Filters to be applied * * @var string */ private $filters = null; /** * Attributes passed in request * * @var array */ private $attributes = []; public function __construct($model) { $this->model = $model; $this->primaryKey = call_user_func([new $this->model(), "getKeyName"]); $this->parseRequest(); } /** * @return array */ public function getFields() { return $this->fields; } /** * @param array $fields */ public function setFields($fields) { $this->fields = $fields; } /** * @return array */ public function getRelations() { return $this->relations; } /** * @param array $relations */ public function setRelations($relations) { $this->relations = $relations; } /** * @return int */ public function getLimit() { return $this->limit; } /** * @return int */ public function getOffset() { return $this->offset; } /** * @return int */ public function getOrder() { return $this->order; } /** * @return string */ public function getFilters() { return $this->filters; } /** * @return array */ public function getAttributes() { return $this->attributes; } /** * Parse request and fill the parameters * @return $this current controller object for chain method calling * @throws InvalidFilterDefinitionException * @throws InvalidOrderingDefinitionException * @throws MaxLimitException */ protected function parseRequest() { if (request()->limit) { if (request()->limit <= 0) { throw new InvalidLimitException(); } else if (request()->limit > config("api.maxLimit")) { throw new MaxLimitException(); } else { $this->limit = request()->limit; } } else { $this->limit = config("api.defaultLimit"); } if (request()->offset) { $this->offset = request()->offset; } else { $this->offset = 0; } $this->extractFields(); $this->extractFilters(); $this->extractOrdering(); $this->loadTableName(); $this->attributes = request()->all(); return $this; } protected function extractFields() { if (request()->fields) { $this->parseFields(request()->fields); } else { // Else, by default, we only return default set of visible fields $fields = call_user_func($this->model."::getDefaultFields"); // We parse the default fields in same way as above so that, if // relations are included in default fields, they also get included $this->parseFields(implode(",", $fields)); } if (!in_array($this->primaryKey, $this->fields)) { $this->fields[] = $this->primaryKey; } } protected function extractFilters() { if (request()->filters) { $filters = "(" . request()->filters . ")"; if (preg_match(RequestParser::FILTER_REGEX, $filters) === 1) { preg_match_all(RequestParser::FILTER_PARTS_REGEX, $filters, $parts); $filterable = call_user_func($this->model . "::getFilterableFields"); foreach ($parts[1] as $column) { if (!in_array($column, $filterable)) { throw new NotAllowedToFilterOnThisFieldException("Applying filter on field \"" . $column . "\" is not allowed"); } } // Convert filter name to sql `column` format $where = preg_replace( [ "/([\\w]+)\\.([\\w]+)[\\s]+(eq|ne|gt|ge|lt|le|lk)/i", "/([\\w]+)[\\s]+(eq|ne|gt|ge|lt|le|lk)/i", ], [ "`$1`.`$2` $3", "`$1` $2", ], $filters ); // convert eq null to is null and ne null to is not null $where = preg_replace( [ "/ne[\\s]+null/i", "/eq[\\s]+null/i" ], [ "is not null", "is null" ], $where ); // Replace operators $where = preg_replace( [ "/[\\s]+eq[\\s]+/i", "/[\\s]+ne[\\s]+/i", "/[\\s]+gt[\\s]+/i", "/[\\s]+ge[\\s]+/i", "/[\\s]+lt[\\s]+/i", "/[\\s]+le[\\s]+/i", "/[\\s]+lk[\\s]+/i" ], [ " = ", " != ", " > ", " >= ", " < ", " <= ", " LIKE " ], $where ); $this->filters = $where; } else { throw new InvalidFilterDefinitionException(); } } } protected function extractOrdering() { if (request()->order) { if (preg_match(RequestParser::ORDER_FILTER, request()->order) === 1) { $order = request()->order; // eg : user.name asc, year desc, age,month $order = preg_replace( [ "/[\\s]*([\\w]+)\\.([\\w]+)(?:[\\s](?!,))*(asc|desc|)/", "/[\\s]*([\\w`\\.]+)(?:[\\s](?!,))*(asc|desc|)/", ], [ "$1`.`$2 $3", // Result: user`.`name asc, year desc, age,month "`$1` $2", // Result: `user`.`name` asc, `year` desc, `age`,`month` ], $order ); $this->order = $order; } else { throw new InvalidOrderingDefinitionException(); } } } /** * Recursively parses fields to extract limit, ordering and their own fields * and adds width relations * * @param $fields */ private function parseFields($fields) { // If fields parameter is set, parse it using regex preg_match_all(static::FIELDS_REGEX, $fields, $matches); if (!empty($matches[0])) { foreach ($matches[0] as $match) { preg_match_all(static::FIELD_PARTS_REGEX, $match, $parts); $fieldName = $parts[1][0]; if (Str::contains($fieldName, ":") || call_user_func($this->model . "::relationExists", $fieldName)) { // If field name has a colon, we assume its a relations // OR // If method with field name exists in the class, we assume its a relation // This is default laravel behavior $limit = ($parts[3][0] == "") ? config("api.defaultLimit") : $parts[3][0]; $offset = ($parts[4][0] == "") ? 0 : $parts[4][0]; $order = ($parts[5][0] == "chronological") ? "chronological" : "reverse_chronological"; if (!empty($parts[7][0])) { $subFields = explode(",", $parts[7][0]); // This indicates if user specified fields for relation or not $userSpecifiedFields = true; } else { $subFields = []; $userSpecifiedFields = false; } $fieldName = str_replace(":", ".", $fieldName); // Check if relation name in modal is in camel case then convert relation name in camel case if(config("api.relation_case", 'snakecase') === 'camelcase'){ $fieldName = Str::camel($fieldName); } if (!isset($this->relations[$fieldName])) { $this->relations[$fieldName] = [ "limit" => $limit, "offset" => $offset, "order" => $order, "fields" => $subFields, "userSpecifiedFields" => $userSpecifiedFields ]; } else { $this->relations[$fieldName]["limit"] = $limit; $this->relations[$fieldName]["offset"] = $offset; $this->relations[$fieldName]["order"] = $order; $this->relations[$fieldName]["fields"] = array_merge($this->relations[$fieldName]["fields"], $subFields); } // We also need to add the relation's foreign key field to select. If we don't, // relations always return null if (Str::contains($fieldName, ".")) { $relationNameParts = explode('.', $fieldName); $model = $this->model; $relation = null; foreach ($relationNameParts as $rp) { $relation = call_user_func([ new $model(), $rp]); $model = $relation->getRelated(); } // Its a multi level relations $fieldParts = explode(".", $fieldName); if ($relation instanceof BelongsTo) { $singular = $relation->getForeignKeyName(); } else if ($relation instanceof HasOne || $relation instanceof HasMany) { $singular = $relation->getForeignKeyName(); } // Unset last element of array unset($fieldParts[count($fieldParts) - 1]); $parent = implode(".", $fieldParts); if ($relation instanceof HasOne || $relation instanceof HasMany) { // For hasMany and HasOne, the foreign key is in current relation table, not in parent $this->relations[$fieldName]["fields"][] = $singular; } else { // The parent might already been set because we cannot rely on order // in which user sends relations in request if (!isset($this->relations[$parent])) { $this->relations[$parent] = [ "limit" => config("api.defaultLimit"), "offset" => 0, "order" => "chronological", "fields" => isset($singular) ? [$singular] : [], "userSpecifiedFields" => true ]; } else { if (isset($singular)) { $this->relations[$parent]["fields"][] = $singular; } } } if ($relation instanceof BelongsTo) { $this->relations[$fieldName]["limit"] = max($this->relations[$fieldName]["limit"], $this->relations[$parent]["limit"]); } else if ($relation instanceof HasMany) { $this->relations[$fieldName]["limit"] = $this->relations[$fieldName]["limit"] * $this->relations[$parent]["limit"]; } } else { $relation = call_user_func([new $this->model(), $fieldName]); if ($relation instanceof HasOne) { $keyField = explode(".", $relation->getQualifiedParentKeyName())[1]; } else if ($relation instanceof BelongsTo) { $keyField = explode(".", $relation->getQualifiedForeignKeyName())[1]; } if (isset($keyField) && !in_array($keyField, $this->fields)) { $this->fields[] = $keyField; } if ($relation instanceof BelongsTo) { $this->relations[$fieldName]["limit"] = max($this->relations[$fieldName]["limit"], $this->limit); } else if ($relation instanceof HasMany) { // Commented out for third level hasmany limit // $this->relations[$fieldName]["limit"] = $this->relations[$fieldName]["limit"] * $this->limit; } } } else { // Else, its a normal field $this->fields[] = $fieldName; } } } } /** * Load table name into the $table property */ private function loadTableName() { $this->table = call_user_func($this->model."::getTableName"); } }
php
MIT
45e05076f8fc7918d70631369b02ed7168a6cb5d
2026-01-05T04:52:55.517023Z
false
Froiden/laravel-rest-api
https://github.com/Froiden/laravel-rest-api/blob/45e05076f8fc7918d70631369b02ed7168a6cb5d/src/ApiController.php
src/ApiController.php
<?php namespace Froiden\RestAPI; use Froiden\RestAPI\Exceptions\Parse\NotAllowedToFilterOnThisFieldException; use Froiden\RestAPI\Exceptions\ResourceNotFoundException; use Froiden\RestAPI\Tests\Models\DummyUser; use Illuminate\Database\Eloquent\Builder; use Illuminate\Database\Eloquent\Collection; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Relations\BelongsTo; use Froiden\RestAPI\ExtendedRelations\BelongsToMany; use Illuminate\Database\Eloquent\Relations\HasMany; use Illuminate\Database\Eloquent\Relations\HasOne; use Illuminate\Database\Eloquent\Relations\Relation; use Illuminate\Foundation\Http\FormRequest; use Illuminate\Support\Arr; use Illuminate\Support\Str; class ApiController extends \Illuminate\Routing\Controller { /** * Full class reference to model this controller represents * * @var string */ protected $model = null; /** * Table name corresponding to the model this controller is handling * * @var string */ private $table = null; /** * Primary key of the model * * @var string */ private $primaryKey = null; /** * Default number of records to return * * @var int */ protected $defaultLimit = 10; /** * Maximum number of recorded allowed to be returned in single request * * @var int */ protected $maxLimit = 1000; /** * Query being built to fetch the results * * @var Builder */ private $query = null; /** * Form request to validate index request * * @var FormRequest */ protected $indexRequest = null; /** * Form request to validate store request * * @var FormRequest */ protected $storeRequest = null; /** * Form request to validate show request * * @var FormRequest */ protected $showRequest = null; /** * Form request to validate update request * * @var FormRequest */ protected $updateRequest = null; /** * Form request to validate delete request * * @var FormRequest */ protected $deleteRequest = null; /** * Time when processing of this request started. Used * to measure total processing time * * @var float */ private $processingStartTime = 0; /** * Fields to be excluded while saving a request. Fields not in excluded list * are considered model attributes * * @var array */ protected $exclude = ["_token"]; /** * @var RequestParser */ private $parser = null; protected $results = null; public function __construct() { $this->processingStartTime = microtime(true); if ($this->model) { // Only if model is defined. Otherwise, this is a normal controller $this->primaryKey = call_user_func([new $this->model(), "getKeyName"]); $this->table = call_user_func([new $this->model(), "getTable"]); } if (config('app.debug') == true) { \DB::enableQueryLog(); } } /** * Process index page request * * @return mixed */ public function index() { $this->validate(); $results = $this->parseRequest() ->addIncludes() ->addFilters() ->addOrdering() ->addPaging() ->modify() ->getResults() ->toArray(); $meta = $this->getMetaData(); return ApiResponse::make(null, $results, $meta); } /** * Process the show request * * @return mixed */ public function show(...$args) { // We need to do this in order to support multiple parameter resource routes. For example, // if we map route /user/{user}/comments/{comment} to a controller, Laravel will pass `user` // as first argument and `comment` as last argument. So, id object that we want to fetch // is the last argument. $id = last(func_get_args()); $this->validate(); $results = $this->parseRequest() ->addIncludes() ->addKeyConstraint($id) ->modify() ->getResults(true) ->first() ->toArray(); $meta = $this->getMetaData(true); return ApiResponse::make(null, $results, $meta); } public function store() { \DB::beginTransaction(); $this->validate(); // Create new object /** @var ApiModel $object */ $object = new $this->model(); $object->fill(request()->all()); // Run hook if exists if(method_exists($this, 'storing')) { $object = call_user_func([$this, 'storing'], $object); } $object->save(); $meta = $this->getMetaData(true); \DB::commit(); if(method_exists($this, 'stored')) { call_user_func([$this, 'stored'], $object); } return ApiResponse::make("Resource created successfully", [ "id" => $object->id ], $meta); } public function update(...$args) { \DB::beginTransaction(); $id = last(func_get_args()); $this->validate(); // Get object for update $this->query = call_user_func($this->model . "::query"); $this->modify(); /** @var ApiModel $object */ $object = $this->query->find($id); if (!$object) { throw new ResourceNotFoundException(); } $object->fill(request()->all()); if(method_exists($this, 'updating')) { $object = call_user_func([$this, 'updating'], $object); } $object->save(); $meta = $this->getMetaData(true); \DB::commit(); if(method_exists($this, 'updated')) { call_user_func([$this, 'updated'], $object); } return ApiResponse::make("Resource updated successfully", [ "id" => $object->id ], $meta); } public function destroy(...$args) { \DB::beginTransaction(); $id = last(func_get_args()); $this->validate(); // Get object for update $this->query = call_user_func($this->model . "::query"); $this->modify(); /** @var Model $object */ $object = $this->query->find($id); if (!$object) { throw new ResourceNotFoundException(); } if(method_exists($this, 'destroying')) { $object = call_user_func([$this, 'destroying'], $object); } $object->delete(); $meta = $this->getMetaData(true); \DB::commit(); if(method_exists($this, 'destroyed')) { call_user_func([$this, 'destroyed'], $object); } return ApiResponse::make("Resource deleted successfully", null, $meta); } public function relation($id, $relation) { $this->validate(); // To show relations, we just make a new fields parameter, which requests // only object id, and the relation and get the results like normal index request $fields = "id," . $relation . ".limit(" . ((request()->limit) ? request()->limit : $this->defaultLimit) . ")" . ((request()->offset) ? ".offset(" . request()->offset . ")": "" ) . ((request()->fields) ? "{" .request()->fields . "}" : ""); request()->fields = $fields; $results = $this->parseRequest() ->addIncludes() ->addKeyConstraint($id) ->modify() ->getResults(true) ->first() ->toArray(); $data = $results[$relation]; $meta = $this->getMetaData(true); return ApiResponse::make(null, $data, $meta); } protected function parseRequest() { $this->parser = new RequestParser($this->model); return $this; } protected function validate() { if ($this->isIndex()) { $requestClass = $this->indexRequest; } else if ($this->isShow()) { $requestClass = $this->showRequest; } else if ($this->isUpdate()) { $requestClass = $this->updateRequest; } else if ($this->isDelete()) { $requestClass = $this->deleteRequest; } else if ($this->isStore()) { $requestClass = $this->storeRequest; } else if ($this->isRelation()) { $requestClass = $this->indexRequest; } else { $requestClass = null; } if ($requestClass) { // We just make the class, its validation is called automatically app()->make($requestClass); } } /** * Looks for relations in the requested fields and adds with query for them * * @return $this current controller object for chain method calling */ protected function addIncludes() { $relations = $this->parser->getRelations(); if (!empty($relations)) { $includes = []; foreach ($relations as $key => $relation) { $includes[$key] = function (Relation $q) use ($relation, $key) { $relations = $this->parser->getRelations(); $tableName = $q->getRelated()->getTable(); $primaryKey = $q->getRelated()->getKeyName(); if ($relation["userSpecifiedFields"]) { // Prefix table name so that we do not get ambiguous column errors $fields = $relation["fields"]; } else { // Add default fields, if no fields specified $related = $q->getRelated(); $fields = call_user_func(get_class($related) . "::getDefaultFields"); $fields = array_merge($fields, $relation["fields"]); $relations[$key]["fields"] = $fields; } // Remove appends from select $appends = call_user_func(get_class($q->getRelated()) . "::getAppendFields"); $relations[$key]["appends"] = $appends; if (!in_array($primaryKey, $fields)) { $fields[] = $primaryKey; } $fields = array_map(function($name) use($tableName) { return $tableName . "." . $name; }, array_diff($fields, $appends)); if ($q instanceof BelongsToMany) { // Because laravel loads all the related models of relations in many-to-many // together, limit and offset do not work. So, we have to complicate things // to make them work $innerQuery = $q->getQuery(); $innerQuery->select($fields); $innerQuery->selectRaw("@currcount := IF(@currvalue = " . $q->getQualifiedForeignPivotKeyName() . ", @currcount + 1, 1) AS rank"); $innerQuery->selectRaw("@currvalue := " . $q->getQualifiedForeignPivotKeyName() . " AS whatever"); $innerQuery->orderBy($q->getQualifiedForeignPivotKeyName(), ($relation["order"] == "chronological") ? "ASC" : "DESC"); // Inner Join causes issues when a relation for parent does not exist. // So, we change it to right join for this query $innerQuery->getQuery()->joins[0]->type = "right"; $outerQuery = $q->newPivotStatement(); $outerQuery->from(\DB::raw("(". $innerQuery->toSql() . ") as `$tableName`")) ->mergeBindings($innerQuery->getQuery()); $q->select($fields) ->join(\DB::raw("(" . $outerQuery->toSql() . ") as `outer_query`"), function ($join) use($q) { $join->on("outer_query." . $q->getRelatedKeyName(), "=", $q->getQualifiedRelatedPivotKeyName ()); $join->on("outer_query.whatever", "=", $q->getQualifiedForeignPivotKeyName()); }) ->setBindings(array_merge($q->getQuery()->getBindings(), $outerQuery->getBindings())) ->where("rank", "<=", $relation["limit"] + $relation["offset"]) ->where("rank", ">", $relation["offset"]); } else { // We need to select foreign key so that Laravel can match to which records these // need to be attached if ($q instanceof BelongsTo) { $fields[] = $q->getOwnerKeyName(); if (strpos($key, ".") !== false) { $parts = explode(".", $key); array_pop($parts); $relation["limit"] = $relations[implode(".", $parts)]["limit"]; } } else if ($q instanceof HasOne) { $fields[] = $q->getQualifiedForeignKeyName(); // This will be used to hide this foreign key field // in the processAppends function later $relations[$key]["foreign"] = $q->getQualifiedForeignKeyName(); } else if ($q instanceof HasMany) { $fields[] = $q->getQualifiedForeignKeyName(); $relations[$key]["foreign"] = $q->getQualifiedForeignKeyName(); $q->orderBy($primaryKey, ($relation["order"] == "chronological") ? "ASC" : "DESC"); } $q->select($fields); $q->take($relation["limit"]); if ($relation["offset"] !== 0) { $q->skip($relation["offset"]); } } $this->parser->setRelations($relations); }; } $this->query = call_user_func($this->model."::with", $includes); } else { $this->query = call_user_func($this->model."::query"); } return $this; } /** * Add requested filters. Filters are defined similar to normal SQL queries like * (name eq "Milk" or name eq "Eggs") and price lt 2.55 * The string should be enclosed in double quotes * @return $this * @throws NotAllowedToFilterOnThisFieldException */ protected function addFilters() { if ($this->parser->getFilters()) { $this->query->whereRaw($this->parser->getFilters()); } return $this; } /** * Add sorting to the query. Sorting is similar to SQL queries * * @return $this */ protected function addOrdering() { if ($this->parser->getOrder()) { $this->query->orderByRaw($this->parser->getOrder()); } return $this; } /** * Adds paging limit and offset to SQL query * * @return $this */ protected function addPaging() { $limit = $this->parser->getLimit(); $offset = $this->parser->getOffset(); if ($offset <= 0) { $skip = 0; } else { $skip = $offset; } $this->query->skip($skip); $this->query->take($limit); return $this; } protected function addKeyConstraint($id) { // Add equality constraint $this->query->where($this->table . "." . ($this->primaryKey), "=", $id); return $this; } /** * Runs query and fetches results * * @param bool $single * @return Collection * @throws ResourceNotFoundException */ protected function getResults($single = false) { $customAttributes = call_user_func($this->model."::getAppendFields"); // Laravel's $appends adds attributes always to the output. With this method, // we can specify which attributes are to be included $appends = []; $fields = $this->parser->getFields(); foreach ($fields as $key => $field) { if (in_array($field, $customAttributes)) { $appends[] = $field; unset($fields[$key]); } else { // Add table name to fields to prevent ambiguous column issues $fields[$key] = $this->table . "." . $field; } } $this->parser->setFields($fields); if (!$single) { /** @var Collection $results */ $results = $this->query->select($fields)->get(); } else { /** @var Collection $results */ $results = $this->query->select($fields)->skip(0)->take(1)->get(); if ($results->count() == 0) { throw new ResourceNotFoundException(); } } foreach($results as $result) { $result->setAppends($appends); } $this->processAppends($results); $this->results = $results; return $results; } private function processAppends($models, $parent = null) { if (! ($models instanceof Collection)) { return $models; } else if ($models->count() == 0) { return $models; } // Attribute at $key is a relation $first = $models->first(); $attributeKeys = array_keys($first->getRelations()); $relations = $this->parser->getRelations(); foreach ($attributeKeys as $key) { $relationName = ($parent === null) ? $key : $parent . "." . $key; if (isset($relations[$relationName])) { $appends = $relations[$relationName]["appends"]; $appends = array_intersect($appends, $relations[$relationName]["fields"]); if (isset($relations[$relationName]["foreign"])) { $foreign = explode(".", $relations[$relationName]["foreign"])[1]; } else { $foreign = null; } foreach ($models as $model) { if ($model->$key instanceof Collection) { $model->{$key}->each(function ($item, $key) use($appends, $foreign) { $item->setAppends($appends); // Hide the foreign key fields if (!empty($foreign)) { $item->makeHidden($foreign); } }); $this->processAppends($model->$key, $key); } else if (!empty($model->$key)) { $model->$key->setAppends($appends); if (!empty($foreign)) { $model->$key->makeHidden($foreign); } $this->processAppends(collect($model->$key), $key); } } } } } /** * Builds metadata - paging, links, time to complete request, etc * * @return array */ protected function getMetaData($single = false) { if (!$single) { $meta = [ "paging" => [ "links" => [ ] ] ]; $limit = $this->parser->getLimit(); $pageOffset = $this->parser->getOffset(); $current = $pageOffset; // Remove offset because setting offset does not return // result. As, there is single result in count query, // and setting offset will not return that record $offset = $this->query->getQuery()->offset; $this->query->offset(0); $totalRecords = $this->query->count($this->table . "." . $this->primaryKey); $this->query->offset($offset); $meta["paging"]["total"] = $totalRecords; if (($current + $limit) < $meta["paging"]["total"]) { $meta["paging"]["links"]["next"] = $this->getNextLink(); } if ($current >= $limit) { $meta["paging"]["links"]["previous"] = $this->getPreviousLink(); } } $meta["time"] = round(microtime(true) - $this->processingStartTime, 3); if (config('app.debug') == true) { $log = \DB::getQueryLog(); \DB::disableQueryLog(); $meta["queries"] = count($log); $meta["queries_list"] = $log; } return $meta; } protected function getPreviousLink() { $offset = $this->parser->getOffset(); $limit = $this->parser->getLimit(); $queryString = ((request()->fields) ? "&fields=" . urlencode(request()->fields) : "") . ((request()->filters) ? "&filters=" . urlencode(request()->filters) : "") . ((request()->order) ? "&fields=" . urlencode(request()->order) : ""); $queryString .= "&offset=" . ($offset - $limit); return request()->url() . "?" . trim($queryString, "&"); } protected function getNextLink() { $offset = $this->parser->getOffset(); $limit = $this->parser->getLimit(); $queryString = ((request()->fields) ? "&fields=" . urlencode(request()->fields) : "") . ((request()->filters) ? "&filters=" . urlencode(request()->filters) : "") . ((request()->order) ? "&fields=" . urlencode(request()->order) : ""); $queryString .= "&offset=" . ($offset + $limit); return request()->url() . "?" . trim($queryString, "&"); } /** * Checks if current request is index request * @return bool */ protected function isIndex() { return in_array("index", explode(".", request()->route()->getName())); } /** * Checks if current request is create request * @return bool */ protected function isCreate() { return in_array("create", explode(".", request()->route()->getName())); } /** * Checks if current request is show request * @return bool */ protected function isShow() { return in_array("show", explode(".", request()->route()->getName())); } /** * Checks if current request is update request * @return bool */ protected function isUpdate() { return in_array("update", explode(".", request()->route()->getName())); } /** * Checks if current request is delete request * @return bool */ protected function isDelete() { return in_array("destroy", explode(".", request()->route()->getName())); } /** * Checks if current request is store request * @return bool */ protected function isStore() { return in_array("store", explode(".", request()->route()->getName())); } /** * Checks if current request is relation request * @return bool */ protected function isRelation() { return in_array("relation", explode(".", request()->route()->getName())); } /** * Calls the modifyRequestType methods to modify query just before execution * @return $this */ private function modify() { if ($this->isIndex()) { $this->query = $this->modifyIndex($this->query); } else if ($this->isShow()) { $this->query = $this->modifyShow($this->query); } else if ($this->isDelete()) { $this->query = $this->modifyDelete($this->query); } else if ($this->isUpdate()) { $this->query = $this->modifyUpdate($this->query); } return $this; } /** * Modify the query for show request * @param $query * @return mixed */ protected function modifyShow($query) { return $query; } /** * Modify the query for update request * @param $query * @return mixed */ protected function modifyUpdate($query) { return $query; } /** * Modify the query for delete request * @param $query * @return mixed */ protected function modifyDelete($query) { return $query; } /** * Modify the query for index request * @param $query * @return mixed */ protected function modifyIndex($query) { return $query; } protected function getQuery() { return $this->query; } protected function setQuery($query) { $this->query = $query; } //endregion }
php
MIT
45e05076f8fc7918d70631369b02ed7168a6cb5d
2026-01-05T04:52:55.517023Z
false
Froiden/laravel-rest-api
https://github.com/Froiden/laravel-rest-api/blob/45e05076f8fc7918d70631369b02ed7168a6cb5d/src/Routing/ApiUrlGenerator.php
src/Routing/ApiUrlGenerator.php
<?php namespace Froiden\RestAPI\Routing; class ApiUrlGenerator extends \Illuminate\Routing\UrlGenerator { }
php
MIT
45e05076f8fc7918d70631369b02ed7168a6cb5d
2026-01-05T04:52:55.517023Z
false
Froiden/laravel-rest-api
https://github.com/Froiden/laravel-rest-api/blob/45e05076f8fc7918d70631369b02ed7168a6cb5d/src/Routing/ApiResourceRegistrar.php
src/Routing/ApiResourceRegistrar.php
<?php namespace Froiden\RestAPI\Routing; use Illuminate\Routing\ResourceRegistrar; use Illuminate\Support\Str; class ApiResourceRegistrar extends ResourceRegistrar { /** * The default actions for a resourceful controller. * * @var array */ protected $resourceDefaults = ['index', 'store', 'show', 'update', 'destroy', 'relation']; /** * Create a new resource registrar instance. * * @param ApiRouter|\Illuminate\Routing\Router $router */ public function __construct(ApiRouter $router) { $this->router = $router; } /** * Route a resource to a controller. * * @param string $name * @param string $controller * @param array $options * @return void */ public function register($name, $controller, array $options = []) { if (isset($options['parameters']) && ! isset($this->parameters)) { $this->parameters = $options['parameters']; } // If the resource name contains a slash, we will assume the developer wishes to // register these resource routes with a prefix so we will set that up out of // the box so they don't have to mess with it. Otherwise, we will continue. if (Str::contains($name, '/')) { $this->prefixedResource($name, $controller, $options); return; } // We need to extract the base resource from the resource name. Nested resources // are supported in the framework, but we need to know what name to use for a // place-holder on the route parameters, which should be the base resources. $base = $this->getResourceWildcard(last(explode('.', $name))); $defaults = $this->resourceDefaults; foreach ($this->getResourceMethods($defaults, $options) as $m) { $this->{'addResource'.ucfirst($m)}($name, $base, $controller, $options); } } /** * Add the relation get method for a resourceful route. * * @param string $name * @param string $base * @param string $controller * @param array $options * @return \Illuminate\Routing\Route */ protected function addResourceRelation($name, $base, $controller, $options) { $uri = $this->getResourceUri($name).'/{'.$base.'}'."/{relation}"; $action = $this->getResourceAction($name, $controller, 'relation', $options); return $this->router->get($uri, $action); } }
php
MIT
45e05076f8fc7918d70631369b02ed7168a6cb5d
2026-01-05T04:52:55.517023Z
false
Froiden/laravel-rest-api
https://github.com/Froiden/laravel-rest-api/blob/45e05076f8fc7918d70631369b02ed7168a6cb5d/src/Routing/ApiRouter.php
src/Routing/ApiRouter.php
<?php namespace Froiden\RestAPI\Routing; use Closure; use Froiden\RestAPI\Exceptions\ApiException; use Froiden\RestAPI\Middleware\ApiMiddleware; use Illuminate\Contracts\Container\Container; use Illuminate\Contracts\Events\Dispatcher; use Illuminate\Routing\ResourceRegistrar; use Illuminate\Routing\Router; class ApiRouter extends Router { protected $versions = []; /** * Route a resource to a controller. * * @param string $name * @param string $controller * @param array $options * @return void */ public function resource($name, $controller, array $options = []) { if ($this->container && $this->container->bound('Froiden\RestAPI\Routing\ApiResourceRegistrar')) { $registrar = $this->container->make('Froiden\RestAPI\Routing\ApiResourceRegistrar'); } else { $registrar = new ResourceRegistrar($this); } $registrar->register($name, $controller, $options); } public function version($versions, Closure $callback) { if (is_string($versions)) { $versions = [$versions]; } $this->versions = $versions; call_user_func($callback, $this); } /** * Add a route to the underlying route collection. * * @param array|string $methods * @param string $uri * @param \Closure|array|string|null $action * @return \Illuminate\Routing\Route */ public function addRoute($methods, $uri, $action) { // We do not keep routes in ApiRouter. Whenever a route is added, // we add it to Laravel's primary route collection $routes = app("router")->getRoutes(); $prefix = config("api.prefix"); if (empty($this->versions)) { if (($default = config("api.default_version")) !== null) { $versions = [$default]; } else { $versions = [null]; } } else { $versions = $this->versions; } // Add version prefix foreach ($versions as $version) { // Add ApiMiddleware to all routes $route = $this->createRoute($methods, $uri, $action); $route->middleware(ApiMiddleware::class); if ($version !== null) { $route->prefix($version); $route->name("." . $version); } if (!empty($prefix)) { $route->prefix($prefix); } // $routes->add($route); // Options route // $route = $this->createRoute(['OPTIONS'], $uri, ['uses' => '\Froiden\RestAPI\Routing\ApiRouter@returnRoute']); // $route->middleware(ApiMiddleware::class); // if ($version !== null) { // $route->prefix($version); // $route->name("." . $version); // } // if (!empty($prefix)) { // $route->prefix($prefix); // } $routes->add($route); } app("router")->setRoutes($routes); } public function returnRoute() { return []; } }
php
MIT
45e05076f8fc7918d70631369b02ed7168a6cb5d
2026-01-05T04:52:55.517023Z
false
Froiden/laravel-rest-api
https://github.com/Froiden/laravel-rest-api/blob/45e05076f8fc7918d70631369b02ed7168a6cb5d/src/Exceptions/UnauthorizedException.php
src/Exceptions/UnauthorizedException.php
<?php namespace Froiden\RestAPI\Exceptions; class UnauthorizedException extends ApiException { protected $statusCode = 403; protected $code = ErrorCodes::UNAUTHORIZED_EXCEPTION; protected $message = "Not authorized to perform this request"; }
php
MIT
45e05076f8fc7918d70631369b02ed7168a6cb5d
2026-01-05T04:52:55.517023Z
false
Froiden/laravel-rest-api
https://github.com/Froiden/laravel-rest-api/blob/45e05076f8fc7918d70631369b02ed7168a6cb5d/src/Exceptions/UnauthenticationException.php
src/Exceptions/UnauthenticationException.php
<?php namespace Froiden\RestAPI\Exceptions; class UnauthenticationException extends ApiException { protected $statusCode = 401; protected $code = ErrorCodes::UNAUTHENTICATION_EXCEPTION; protected $message = "Not authenticated to perform this request"; }
php
MIT
45e05076f8fc7918d70631369b02ed7168a6cb5d
2026-01-05T04:52:55.517023Z
false
Froiden/laravel-rest-api
https://github.com/Froiden/laravel-rest-api/blob/45e05076f8fc7918d70631369b02ed7168a6cb5d/src/Exceptions/ApiException.php
src/Exceptions/ApiException.php
<?php namespace Froiden\RestAPI\Exceptions; use Illuminate\Contracts\Support\Jsonable; class ApiException extends \Exception implements \JsonSerializable, Jsonable { /** * Response status code * * @var int */ protected $statusCode = 400; /** * Error code * * @var int */ protected $code = ErrorCodes::UNKNOWN_EXCEPTION; /** * Error message * * @var string */ protected $message = "An unknown error occurred"; public function __construct($message = null, $previous = null, $code = null, $statusCode = null, $innerError = null, $details = []) { if ($statusCode !== null) { $this->statusCode = $statusCode; } if ($code !== null) { $this->code = $code; } if ($innerError !== null) { $this->innerError = $innerError; } if (!empty($details)) { $this->details = $details; } if ($message == null) { parent::__construct($this->message, $this->code, $previous); } else { parent::__construct($message, $this->code, $previous); } } public function __toString() { return "ApiException (#{$this->getCode()}): {$this->getMessage()}"; } /** * Return the status code the response should be sent with * * @return int */ public function getStatusCode() { return $this->statusCode; } /** * Convert the exception to its JSON representation. * * @param int $options * @return string */ public function toJson($options = 0) { return json_encode($this->jsonSerialize(), $options); } /** * Specify data which should be serialized to JSON * @link http://php.net/manual/en/jsonserializable.jsonserialize.php * @return mixed data which can be serialized by <b>json_encode</b>, * which is a value of any type other than a resource. */ public function jsonSerialize() { $jsonArray = [ "message" => $this->getMessage(), "error" => [ "message" => $this->getMessage(), "code" => $this->getCode() ] ]; if (isset($this->details)) { $jsonArray["error"]["details"] = $this->details; } if (isset($this->innerError)) { $jsonArray["error"]["innererror"] = [ "code" => $this->innerError ]; } return $jsonArray; } }
php
MIT
45e05076f8fc7918d70631369b02ed7168a6cb5d
2026-01-05T04:52:55.517023Z
false
Froiden/laravel-rest-api
https://github.com/Froiden/laravel-rest-api/blob/45e05076f8fc7918d70631369b02ed7168a6cb5d/src/Exceptions/ErrorCodes.php
src/Exceptions/ErrorCodes.php
<?php namespace Froiden\RestAPI\Exceptions; class ErrorCodes { const REQUEST_PARSE_EXCEPTION = 100; const UNKNOWN_EXCEPTION = 1; const UNAUTHENTICATION_EXCEPTION = 401; const UNAUTHORIZED_EXCEPTION = 403; const VALIDATION_EXCEPTION = 422; const RESOURCE_NOT_FOUND_EXCEPTION = 404; const INNER_FILTER_NOT_FOUND = 1001; const INNER_INVALID_FILTER_DEFINITION = 1002; const INNER_UNKNOWN_FILED_EXCEPTION = 1003; const INNER_NOT_ALLOWED_TO_FILTER_ON_THIS_FIELD = 1004; const INNER_ORDERING_INVALID = 1005; const INNER_MAX_LIMIT = 1006; const INNER_INVALID_LIMIT = 1007; const INNER_RELATED_RESOURCE_NOT_EXISTS = 1010; }
php
MIT
45e05076f8fc7918d70631369b02ed7168a6cb5d
2026-01-05T04:52:55.517023Z
false
Froiden/laravel-rest-api
https://github.com/Froiden/laravel-rest-api/blob/45e05076f8fc7918d70631369b02ed7168a6cb5d/src/Exceptions/ValidationException.php
src/Exceptions/ValidationException.php
<?php namespace Froiden\RestAPI\Exceptions; class ValidationException extends ApiException { protected $statusCode = 422; protected $code = ErrorCodes::VALIDATION_EXCEPTION; protected $message = "Request could not be validated"; /** * Validation errors * * @var array */ private $errors = []; public function __construct($errors = []) { parent::__construct(); $this->details = $errors; } }
php
MIT
45e05076f8fc7918d70631369b02ed7168a6cb5d
2026-01-05T04:52:55.517023Z
false
Froiden/laravel-rest-api
https://github.com/Froiden/laravel-rest-api/blob/45e05076f8fc7918d70631369b02ed7168a6cb5d/src/Exceptions/RelatedResourceNotFoundException.php
src/Exceptions/RelatedResourceNotFoundException.php
<?php namespace Froiden\RestAPI\Exceptions; class RelatedResourceNotFoundException extends ApiException { protected $statusCode = 422; protected $code = ErrorCodes::VALIDATION_EXCEPTION; protected $innercode = ErrorCodes::INNER_RELATED_RESOURCE_NOT_EXISTS; protected $message = "Related resource not found"; }
php
MIT
45e05076f8fc7918d70631369b02ed7168a6cb5d
2026-01-05T04:52:55.517023Z
false
Froiden/laravel-rest-api
https://github.com/Froiden/laravel-rest-api/blob/45e05076f8fc7918d70631369b02ed7168a6cb5d/src/Exceptions/ResourceNotFoundException.php
src/Exceptions/ResourceNotFoundException.php
<?php namespace Froiden\RestAPI\Exceptions; class ResourceNotFoundException extends ApiException { protected $statusCode = 404; protected $code = ErrorCodes::RESOURCE_NOT_FOUND_EXCEPTION; protected $message = "Requested resource not found"; }
php
MIT
45e05076f8fc7918d70631369b02ed7168a6cb5d
2026-01-05T04:52:55.517023Z
false
Froiden/laravel-rest-api
https://github.com/Froiden/laravel-rest-api/blob/45e05076f8fc7918d70631369b02ed7168a6cb5d/src/Exceptions/Parse/NotAllowedToFilterOnThisFieldException.php
src/Exceptions/Parse/NotAllowedToFilterOnThisFieldException.php
<?php namespace Froiden\RestAPI\Exceptions\Parse; use Froiden\RestAPI\Exceptions\ApiException; use Froiden\RestAPI\Exceptions\ErrorCodes; class NotAllowedToFilterOnThisFieldException extends ApiException { protected $code = ErrorCodes::REQUEST_PARSE_EXCEPTION; protected $innerError = ErrorCodes::INNER_NOT_ALLOWED_TO_FILTER_ON_THIS_FIELD; protected $message = "Applying filter on one of the specified fields is not allowed"; }
php
MIT
45e05076f8fc7918d70631369b02ed7168a6cb5d
2026-01-05T04:52:55.517023Z
false
Froiden/laravel-rest-api
https://github.com/Froiden/laravel-rest-api/blob/45e05076f8fc7918d70631369b02ed7168a6cb5d/src/Exceptions/Parse/InvalidOrderingDefinitionException.php
src/Exceptions/Parse/InvalidOrderingDefinitionException.php
<?php namespace Froiden\RestAPI\Exceptions\Parse; use Froiden\RestAPI\Exceptions\ApiException; use Froiden\RestAPI\Exceptions\ErrorCodes; class InvalidOrderingDefinitionException extends ApiException { protected $code = ErrorCodes::REQUEST_PARSE_EXCEPTION; protected $innerError = ErrorCodes::INNER_ORDERING_INVALID; protected $message = "Ordering defined incorrectly"; }
php
MIT
45e05076f8fc7918d70631369b02ed7168a6cb5d
2026-01-05T04:52:55.517023Z
false
Froiden/laravel-rest-api
https://github.com/Froiden/laravel-rest-api/blob/45e05076f8fc7918d70631369b02ed7168a6cb5d/src/Exceptions/Parse/UnknownFieldException.php
src/Exceptions/Parse/UnknownFieldException.php
<?php namespace Froiden\RestAPI\Exceptions\Parse; use Froiden\RestAPI\Exceptions\ApiException; use Froiden\RestAPI\Exceptions\ErrorCodes; class UnknownFieldException extends ApiException { protected $code = ErrorCodes::REQUEST_PARSE_EXCEPTION; protected $innerError = ErrorCodes::INNER_UNKNOWN_FILED_EXCEPTION; protected $message = "One of the specified fields does not exist"; }
php
MIT
45e05076f8fc7918d70631369b02ed7168a6cb5d
2026-01-05T04:52:55.517023Z
false
Froiden/laravel-rest-api
https://github.com/Froiden/laravel-rest-api/blob/45e05076f8fc7918d70631369b02ed7168a6cb5d/src/Exceptions/Parse/MaxLimitException.php
src/Exceptions/Parse/MaxLimitException.php
<?php namespace Froiden\RestAPI\Exceptions\Parse; use Froiden\RestAPI\Exceptions\ApiException; use Froiden\RestAPI\Exceptions\ErrorCodes; class MaxLimitException extends ApiException { protected $code = ErrorCodes::REQUEST_PARSE_EXCEPTION; protected $innerError = ErrorCodes::INNER_MAX_LIMIT; protected $message = "Requested more records than maximum limit in single request"; }
php
MIT
45e05076f8fc7918d70631369b02ed7168a6cb5d
2026-01-05T04:52:55.517023Z
false
Froiden/laravel-rest-api
https://github.com/Froiden/laravel-rest-api/blob/45e05076f8fc7918d70631369b02ed7168a6cb5d/src/Exceptions/Parse/InvalidLimitException.php
src/Exceptions/Parse/InvalidLimitException.php
<?php namespace Froiden\RestAPI\Exceptions\Parse; use Froiden\RestAPI\Exceptions\ApiException; use Froiden\RestAPI\Exceptions\ErrorCodes; class InvalidLimitException extends ApiException { protected $statusCode = 422; protected $code = ErrorCodes::REQUEST_PARSE_EXCEPTION; protected $innercode = ErrorCodes::INNER_INVALID_LIMIT; protected $message = "Limit cannot be negative or zero"; }
php
MIT
45e05076f8fc7918d70631369b02ed7168a6cb5d
2026-01-05T04:52:55.517023Z
false
Froiden/laravel-rest-api
https://github.com/Froiden/laravel-rest-api/blob/45e05076f8fc7918d70631369b02ed7168a6cb5d/src/Exceptions/Parse/InvalidFilterDefinitionException.php
src/Exceptions/Parse/InvalidFilterDefinitionException.php
<?php namespace Froiden\RestAPI\Exceptions\Parse; use Froiden\RestAPI\Exceptions\ApiException; use Froiden\RestAPI\Exceptions\ErrorCodes; class InvalidFilterDefinitionException extends ApiException { protected $code = ErrorCodes::REQUEST_PARSE_EXCEPTION; protected $innerError = ErrorCodes::INNER_INVALID_FILTER_DEFINITION; protected $message = "Filter defined incorrectly"; }
php
MIT
45e05076f8fc7918d70631369b02ed7168a6cb5d
2026-01-05T04:52:55.517023Z
false
Froiden/laravel-rest-api
https://github.com/Froiden/laravel-rest-api/blob/45e05076f8fc7918d70631369b02ed7168a6cb5d/src/Exceptions/Parse/FilterNotFoundException.php
src/Exceptions/Parse/FilterNotFoundException.php
<?php namespace Froiden\RestAPI\Exceptions\Parse; use Froiden\RestAPI\Exceptions\ApiException; use Froiden\RestAPI\Exceptions\ErrorCodes; class FilterNotFoundException extends ApiException { protected $code = ErrorCodes::REQUEST_PARSE_EXCEPTION; protected $innerError = ErrorCodes::INNER_FILTER_NOT_FOUND; protected $message = "Requested filter not found"; }
php
MIT
45e05076f8fc7918d70631369b02ed7168a6cb5d
2026-01-05T04:52:55.517023Z
false
Froiden/laravel-rest-api
https://github.com/Froiden/laravel-rest-api/blob/45e05076f8fc7918d70631369b02ed7168a6cb5d/src/Facades/ApiRoute.php
src/Facades/ApiRoute.php
<?php namespace Froiden\RestAPI\Facades; use Froiden\RestAPI\Routing\ApiRouter; use Illuminate\Support\Facades\Facade; class ApiRoute extends Facade { /** * Get the registered name of the component. * * @return string */ protected static function getFacadeAccessor() { return ApiRouter::class; } }
php
MIT
45e05076f8fc7918d70631369b02ed7168a6cb5d
2026-01-05T04:52:55.517023Z
false
Froiden/laravel-rest-api
https://github.com/Froiden/laravel-rest-api/blob/45e05076f8fc7918d70631369b02ed7168a6cb5d/src/ExtendedRelations/BelongsToMany.php
src/ExtendedRelations/BelongsToMany.php
<?php namespace Froiden\RestAPI\ExtendedRelations; use Illuminate\Database\Eloquent\Relations\BelongsToMany as LaravelBelongsToMany; class BelongsToMany extends LaravelBelongsToMany { public function getRelatedKeyName() { return $this->relatedKey ?: 'id'; } }
php
MIT
45e05076f8fc7918d70631369b02ed7168a6cb5d
2026-01-05T04:52:55.517023Z
false
Froiden/laravel-rest-api
https://github.com/Froiden/laravel-rest-api/blob/45e05076f8fc7918d70631369b02ed7168a6cb5d/src/Middleware/ApiMiddleware.php
src/Middleware/ApiMiddleware.php
<?php namespace Froiden\RestAPI\Middleware; use Closure; use Froiden\RestAPI\ApiResponse; use Froiden\RestAPI\Exceptions\UnauthorizedException; use Illuminate\Support\Str; use Symfony\Component\HttpFoundation\StreamedResponse; class ApiMiddleware { public function handle($request, Closure $next) { // Add CORS headers $response = $next($request); if ($response->getStatusCode() == 403 && ($response->getContent() == "Forbidden" || Str::contains($response->getContent(), ['HttpException', 'authorized']))) { $response = ApiResponse::exception(new UnauthorizedException()); } if (config("api.cors") && !$response instanceof StreamedResponse) { $response->header('Access-Control-Allow-Origin', '*') ->header('Access-Control-Allow-Methods', 'GET, POST, PUT, PATCH, DELETE, OPTIONS') ->header('Access-Control-Allow-Headers', implode(',', config('api.cors_headers'))); } return $response; } }
php
MIT
45e05076f8fc7918d70631369b02ed7168a6cb5d
2026-01-05T04:52:55.517023Z
false
Froiden/laravel-rest-api
https://github.com/Froiden/laravel-rest-api/blob/45e05076f8fc7918d70631369b02ed7168a6cb5d/src/Providers/ApiServiceProvider.php
src/Providers/ApiServiceProvider.php
<?php namespace Froiden\RestAPI\Providers; use Froiden\RestAPI\Handlers\ApiExceptionHandler; use Froiden\RestAPI\Routing\ApiResourceRegistrar; use Froiden\RestAPI\Routing\ApiRouter; use Illuminate\Container\Container; use Illuminate\Events\Dispatcher; use Illuminate\Routing\RouteCollection; use Illuminate\Routing\Router; use Illuminate\Routing\UrlGenerator; use Illuminate\Support\ServiceProvider; class ApiServiceProvider extends ServiceProvider { public function boot() { $this->publishes([ __DIR__.'/../api.php' => config_path("api.php"), ]); } /** * Register the service provider. * * @return void */ public function register() { $this->registerRouter(); $this->registerExceptionHandler(); $this->mergeConfigFrom( __DIR__.'/../api.php', 'api' ); } public function registerRouter() { $this->app->singleton( ApiRouter::class, function ($app) { return new ApiRouter($app->make(Dispatcher::class), $app->make(Container::class)); } ); $this->app->singleton( ApiResourceRegistrar::class, function ($app) { return new ApiResourceRegistrar($app->make(ApiRouter::class)); } ); } public function registerExceptionHandler() { $this->app->singleton( \Illuminate\Contracts\Debug\ExceptionHandler::class, ApiExceptionHandler::class ); } }
php
MIT
45e05076f8fc7918d70631369b02ed7168a6cb5d
2026-01-05T04:52:55.517023Z
false
Froiden/laravel-rest-api
https://github.com/Froiden/laravel-rest-api/blob/45e05076f8fc7918d70631369b02ed7168a6cb5d/src/Handlers/ApiExceptionHandler.php
src/Handlers/ApiExceptionHandler.php
<?php namespace Froiden\RestAPI\Handlers; use App\Exceptions\Handler; use Froiden\RestAPI\ApiResponse; use Froiden\RestAPI\Exceptions\ApiException; use Froiden\RestAPI\Exceptions\Parse\UnknownFieldException; use Froiden\RestAPI\Exceptions\UnauthenticatedException; use Froiden\RestAPI\Exceptions\UnauthenticationException; use Froiden\RestAPI\Exceptions\UnauthorizedException; use Froiden\RestAPI\Exceptions\ValidationException; use Illuminate\Auth\AuthenticationException; use Illuminate\Database\Eloquent\ModelNotFoundException; use Illuminate\Database\QueryException; use Illuminate\Http\Exceptions\HttpResponseException; use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; use Throwable; class ApiExceptionHandler extends Handler { public function render($request, Throwable $e) { $debug = config('app.debug'); $prefix = config("api.prefix"); // Check if prefix is set and use that debug // This is done to prevent default error message show in otherwise application // which are not using the api if ($request->is($prefix . '/*')) { // When the user is not authenticated or logged show this message with status code 401 if ($e instanceof AuthenticationException) { return ApiResponse::exception(new UnauthenticationException()); } if ($e instanceof HttpResponseException || $e instanceof \Illuminate\Validation\ValidationException) { if ($e->status == 403) { return ApiResponse::exception(new UnauthorizedException()); } return ApiResponse::exception(new ValidationException($e->errors())); } if ($e instanceof NotFoundHttpException) { return ApiResponse::exception(new ApiException('This api endpoint does not exist', null, 404, 404, 2005, [ 'url' => request()->url() ])); } if ($e instanceof ModelNotFoundException) { return ApiResponse::exception(new ApiException('Requested resource not found', null, 404, 404, null, [ 'url' => request()->url() ])); } if ($e instanceof ApiException) { return ApiResponse::exception($e); } if ($e instanceof QueryException) { if ($e->getCode() == "422") { preg_match("/Unknown column \\'([^']+)\\'/", $e->getMessage(), $result); if (!isset($result[1])) { return ApiResponse::exception(new UnknownFieldException(null, $e)); } $parts = explode(".", $result[1]); $field = count($parts) > 1 ? $parts[1] : $result; return ApiResponse::exception(new UnknownFieldException("Field '" . $field . "' does not exist", $e)); } } // When Debug is on move show error here $message = null; if($debug){ $response['trace'] = $e->getTrace(); $response['code'] = $e->getCode(); $message = $e->getMessage(); } return ApiResponse::exception(new ApiException($message, null, 500, 500, null, $response)); } return parent::render($request, $e); } }
php
MIT
45e05076f8fc7918d70631369b02ed7168a6cb5d
2026-01-05T04:52:55.517023Z
false
Froiden/laravel-rest-api
https://github.com/Froiden/laravel-rest-api/blob/45e05076f8fc7918d70631369b02ed7168a6cb5d/tests/DummyUserTest.php
tests/DummyUserTest.php
<?php use Froiden\RestAPI\Tests\TestCase; use Illuminate\Foundation\Testing\DatabaseMigrations; use Illuminate\Foundation\Testing\DatabaseTransactions; use Illuminate\Foundation\Testing\WithoutMiddleware; use Illuminate\Routing\Router; class DummyUserTest extends TestCase { /** * Test User Index Page. * * @return void */ public function testUserIndex() { // Send Simple Index Request $response = $this->call('GET', '/dummyUser'); $this->assertEquals(200, $response->status()); } public function testUserIndexWithFields() { $response = $this->call('GET', '/dummyUser', [ 'fields' => "id,name,email,age", ]); $this->assertEquals(200, $response->status()); } public function testOneToOneRelationWithFieldsParameter() { $response = $this->call('GET', '/dummyUser', [ 'fields' => "id,name,email,phone", ]); $responseContent = json_decode($response->getContent(), true); $this->assertNotNull($responseContent["data"]["0"]["phone"]); $this->assertEquals(200, $response->status()); } public function testOneToManyRelationWithFieldsParameter() { // Get Data With Related Post $response = $this->call('GET', '/dummyUser', [ 'fields' => "id,name,email,posts", ]); $responseContent = json_decode($response->getContent(), true); $this->assertNotEmpty($responseContent["data"]["0"]["posts"]); $this->assertEquals(200, $response->status()); // Get Data With User Comments on Post $response = $this->call('GET', '/dummyUser', [ 'fields' => "id,name,email,comments", ]); $responseContent = json_decode($response->getContent(), true); $this->assertNotEmpty($responseContent["data"]["0"]["comments"]); $this->assertEquals(200, $response->status()); } public function testUserIndexWithFilters() { $createFactory = \Illuminate\Database\Eloquent\Factory::construct(\Faker\Factory::create(), base_path() . '/laravel-rest-api/tests/Factories'); $userId = $createFactory->of(\Froiden\RestAPI\Tests\Models\DummyUser::class)->create(); // Use "filters" to modify The result $response = $this->call('GET', '/dummyUser', [ 'filters' => 'age lt 7', ]); $this->assertEquals(200, $response->status()); // With 'lk' operator $response = $this->call('GET', '/dummyUser', [ 'fields' => "id,name", 'filters' => 'name lk "%'.$userId->name.'%"', ]); $this->assertEquals(200, $response->status()); } public function testUserIndexWithLimit() { // Use "Limit" to get required number of result $response = $this->call('GET', '/dummyUser', [ 'limit' => '5', ]); $this->assertEquals(200, $response->status()); } public function testUserIndexWithsOrderParameter() { // Define order of result $response = $this->call('GET', '/dummyUser', [ 'order' => "id desc", ]); $this->assertEquals(200, $response->status()); $response = $this->call('GET', '/dummyUser', [ 'order' => "id asc", ]); $this->assertEquals(200, $response->status()); } public function testUserShowFunction() { $user = \Froiden\RestAPI\Tests\Models\DummyUser::all()->random(); $response = $this->call('GET', '/dummyUser/'.$user->id); $this->assertEquals(200, $response->status()); } public function testShowCommentsByUserRelationsEndpoint() { $user = \Froiden\RestAPI\Tests\Models\DummyUser::all()->random(); $post = \Froiden\RestAPI\Tests\Models\DummyPost::all()->random(); $createFactory = \Illuminate\Database\Eloquent\Factory::construct(\Faker\Factory::create(), base_path() . '/laravel-rest-api/tests/Factories'); $comment = $createFactory->of(\Froiden\RestAPI\Tests\Models\DummyComment::class)->create([ 'comment' => "Dummy Comments", 'user_id' => $user->id, 'post_id' => $post->id ]); $response = $this->call('GET', '/dummyUser/'.$user->id.'/comments'); $responseContent = json_decode($response->getContent(), true); $this->assertNotEmpty($responseContent["data"]); $this->assertEquals(200, $response->status()); } public function testShowPostsByUserRelationsEndpoint() { //region Insert Dummy Data $user = \Froiden\RestAPI\Tests\Models\DummyUser::all()->random(); $createFactory = \Illuminate\Database\Eloquent\Factory::construct(\Faker\Factory::create(), base_path() . '/laravel-rest-api/tests/Factories'); $createFactory->of(\Froiden\RestAPI\Tests\Models\DummyPost::class)->create([ 'post' => "dummy POst", 'user_id' => $user->id, ]); //endregion $response = $this->call('GET', '/dummyUser/'.$user->id.'/posts'); $responseContent = json_decode($response->getContent(), true); $this->assertNotEmpty($responseContent["data"]); $this->assertEquals(200, $response->status()); } public function testUserStore() { $response = $this->call('POST', '/dummyUser', [ 'name' => "Dummy User", 'email' => "dummy@test.com", 'age' => 25 ]); $this->assertEquals(200, $response->status()); } public function testUserUpdate() { $user = \Froiden\RestAPI\Tests\Models\DummyUser::all()->random(); $response = $this->call('PUT', '/dummyUser/'.$user->id, [ 'name' => "Dummy1 User", 'email' => "dummy2@test.com", 'age' => 25, ]); $this->assertEquals(200, $response->status()); } /** * Test User Delete Function. * * @return void */ public function testUserDelete() { $user = \Froiden\RestAPI\Tests\Models\DummyUser::all()->random(); $response = $this->call('DELETE', '/dummyUser/'.$user->id); $this->assertEquals(200, $response->status()); } }
php
MIT
45e05076f8fc7918d70631369b02ed7168a6cb5d
2026-01-05T04:52:55.517023Z
false
Froiden/laravel-rest-api
https://github.com/Froiden/laravel-rest-api/blob/45e05076f8fc7918d70631369b02ed7168a6cb5d/tests/PaginationTest.php
tests/PaginationTest.php
<?php use Illuminate\Foundation\Testing\WithoutMiddleware; use Illuminate\Foundation\Testing\DatabaseMigrations; use Illuminate\Foundation\Testing\DatabaseTransactions; use Froiden\RestAPI\Tests\TestCase; class PaginationTest extends TestCase { /** * Test User Index Page. * * @return void **/ public function testPagination() { // Pagination set offset = "5" or limit ="3" $response = $this->call('GET', '/dummyUser', [ 'order' => 'id asc', 'offset' => '5', 'limit' => '2' ]); $this->assertEquals(200, $response->status()); // Pagination set offset = "1" or limit ="1" $response = $this->call('GET', '/dummyUser', [ 'order' => 'id asc', 'offset' => '1', 'limit' => '1' ]); $this->assertEquals(200, $response->status()); // Pagination set offset = "5" or limit ="3" $response = $this->call('GET', '/dummyUser', [ 'order' => 'id asc', 'offset' => '5', 'limit' => '-2' ]); $this->assertNotEquals(200, $response->status()); } }
php
MIT
45e05076f8fc7918d70631369b02ed7168a6cb5d
2026-01-05T04:52:55.517023Z
false
Froiden/laravel-rest-api
https://github.com/Froiden/laravel-rest-api/blob/45e05076f8fc7918d70631369b02ed7168a6cb5d/tests/TestCase.php
tests/TestCase.php
<?php namespace Froiden\RestAPI\Tests; use Froiden\RestAPI\Facades\ApiRoute; use Froiden\RestAPI\Routing\ApiRouter; use Froiden\RestAPI\Tests\Controllers\CommentController; use Froiden\RestAPI\Tests\Controllers\PostController; use Froiden\RestAPI\Tests\Controllers\UserController; use Froiden\RestAPI\Tests\Models\DummyComment; use Froiden\RestAPI\Tests\Models\DummyPhone; use Froiden\RestAPI\Tests\Models\DummyPost; use Froiden\RestAPI\Tests\Models\DummyUser; use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; /** * Class TestCase * @package Froiden\RestAPI\Tests */ class TestCase extends \Illuminate\Foundation\Testing\TestCase { /** * The base URL to use while testing the application. * * @var string */ protected $baseUrl = 'http://localhost/api/v1'; /** * */ public function setUp() { parent::setUp(); \DB::statement("SET GLOBAL sql_mode=(SELECT REPLACE(@@sql_mode,'ONLY_FULL_GROUP_BY',''));"); $this->createTables(); $this->seedDummyData(); $this->app[ApiRouter::class]->resource('/dummyUser', UserController::class); $this->app[ApiRouter::class]->resource('/dummyPost', PostController::class); $this->app[ApiRouter::class]->resource('/dummyComment', CommentController::class); } /** * Creates the application. * * @return \Illuminate\Foundation\Application */ public function createApplication() { $app = require __DIR__.'/../../bootstrap/app.php'; $app->make(\Illuminate\Contracts\Console\Kernel::class)->bootstrap(); return $app; } /** * This is the description for the function below. * * Insert dummy data into tables * * @return void */ public function seedDummyData() { $factory = \Illuminate\Database\Eloquent\Factory::construct(\Faker\Factory::create(), base_path() . '/laravel-rest-api/tests/Factories'); \DB::beginTransaction(); for($i = 0; $i < 10; $i++) { $user = $factory->of(DummyUser::class)->create(); $factory->of(DummyPhone::class)->create( [ 'user_id' => $user->id ] ); $post = $factory->of(DummyPost::class)->create( [ 'user_id' => $user->id, ] ); $factory->of(DummyComment::class)->create( [ 'post_id' => $post->id, 'user_id' => $user->id, ] ); } \DB::commit(); } /** * This is the description for the function below. * * Create a tables * * @return void */ public function createTables() { Schema::dropIfExists('dummy_comments'); Schema::dropIfExists('dummy_posts'); Schema::dropIfExists('dummy_phones'); Schema::dropIfExists('dummy_users'); Schema::create('dummy_users', function (Blueprint $table) { $table->increments('id'); $table->string('name'); $table->string('email', 100)->unique(); $table->integer('age'); $table->timestamps(); }); Schema::create('dummy_phones', function (Blueprint $table) { $table->increments('id'); $table->string('name'); $table->string('modal_no'); $table->unsignedInteger('user_id'); $table->foreign('user_id')->references('id')->on('dummy_users') ->onUpdate('CASCADE') ->onDelete('CASCADE'); $table->timestamps(); }); Schema::create('dummy_posts', function (Blueprint $table) { $table->increments('id'); $table->string('post'); $table->unsignedInteger('user_id'); $table->foreign('user_id')->references('id')->on('dummy_users') ->onUpdate('CASCADE') ->onDelete('CASCADE'); $table->timestamps(); }); Schema::create('dummy_comments', function (Blueprint $table) { $table->increments('id'); $table->string('comment'); $table->unsignedInteger('user_id'); $table->foreign('user_id')->references('id')->on('dummy_users') ->onUpdate('CASCADE') ->onDelete('CASCADE'); $table->unsignedInteger('post_id'); $table->foreign('post_id')->references('id')->on('dummy_posts') ->onUpdate('CASCADE') ->onDelete('CASCADE'); $table->timestamps(); }); } }
php
MIT
45e05076f8fc7918d70631369b02ed7168a6cb5d
2026-01-05T04:52:55.517023Z
false
Froiden/laravel-rest-api
https://github.com/Froiden/laravel-rest-api/blob/45e05076f8fc7918d70631369b02ed7168a6cb5d/tests/Controllers/PostController.php
tests/Controllers/PostController.php
<?php namespace Froiden\RestAPI\Tests\Controllers; use Froiden\RestAPI\ApiController; use Froiden\RestAPI\Tests\Models\DummyPost; class PostController extends ApiController { protected $model = DummyPost::class; }
php
MIT
45e05076f8fc7918d70631369b02ed7168a6cb5d
2026-01-05T04:52:55.517023Z
false
Froiden/laravel-rest-api
https://github.com/Froiden/laravel-rest-api/blob/45e05076f8fc7918d70631369b02ed7168a6cb5d/tests/Controllers/CommentController.php
tests/Controllers/CommentController.php
<?php namespace Froiden\RestAPI\Tests\Controllers; use Froiden\RestAPI\ApiController; use Froiden\RestAPI\Tests\Models\DummyComment; class CommentController extends ApiController { protected $model = DummyComment::class; }
php
MIT
45e05076f8fc7918d70631369b02ed7168a6cb5d
2026-01-05T04:52:55.517023Z
false
Froiden/laravel-rest-api
https://github.com/Froiden/laravel-rest-api/blob/45e05076f8fc7918d70631369b02ed7168a6cb5d/tests/Controllers/UserController.php
tests/Controllers/UserController.php
<?php namespace Froiden\RestAPI\Tests\Controllers; use Froiden\RestAPI\ApiController; use Froiden\RestAPI\Tests\Models\DummyUser; class UserController extends ApiController { protected $model = DummyUser::class; }
php
MIT
45e05076f8fc7918d70631369b02ed7168a6cb5d
2026-01-05T04:52:55.517023Z
false