### file: /share_imcat/core/glib/glbDBObj.php config = empty($config) ? self::getCfg() : $config; $this->otps['field'] = '*';//默认查询字段 $this->driver = $this->config['db_driver']; $this->pre = $this->config['db_prefix'];//数据表前缀 $this->ext = $this->config['db_suffix'];//数据表后缀 } //连接数据库 function connect(){ if(!is_object($this->db)){ //$this->db不是对象,则连接数据库 $file = 'db'.ucfirst($this->driver); require_once DIR_IMCAT."/adpt/dbdrv/{$file}.php"; $class = "\\imcat\\$file"; $this->db = new $class();//连接数据库 $this->runTimer(); $this->db->connect($this->config); $this->runTimer('connect'); } } //执行时间分析 function runTimer($mode=0){ global $_cbase; if(!$mode){ $_cbase['run']['qstart'] = microtime(1); //记录Start return; }else{ $run_one = microtime(1)-$_cbase['run']['qstart']; $_cbase['run']['qtime'] += $run_one; $_cbase['run']['query']++; $loger = $this->runChkbug($mode); if(empty($loger)) return; } $tpl = $_cbase['run']['tplname']; if($_cbase['debug']['db_sql']=='db'){ $info = basDebug::bugInfo(); $sql = basReq::in($this->sql); $used = 1000*$run_one; $run = $_cbase['run']; $kid = basKeyid::kidTemp().$_cbase['run']['query']; $vals = "'$kid','$sql','$used','{$info['vp']}','$tpl','','{$run['stamp']}'"; $this->db->run("INSERT INTO ".$this->table('logs_dbsql',2)."(kid,`sql`,used,page,tpl,tag,atime)VALUES($vals)"); }elseif(!empty($_cbase['debug']['db_sql'])){ $fmt = $_cbase['debug']['db_sql']; $file = date($fmt).".dbsql"; basDebug::bugLogs('dbobj',$this->sql,$file,'file'); } } function runChkbug($mode){ global $_cbase; if(!strpos($_cbase['debug']['db_acts'],$mode)) return 0; $indefine = 0; foreach($_cbase['debug']['db_area'] as $key){ if(defined($key)){ $indefine = 1; break; } } return $indefine; } //回调方法,连贯操作的实现 function __call($method, $args) { $method = strtolower($method); if(in_array($method,array('field','data','where','groups','having','order','limit','cache'))){ $this->otps[$method] = $args[0]; //接收数据 return $this; //返回对象,连贯查询 }else{ glbError::show($method.':No Found.'); } } //设置表,$nofix为true的时候,不加上默认的表前缀 function table($table, $nofix=false){ $full = '`'.$this->pre.$table.$this->ext.'`'; if($nofix===2){ return $full; }elseif($nofix){ $this->otps['table'] = '`'.$table.'`'; }else{ $this->otps['bare_tab'] = $table; $this->otps['table'] = $full; } return $this; } //执行原生sql语句,如果sql是查询语句,返回二维数组 function query($sql){ $this->sql = $sql; //判断当前的sql是否是查询语句 if(strpos(trim(strtolower($sql)),'select')===0){ $this->runTimer(); $data = $this->db->arr($this->sql); $this->runTimer('qSelect'); return $data; }else{ //不是查询条件,执行之后,直接返回 $query = $this->run($this->sql,'qOther'); return $query; } } //执行sql语句 function run($sql, $act=''){ global $_cbase; $this->sql = $sql; $this->runTimer(); $re = $this->db->run($this->sql); $this->runTimer($act); return $re; } //统计行数 function count(){ $table = $this->otps['table'];//当前表 $field = 'count(*)';//查询的字段 $where = $this->_parseCond();//条件 $this->sql="SELECT $field FROM $table $where"; $this->runTimer(); $re = $this->db->val($this->sql); $this->runTimer('count'); return $re; } //只查询一条信息,返回一维数组 function find(){ $table = $this->otps['table'];//当前表 $field = $this->otps['field'];//查询的字段 $this->otps['limit']=1;//限制只查询一条数据 $where = $this->_parseCond();//条件 $this->otps['field']='*';//设置下一次查询时,字段的默认值 $this->sql="SELECT $field FROM $table $where"; $data = array(); $this->runTimer(); $data = $this->db->row($this->sql); $this->runTimer('find'); return $data; } //查询多条信息,返回数组 function select(){ $table = $this->otps['table'];//当前表 $field = $this->otps['field'];//查询的字段 $where = $this->_parseCond();//条件 $this->otps['field'] = '*';//设置下一次查询时,字段的默认值 $this->sql = "SELECT $field FROM $table $where"; $data = array(); $this->runTimer(); $data = $this->db->arr($this->sql); $this->runTimer('select'); return $data; } //插入数据 function insert($log='a') { $table = $this->otps['table'];//当前表 $data = $this->_parseData('add',$log);//要插入的数据 $this->sql = "INSERT INTO $table $data"; $this->run($this->sql,'insert'); if($this->db->affRows){ $id = $this->db->lastID; return empty($id)?$this->db->affRows:$id; } return false; } //替换数据 function replace($log='a') { $table = $this->otps['table'];//当前表 $data = $this->_parseData('add',$log);//要插入的数据 $this->sql="REPLACE INTO $table $data" ; $this->run($this->sql,'replace'); if($this->db->affRows){ return $this->db->lastID; } return false; } //修改更新 function update($log='e'){ $table = $this->otps['table'];//当前表 $data = $this->_parseData('save',$log);//要更新的数据 $where = $this->_parseCond();//更新条件 if(empty($where)) return false; //修改条件为空时,则返回false,避免不小心将整个表数据修改了 $this->sql = "UPDATE $table SET $data $where" ; $this->run($this->sql,'update'); return $this->db->affRows; } //删除 function delete(){ $table = $this->otps['table'];//当前表 $where = $this->_parseCond();//条件 if(empty($where)) return false; //删除条件为空时,则返回false,避免数据不小心被全部删除 $this->sql = "DELETE FROM $table $where"; $this->run($this->sql,'delete'); return $this->db->affRows; } // 取得数据表的字段信息 function fields($tab){ $tab = is_array($tab) ? $tab[0] : $tab; $this->runTimer(); $a = $this->db->fields("$this->pre$tab$this->ext"); $this->runTimer('fields'); return $a; } // 取得数据库的表信息 function tables($info=0){ $this->runTimer(); $a = $info ? $this->db->tabinfo() : $this->db->tables(); $this->runTimer('tables'); $tab = array(); foreach($a as $v){ if($info){ $v['Name'] = str_replace(array("($this->pre","$this->ext)"),'',"({$v['Name']})"); if(($this->pre && strstr($v['Name'],'(')) || ($this->ext && strpos($v['Name'],')'))) continue; $tab[] = $v; }else{ $table = str_replace(array("($this->pre","$this->ext)"),'',"($v)"); if(($this->pre && strstr($table,'(')) || ($this->ext && strpos($table,')'))) continue; $tab[] = $table; } } return $tab; } // 取得创建表sql function create($tab){ $this->runTimer(); $a = $this->db->create("{$this->pre}$tab{$this->ext}"); $this->runTimer('create'); return $a; } //返回sql语句 function getSql(){ return $this->sql; } //返回quoteSql语句 function quoteSql($sql){ return $this->db->quoteSql($sql); } //解析数据,添加数据时$type=add,更新数据时$type=save public function _parseData($type, $log='') { if(empty($this->otps['data'])){ die("Error, Null-Data!"); } //如果数据是字符串,直接返回 if(is_string($this->otps['data'])){ return $this->otps['data']; } $arfix = array('advs_','base','bext','coms_','docs_','types','users'); if($log && in_array(substr($this->otps['bare_tab'],0,5), $arfix)){ $dlog = basSql::logData($log); $this->otps['data'] = array_merge($dlog, $this->otps['data']); } switch($type){ case 'add': $data=array(); $data['key'] = ""; $data['value'] = ""; foreach($this->otps['data'] as $key=>$value){ $data['key'] .= "`$key`,"; $data['value'] .= "'$value',"; } $data['key'] = substr($data['key'], 0,-1);//去除后面的逗号 $data['value'] = substr($data['value'], 0,-1);//去除后面的逗号 return " (".$data['key'].") VALUES (".$data['value'].") "; break; case 'save': $data = ""; foreach($this->otps['data'] as $key=>$value){ $data .= "`$key`='$value',"; } $data = substr($data, 0,-1); //去除后面的逗号 return $data; break; default: return false; } } //解析sql查询条件 public function _parseCond() { $cond = ""; //解析where()方法 if(!empty($this->otps['where'])){ $cond = " WHERE "; if(is_string($this->otps['where'])){ $cond .= $this->otps['where']; }else if(is_array($this->otps['where'])){ foreach($this->otps['where'] as $key=>$value){ $cond .= " `$key`='$value' AND "; } $cond = substr($cond, 0,-4); }else{ $cond = ""; } unset($this->otps['where']);//清空$this->otps['where']数据 } if(!empty($this->otps['groups'])&&is_string($this->otps['groups'])){ $cond .= " GROUP BY ".$this->otps['groups']; unset($this->otps['groups']); } if(!empty($this->otps['having'])&&is_string($this->otps['having'])){ $cond .= " HAVING ".$this->otps['having']; unset($this->otps['having']); } if(!empty($this->otps['order'])&&is_string($this->otps['order'])){ $cond .= " ORDER BY ".$this->otps['order']; unset($this->otps['order']); } if(!empty($this->otps['limit'])&&(is_string($this->otps['limit'])||is_numeric($this->otps['limit']))){ $cond .= " LIMIT ".$this->otps['limit']; unset($this->otps['limit']); } if(empty($cond)) return ""; return $cond; } // static function dbObj($config=array(), $catch=0){ $dbcfg = self::getCfg(); if(empty($config)){ $key = 'db0_main'; }elseif(is_string($config)){ // `user` $key = $config; $config = isset($dbcfg[$key]) ? $dbcfg[$key] : $dbcfg; $key = isset($dbcfg[$key]) ? "db1_$key" : 'db0_main'; }else{ // array() $config = array_merge($dbcfg, $config); $key = 'dba_'.$config['db_host'].'_'.$config['db_name']; } $key .= $catch; if(empty(self::$uobj[$key])){ $class = $catch ? '\\imcat\\glbDBCache' : '\\imcat\\glbDBObj'; self::$uobj[$key] = new $class($config); self::$uobj[$key]->connect($config); } return self::$uobj[$key]; } static function getCfg($key=''){ static $dbcfg; if(empty($dbcfg)){ require DIR_ROOT.'/cfgs/boot/cfg_db.php'; $dbcfg = $_cfgs; } return ($key && isset($dbcfg[$key])) ? $dbcfg[$key] : $dbcfg; } } ### file: /share_imcat/core/glib/glbError.php detail($erCode, $erMsg, $erFile, $erLine); $this->dtrace(); $this->errView(); } //detail protected function detail($erCode=0, $erMsg='', $erFile='', $erLine=0) { if(is_array($erMsg)){ $erStr = implode("
", $erMsg); $this->erMsg = basDebug::hidInfo($erStr, 1); $this->erCode = $erCode; }elseif(is_object($erCode)){ $this->erMsg = $erCode->getMessage(); $this->erFile = $erCode->getFile(); $this->erLine = $erCode->getLine(); //$this->trace = $erCode; $this->erCode = -24; }elseif(!empty($erFile)){ $this->erMsg = $erMsg; $this->erCode = $erCode; $this->erFile = $erFile; $this->erLine = $erLine; }elseif(!empty($erMsg)){ $this->erMsg = $erMsg; $this->erCode = $erCode; }else{ $err = error_get_last(); if(!empty($err)){ $this->erMsg = $err['message']; $this->erFile = $err['file']; $this->erLine = $err['line']; $this->erCode = $err['type']; } } } //获取trace信息 protected function dtrace() { $trace = empty($this->trace) ? $this->getTrace() : $this->trace; $tInfo = []; foreach($trace as $t) { $class = isset($t['class']) ? $t['class'] : ''; $type = isset($t['type']) ? $t['type'] : ''; $function = isset($t['function']) ? $t['function'] : ''; $tInfo[] = @$t['file'] . ' (' . @$t['line'] . ') ' . $class . $type . $function; } $this->trace = $tInfo; } // 输出错误信息 protected function errView(){ global $_cbase; // sLevel,message,title,traceInfo:为兼容旧模板 $erCode = $sLevel = empty($this->erCode) ? '[RUN]' : (is_numeric($this->erCode) ? $this->getLevel() : $this->erCode); $erMsg = $message = $title = basDebug::hidInfo($this->erMsg); $erFile = $this->erFile; $erLine = $this->erLine; $erTrace = basDebug::hidInfo($this->trace); $traceInfo = implode("
",basDebug::hidInfo($this->trace)); // 兼容 // if(basEnv::isMpro() || basEnv::isAjax() || defined('RUN_AJAX')){ $data = ['errno'=>$erCode, 'errmsg'=>$erMsg, 'erFile'=>$erFile, 'erLine'=>$erLine, 'erTrace'=>$erTrace]; vopApi::view($data); }else{ glbHtml::httpStatus('404'); include vopTpls::cinc("base:stpl/err_info"); } if(!defined('ERR_NODIE')){ die(); // ??? } } //错误等级 protected function getLevel() { $arr = array( 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)', 2047 => 'E_ALL', 2048 => 'E_STRICT', '-24' => 'EXCEPT_HANDLER', ); $fix = isset($arr[$this->erCode]) ? "({$arr[$this->erCode]})" : ''; return $this->erCode.$fix; } } ### file: /share_imcat/core/glib/glbDBCache.php sql = $sql; //判断当前的sql是否是查询语句 if($func){ return parent::query($sql,$func); }elseif(strpos(trim(strtolower($sql)),'select')===0){ //读取缓存 $data = $this->_dcGet(); if(!empty($data)){ return $data; } //没有缓存,则查询数据库 $this->runTimer(); $data = $this->db->arr($this->sql); $this->runTimer('qSelect'); $this->_dcPut($data);//写入缓存 return $data; }else{ //不是查询条件,执行之后,直接返回 return parent::query($sql,$func); } } //统计行数 function count(){ // SELECT $func($field) AS $field FROM $tab WHERE kid='$job' $table = $this->opts['table'];//当前表 $field = 'count(*)';//查询的字段 $where = $this->_parseCond();//条件 $this->sql = "SELECT $field FROM $table $where"; //读取缓存 $re = $this->_dcGet(); if(!empty($re)){ return $re; } $this->runTimer(); $re = $this->db->val($this->sql); $this->runTimer('count'); $this->_dcPut($re);//写入缓存 return $re; } //只查询一条信息,返回一维数组 function find(){ $table = $this->opts['table'];//当前表 $field = $this->opts['field'];//查询的字段 $this->opts['limit']=1;//限制只查询一条数据 $where = $this->_parseCond();//条件 $this->opts['field'] = '*';//设置下一次查询时,字段的默认值 $this->sql = "SELECT $field FROM $table $where"; //读取缓存 $data = $this->_dcGet(); if(!empty($data)){ return $data; } $this->runTimer(); $data = $this->db->row($this->sql); $this->runTimer('find'); $this->_dcPut($data);//写入缓存 return $data; } //查询多条信息,返回数组 function select(){ $table = $this->opts['table'];//当前表 $field = $this->opts['field'];//查询的字段 $where = $this->_parseCond();//条件 $this->opts['field'] = '*';//设置下一次查询时,字段的默认值 $this->sql = "SELECT $field FROM $table $where"; //读取缓存 $data = $this->_dcGet(); if(!empty($data)){ return $data; } //没有缓存,则查询数据库 $this->runTimer(); $data = $this->db->arr($this->sql); $this->runTimer('select'); $this->_dcPut($data);//写入缓存 return $data; } //初始化缓存类,如果开启缓存,则加载缓存类并实例化 function _dcInit(){ if(is_object($this->cache)){ return true; }elseif($this->config['dc_on']){ $config = array(); foreach ($this->config as $key => $val) { if($key=='dc_on') continue; $pre = substr($key,0,3); if($pre=='dc_') $config[substr($key,3)] = $val; } $this->cache = new extCache($config); return true; }else{ return false; } } //读取缓存 function _dcGet(){ $key = $this->_dcKey(); unset($this->opts['cache']); $data = $key ? $this->cache->get($key) : ''; if(!empty($data)){ return $data; }else{ return ""; } } //写入缓存 private function _dcPut($data){ $key = $this->_dcKey(0); unset($this->opts['cache']); if($key){ $exp = $this->_dcKey('(exp)'); return $this->cache->set($key[0],$data,$key[1]); } return false; } private function _dcKey($resql=1){ $expire = isset($this->opts['cache']) ? $this->opts['cache'] : $this->config['dc_exp']; if(empty($expire)) return false; // 缓存时间为0,不读取缓存 if(!$this->_dcInit()){ return false; } $arr1 = array( 'SELECT ','FROM ','WHERE ','AND ','OR ', 'INSERT INTO ','UPDATE ','DELETE ','REPLACE INTO ', 'GROUP BY ','HAVING ','ORDER BY ','LIMIT ', 'LEFT JOIN','RIGHT JOIN','INNER JOIN', ' ', ); $arr2 = array( '[s]','[f]','[w]','[a]','[o]', '[i]','[u]','[d]','[r]', '[gby]','[hav]','[oby]','[lmt]', '[lj]','[rj]','[ij]', '', ); $sql = str_replace($arr1,$arr2,$this->sql); return $resql ? $sql : array($sql,$expire); } //删除数据库缓存 function clear(){ if($this->config['dc_on']) return $this->cache->clear(); return false; } } ### file: /share_imcat/core/glib/safScan.php [ '自定义特征1->phpinfo('=>'phpinfo\(', '自定义特征1->eval('=>'eval\(', '自定义特征1->exec('=>'exec\(', ], '-' =>[], '0' => [ '后门特征->cha88.cn'=>'cha88\.cn', '后门特征->c99shell'=>'c99shell', '后门特征->phpspy'=>'phpspy', '后门特征->Scanners'=>'Scanners', '后门特征->cmd.php'=>'cmd\.php', '后门特征->str_rot13'=>'str_rot13', '后门特征->webshell'=>'webshell', '后门特征->EgY_SpIdEr'=>'EgY_SpIdEr', '后门特征->tools88.com'=>'tools88\.com', '后门特征->SECFORCE'=>'SECFORCE', '后门特征->eval("?>'=>'eval\((\'|")\?>', '可疑代码特征->system('=>'system\(', '可疑代码特征->passthru('=>'passthru\(', '可疑代码特征->shell_exec('=>'shell_exec\(', '可疑代码特征->exec('=>'exec\(', '可疑代码特征->popen('=>'popen\(', '可疑代码特征->proc_open'=>'proc_open', '可疑代码特征->eval($'=>'eval\((\'|"|\s*)\\$', '可疑代码特征->assert($'=>'assert\((\'|"|\s*)\\$', '危险MYSQL代码->returns string soname'=>'returnsstringsoname', '危险MYSQL代码->into outfile'=>'intooutfile', '危险MYSQL代码->load_file'=>'select(\s+)(.*)load_file', '加密后门特征->eval(gzinflate('=>'eval\(gzinflate\(', '加密后门特征->eval(base64_decode('=>'eval\(base64_decode\(', '加密后门特征->eval(gzuncompress('=>'eval\(gzuncompress\(', '加密后门特征->eval(gzdecode('=>'eval\(gzdecode\(', '加密后门特征->eval(str_rot13('=>'eval\(str_rot13\(', '加密后门特征->gzuncompress(base64_decode('=>'gzuncompress\(base64_decode\(', '加密后门特征->base64_decode(gzuncompress('=>'base64_decode\(gzuncompress\(', '一句话后门特征->eval($_'=>'eval\((\'|"|\s*)\\$_(POST|GET|REQUEST|COOKIE)', '一句话后门特征->assert($_'=>'assert\((\'|"|\s*)\\$_(POST|GET|REQUEST|COOKIE)', '一句话后门特征->require($_'=>'require\((\'|"|\s*)\\$_(POST|GET|REQUEST|COOKIE)', '一句话后门特征->require_once($_'=>'require_once\((\'|"|\s*)\\$_(POST|GET|REQUEST|COOKIE)', '一句话后门特征->include($_'=>'include\((\'|"|\s*)\\$_(POST|GET|REQUEST|COOKIE)', '一句话后门特征->include_once($_'=>'include_once\((\'|"|\s*)\\$_(POST|GET|REQUEST|COOKIE)', '一句话后门特征->call_user_func("assert"'=>'call_user_func\(("|\')assert("|\')', '一句话后门特征->call_user_func($_'=>'call_user_func\((\'|"|\s*)\\$_(POST|GET|REQUEST|COOKIE)', '一句话后门特征->$_POST/GET/REQUEST/COOKIE[?]($_POST/GET/REQUEST/COOKIE[?]'=>'\$_(POST|GET|REQUEST|COOKIE)\[([^\]]+)\]\((\'|"|\s*)\\$_(POST|GET|REQUEST|COOKIE)\[', '一句话后门特征->echo(file_get_contents($_POST/GET/REQUEST/COOKIE'=>'echo\(file_get_contents\((\'|"|\s*)\\$_(POST|GET|REQUEST|COOKIE)', '上传后门特征->file_put_contents($_POST/GET/REQUEST/COOKIE,$_POST/GET/REQUEST/COOKIE'=>'file_put_contents\((\'|"|\s*)\\$_(POST|GET|REQUEST|COOKIE)\[([^\]]+)\],(\'|"|\s*)\\$_(POST|GET|REQUEST|COOKIE)', '上传后门特征->fputs(fopen("?","w"),$_POST/GET/REQUEST/COOKIE['=>'fputs\(fopen\((.+),(\'|")w(\'|")\),(\'|"|\s*)\\$_(POST|GET|REQUEST|COOKIE)\[', '.htaccess插马特征->SetHandler application/x-httpd-php'=>'SetHandlerapplication\/x-httpd-php', '.htaccess插马特征->php_value auto_prepend_file'=>'php_valueauto_prepend_file', '.htaccess插马特征->php_value auto_append_file'=>'php_valueauto_append_file' ], ]; static function deel($str, $no=0){ $tab = self::getTab($no); foreach($tab as $key=>$value){ $value = str_replace("\\(", "\\s*\\(", $value); if(preg_match("/$value/i", $str)){ safBase::Stop('scanStop', $key); } } } static function getTab($no=0){ return self::$tabs[$no]; } // --- End ---------------------------------------- } ### file: /share_imcat/core/glib/fldEdit.php "; for($i=1;$i<=$deep;$i++){ $acts = $i>1 ? "style='display:none'" : ''; $acts .= " onChange=\"laySet('$mod','$key',this)\" "; $res .= "\n"; } // layTypes.init(mod,key) return $res; } static function fmOrgData($tabid,$mod,$kid,$fm=array(),$catid=''){ $_groups = glbConfig::read('groups'); if(empty($kid)){ if(!empty($fm['from'])){ $ademo = fldCfgs::addDemo('init_docs')+fldCfgs::addDemo('init_dext')+fldCfgs::addDemo('init_coms')+fldCfgs::addDemo('init_users'); } $def = array('title'=>'','dbtype'=>'varchar','val'=>'','key'=>''); $from = isset($ademo[$fm['from']]) ? $ademo[$fm['from']] : array(); if(isset($_groups[$fm['from']])){ $from['title'] = $_groups[$fm['from']]['title']; } //如果键名为字符,且键名相同,数组相加会将最先出现的值作为结果 $fm = $fm + $from + $def; }else{ $cawhr = ($catid) ? "AND catid='$catid'" : ""; $fm = glbDBObj::dbObj()->table($tabid)->where("model='$mod' AND kid='$kid' $cawhr")->find(); } return $fm; } function __construct($mod,$cfg=array()){ $_groups = glbConfig::read('groups'); $this->mod = $mod; $this->pmod = $_groups[$mod]['pid']; $this->ispara = basReq::val('ispara','0'); $this->cfg = $cfg; $this->type = $cfg['type']; $this->fmextra = $cfg['fmextra']; $this->etab = empty($cfg['etab']) ? 0 : 1; } // iTypeOpts function fmTypeOpts(){ $types = fldCfgs::viewTypes(); $plugs = fldCfgs::viewPlugs(); $plugstr = isset($plugs[$this->fmextra]) ? $plugs[$this->fmextra] : basLang::show('admin.fe_noctrl'); $etab = empty($this->etab)? basLang::show('admin.fe_mtab') : basLang::show('admin.fe_extab'); $row = "\n"; $row .= "\n"; $row .= "\n"; glbHtml::fmae_row(basLang::show('admin.fe_ftype'),$row); } // iPlusPara function fmPlusPara(){ $_groups = glbConfig::read('groups'); $oldval = empty($this->cfg['fmexstr']) ? '' : $this->cfg['fmexstr']; if($this->fmextra=='winpop'){ if(empty($oldval) && isset($_groups[$this->cfg['from']])){ $oldval = $this->cfg['from']; //if(empty($this->cfg['title'])) $this->cfg['title'] = $_groups[$oldval]['title']; } $arr = array(); foreach($_groups as $k=>$v){ if($v['pid']=='types') $arr[$k] = "$k:$v[title]"; } $row = ""; }elseif(in_array($this->fmextra,array('datetm','editor','color'))){ //,'map' $msgs = array('datetm'=>basLang::show('admin.fe_tmfmt').':Y-m-d H:i:s','editor'=>basLang::show('admin.fe_edtool').':full,exbar','color'=>basLang::show('admin.fe_colorto').':title'); $row = " {$msgs[$this->fmextra]}"; }else{ // in_array($this->type,array('input','text','hidden')) echo ""; return; } glbHtml::fmae_row(basLang::show('admin.fe_ctrlp'),$row); } // iParaKeys function fmParaKeys(){ if(empty($this->ispara)) return; $row = ""; $row .= "   ".basLang::show('admin.fe_prval').": "; glbHtml::fmae_row(basLang::show('admin.fe_prkey'),$row); } // iKeyName function fmKeyName(){ $enable = empty($this->cfg['enable']) ? '0' : '1'; $top = empty($this->cfg['top']) ? '888' : $this->cfg['top']; $kid = empty($this->cfg['kid']) ? '' : $this->cfg['kid']; $title = empty($this->cfg['title']) ? '' : $this->cfg['title']; $ienable = ""; // glbHtml::fmae_row(basLang::show('admin.fe_keyid'),"   ".basLang::show('admin.fe_uesable')."$ienable"); $itop = ""; glbHtml::fmae_row(basLang::show('admin.fe_fname'),"   ".basLang::show('admin.fe_order')."$itop"); } // iDbOpts function fmDbOpts(){ if($this->fmextra=='datetm'){ $opts = ""; $opts .= ""; $flen = 12; }elseif(in_array($this->fmextra,array('winpop','map','color'))){ $opts = ""; }elseif(in_array($this->type,array('parts','repeat'))){ $opts = ""; $flen = 0; }elseif(in_array($this->type,array('passwd','file'))){ $opts = ""; $flen = 255; }elseif(in_array($this->type,array('text'))){ // $this->fmextra=='editor' $opts = ""; $opts .= ""; $opts .= ""; $opts .= ""; $flen = $this->cfg['dbtype']=='varchar' ? (isset($this->cfg['dblen'])?$this->cfg['dblen']:255) : 0; }else{ $oldval = empty($this->cfg['dbtype']) ? 'varchar' : $this->cfg['dbtype']; $dbtypes = fldCfgs::dbTypes(); foreach(array('text','mediumtext','nodb','file') as $dk){ unset($dbtypes[$dk]); } $opts = basElm::setOption($dbtypes,$oldval,basLang::show('admin.fe_dbtype')); } $dblen = isset($flen) ? $flen : (empty($this->cfg['dblen']) ? ($this->cfg['dbtype']=='varchar' ? 12 : '0') : $this->cfg['dblen']); @$dbdef = strlen($this->cfg['dbdef']) ? $this->cfg['dbdef'] : ''; $row = "\n"; //$dise = "disabled='disabled'"; $row .= "    ".basLang::show('admin.fe_len').""; $row .= "
"; glbHtml::fmae_row(basLang::show('admin.fe_dbdef'),$row); } // iRegOpts function fmRegOpts(){ $vmax = empty($this->cfg['vmax']) ? '0' : $this->cfg['vmax']; $vtip = empty($this->cfg['vtip']) ? '' : $this->cfg['vtip']; $vreg = empty($this->cfg['vreg']) ? '' : $this->cfg['vreg']; $fnull = '1'; $vtype = ''; $vmin = '0'; if(!empty($this->cfg['vreg'])){ $fnull = strstr($this->cfg['vreg'],'nul:') ? 'nul' : '0'; $vtype = str_replace('nul:','',$this->cfg['vreg']); preg_match("/\:(\d+)\-/",$this->cfg['vreg'],$m); if(isset($m[1]) && is_numeric($m[1])) $vmin = $m[1]; } if($this->fmextra=='file'){ $rtypes = array('fix:file'=>basLang::show('admin.fe_file'), 'fix:image'=>basLang::show('admin.fe_pic'),); }elseif(in_array($this->cfg['dbtype'],array('float','int'))){ $rtypes = basLang::ucfg('cfglibs.fedit_numtype'); }else{ $rtypes = fldCfgs::regTypes(); unset($rtypes['fix:file'],$rtypes['fix:image'],$rtypes['n+i'],$rtypes['n-i'],$rtypes['n+d'],$rtypes['n-d']); } $opts = basElm::setOption($rtypes,$vtype,basLang::show('admin.fe_vtype')); $row = "\n"; $row .= "   ".basLang::show('admin.fe_len').""; $row .= "-"; $row .= ""; $row .= "
".basLang::show('admin.fe_vreg').""; $row .= "
"; $row .= "\n"; glbHtml::fmae_row(basLang::show('admin.fe_3title'),$row); } // iViewOpts function fmViewOpts(){ $fmsize = empty($this->cfg['fmsize']) ? '' : $this->cfg['fmsize']; $fmline = @$this->cfg['fmline']; $fmtitle = @$this->cfg['fmtitle']; $rtip = basLang::show('admin.fe_tipsize'); $row = ""; $row .= "\n"; $row .= "\n"; glbHtml::fmae_row(basLang::show('admin.fe_shsize'),$row); } // iRemCfgs function fmRemCfgs(){ $cfgs = empty($this->cfg['cfgs']) ? '' : $this->cfg['cfgs']; $note = basLang::inc('uless','fldedit_note'); glbHtml::fmae_row(basLang::show('admin.fe_selarr'),""); glbHtml::fmae_row(basLang::show('admin.fe_note'),""); } } ### file: /share_imcat/core/glib/glbHtml.php ');"; if($script){ $jstr = "\n";} echo $jstr; } // viewport-v2 static function wpscv2($width=480, $script=1){ $jstr = "var ww=window.innerWidth, scale=ww/$width; "; //$jsdo = "$('body').css({'transform':'scale('+scale+')','transform-origin':'top center'});"; $jstr .= "if(ww<$width){ $(function(){ $('body').css({'fontSize':scale+'%'}); }); }"; if($script){ $jstr = "\n";} echo $jstr; } // viewport-scale static function wpscale($width=480, $script=1){ $method = preg_match("/Android|iPhone|IEMobile/i",$_SERVER['HTTP_USER_AGENT']) ? 'wpscv1' : 'wpscv2'; self::$method($width); } // 页面结构 static function page($mod='',$ext='',$iex=''){ global $_cbase; if($mod=='body'){ echo "\n"; }elseif($mod=='end'){ if(empty($_cbase['run']['headed'])) self::page(''); if(strlen($ext)>12) echo "$ext\n"; echo "\n"; }elseif($mod=='aumeta'){ // 去掉/修改:author-meta标签在这里 $auweb = "http://txjia.com, https://gitee.com/PeaceXie/imcat"; echo "\n"; }elseif(in_array($mod,array('robots','viewport','keywords','description'))){ if($mod=='robots' && empty($ext)) $ext = 'noindex, nofollow'; if($mod=='viewport' && empty($ext)) $ext = 'width=device-width,minimum-scale=1.0,maximum-scale=1.0,user-scalable=no'; echo "\n"; }elseif($mod=='init'){ echo "\n"; echo "\n"; self::page('viewport'); if($ext) self::page('robots'); if(empty($iex)) echo "\n"; }else{ //head $_cbase['run']['headed'] = 1; $mod || $mod = $_cbase['sys_name']; $mod = str_replace('(sys_name)',$_cbase['sys_name'],$mod); echo "\n"; self::page('init',$ext,$iex); echo "$mod\n"; } } // header static function head($type='js',$cset=''){ global $_cbase; $cset = $cset ? $cset : $_cbase['sys']['cset']; $a = array( 'html'=>'text/html', 'css'=>'text/css', 'xml'=>'text/xml', 'js'=>'text/javascript', 'json'=>'application/json', 'jsonp'=>'application/jsonp', 'down'=>'application/octet-stream', ); header("Content-Type:$a[$type]; charset=$cset"); if(!empty($_cbase['sys']['xpwby'])){ header('X-Powered-By:'.$_cbase['sys']['xpwby']); } } // domain_allow跨域允许 static function dallow($domain=''){ if($domain=='*'){ // 请先自行认证,如oauth $allow = array('*'); }else{ $allow = glbConfig::read('domain.dmacc','sy'); if(empty($domain)){ @$aurl = parse_url(basEnv::serval("HTTP_REFERER")); @$domain = $aurl['host']; } } if(in_array($domain, $allow)){ $aldom = $domain=='*' ? '*' : $domain; // https ? header("Access-Control-Allow-Origin:$aldom"); // http://127.0.0.1, 指定允许其他域名访问 header('Access-Control-Allow-Credentials:true'); // 允许携带 用户认证凭据(也就是请求携带Cookie) header('Access-Control-Allow-Methods:GET,HEAD,OPTIONS,POST,PUT'); // 响应类型 header('Access-Control-Allow-Headers:X-Requested-With,Content-Type'); header('X-Frame-Options:ALLOWALL'); //ALLOWALL,ALLOW-FROM // Access-Control-Allow-Headers,Origin,Accept,X-Requested-With,Content-Type,Access-Control-Request-Method,Access-Control-Request-Headers } } // table:(bar): 头 static function tab_bar($title,$cont,$w1=25,$css2='tc'){ echo "\n"; echo "\n"; echo "\n"; echo "
$title$cont
\n"; } // form+table:头 static function fmt_head($fmid,$fmact,$tbcss='',$win='',$tbbrd=1){ global $_cbase; //if($tbcss=='tblist') $_cbase['run']['tabResize'] = 1; $fmact = basReq::getURep($fmact,'recbk'); echo "
\n"; $recbk = basReq::val('recbk',''); $recbk = $recbk==='ref' ? basEnv::serval("HTTP_REFERER") : $recbk; echo "\n"; if(strstr($tbcss,'tbdata') || strstr($tbcss,'tblist')){ echo "
"; $_cbase['run']['tabResp'] = 1; } echo "\n"; } // form+table:(end):结束 static function fmt_end($data='',$tabend='
'){ global $_cbase; if(strstr($tabend,'') && !empty($_cbase['run']['tabResp'])){ $tabend .= "
"; } if(!$data){ echo "\n$tabend
"; return; } if(is_array($data)){ $arr = $data; }else{ $arr[] = $data; } $str = ''; foreach($arr as $v){ $itm = explode('|',"$v|"); //if($itm[1]) $itm[1] = $itm[0]; $str .= "\n"; } echo "$str$tabend"; } // form:(增加/修改):一行 static function fmae_row($title,$msg,$hid=0){ echo "$title\n"; echo "$msg\n"; } // form:(增加/修改):头 static function fmae_top($title,$msg,$width=25){ echo "$title\n"; echo "$msg\n"; } // form:(增加/修改):提交 static function fmae_send($fmid,$title,$width=0,$bcls='tc'){ $input = ""; echo "$title\n"; echo "$input".($bcls=='tr' ? "     " : "")."\n"; } static function null_cell($str,$char='Y'){ return empty($str) ? "---" : ($char=='Y' ? 'Y' : $str); } static function ieLow_js(){ $tags = 'abbr,article,aside,audio,canvas,datalist,details,dialog,eventsource,figure,footer'; $tags .= ',header,hgroup,mark,menu,meter,nav,output,progress,section,time,video'; $s = ''; echo "\n$s\n"; } static function ieLow_html($mie=9,$css='LowIE',$msg=''){ $msg || $msg = basLang::show('core.ie_low',$mie); $s = ""; echo "\n$s\n"; } // 清空缓存 static function clearCache(){ header("Expires: Mon, 26 Jul 1997 05:00:00 GMT"); // 让它在过去就“失效” header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT"); // 永远是改动过的 header("Cache-Control: no-store, no-cache , must-revalidate"); // HTTP/1.1 header("Cache-Control: post-check=0, pre-check=0", false); header("Pragma: no-cache"); // HTTP/1.0 header("Cache-control: max-age=0"); // IE6 } // PageEnd() static function end($msg='',$end=''){ global $_cbase; if(empty($_cbase['run']['headed'])){ self::page(''); } if($msg) echo "

$msg

\n"; if($end) echo "$end\n"; echo "\n"; die(); } // 发送HTTP状态 static function httpStatus($code, $remsg=0) { $_status = glbConfig::read('https','sy'); if($remsg){ return ($_status[$code] && $remsg) ? $_status[$code] : 'Unknow Error'; } if(isset($_status[$code])) { header('HTTP/1.1 '.$code.' '.$_status[$code]); header('Status:'.$code.' '.$_status[$code]); // 确保FastCGI模式下正常 } } } ### file: /share_imcat/core/glib/glbDBExt.php table($tabf)->where("model='$mod' AND kid='$cid'")->find(); if(in_array($r['dbtype'],array('nodb','file'))) return; $tabid = (empty($r['etab'])?'docs':'dext')."_$mod"; $tabto = (empty($r['etab'])?'dext':'docs')."_$mod"; $cols = $db->fields($tabto); self::setOneFAE($tabto,$cid,$r,$cols); // move:data $sin = "SELECT `$cid` FROM $db->pre{$tabid}$db->ext f WHERE f.did=n.did"; $sql = "UPDATE $db->pre{$tabto}$db->ext n SET n.$cid = ($sin) "; $db->query($sql); // end:del-old-field, upd-field-cfg $db->query("ALTER TABLE $db->pre{$tabid}$db->ext DROP `$cid` "); $dupd['etab'] = empty($r['etab']) ? '1' : '0'; $db->table($tabf)->data($dupd)->where("model='$mod' AND kid='$cid'")->update(); glbCUpd::upd_model($mod); } // 字段 - 添加/删除/修改 static function setOneField($mod,$cid,$act='del',$cfg=array()){ $db = glbDBObj::dbObj(); $tabf = 'base_fields'; $r = $db->table($tabf)->where("model='$mod' AND kid='$cid'")->find(); if(!empty($r) && in_array($r['dbtype'],array('nodb','file'))) return; if(empty($r) && !empty($cfg)) $r = $cfg; $tabid = self::getTable($mod,empty($r['etab'])?'0':1); $cols = $db->fields($tabid); if($act=='del'){ if(isset($cols[$cid])) $db->query("ALTER TABLE $db->pre{$tabid}$db->ext DROP `$cid` "); $db->table($tabf)->where("model='$mod' AND kid='$cid'")->delete(); }else{ self::setOneFAE($tabid,$cid,$r,$cols); } } static function setOneFAE($tabid,$cid,$r,$cols=array()){ $db = glbDBObj::dbObj(); $sql = "ALTER TABLE $db->pre{$tabid}$db->ext"; if(isset($cols[$cid])) $sql.= " CHANGE `$cid` "; else $sql.= " ADD "; $dblen = intval(@$r['dblen']); $sql.= " `$cid` $r[dbtype]".($r['dbtype']=='varchar' ? ($dblen>0?"($dblen)":'(12)') : ''); $sql.= (strpos("($r[vreg]",'nul:') ? " NULL " : ' NOT NULL '); if(strstr($r['dbtype'],'char')){ $sql.= " DEFAULT '".(strlen($r['dbdef'])==0?'':$r['dbdef'])."' "; }elseif(strstr($r['dbtype'],'int') || in_array($r['dbtype'],['float','double','decimal'])){ $sql.= " DEFAULT '".(strlen($r['dbdef'])==0?'0':$r['dbdef'])."' "; } $after = self::findAfterField($cols,$cid); if(!isset($cols[$cid])) $after && $sql.= " AFTER `$after` "; $db->query($sql); } static function setfieldDemo($mod,$obj,$org='(drop)'){ $db = glbDBObj::dbObj(); if($org=='(drop)'){ $db->query("DROP TABLE IF EXISTS $db->pre{$obj}$db->ext "); $db->table('base_fields')->where("model='$mod'")->delete(); }else{ $_ta = explode('_',$org); $obj && $db->query("CREATE TABLE IF NOT EXISTS $db->pre{$obj}$db->ext LIKE $db->pre{$org}$db->ext"); if(in_array($_ta[0],array('coms','docs','users'))){ //增加默认字段配置'dext', $pid = $_ta[1]; $_cfg = glbConfig::read($pid); $farr = @$_cfg['f']; $top = 120; if($farr){ foreach($farr as $k=>$v){ $tabid = 'base_fields'; if(!$db->table($tabid)->where("kid='$k' AND model='$mod'")->find()){ $fm = array('kid'=>$k,'model'=>$mod,'top'=>$top,)+$v; $db->table($tabid)->data($fm)->insert(); } $top += 4; } } } } } // tab下-添加字段,在什么字段后面 static function findAfterField($tab,$col){ $_groups = glbConfig::read('groups'); $a = is_array($tab) ? $tab : $db->fields($tab); if(isset($_groups[$col]) && $_groups[$col]['pid']=='types' && isset($a['catid'])){ $def = 'catid'; }else{ $def = ''; $bak = ''; foreach($a as $k=>$v){ if($k=='aip'){ $def = empty($bak) ? 'aip' : $bak; break; } if(substr("$k)))",0,3)==substr("$col)))",0,3)){ $def = $k; } $bak = $k; } } return $def; } // tab, $tmp(md2,md3,mdh),max, static function dbAutID($tab='utest_keyid', $tmp='max', $n=0, $xTime=''){ $db = glbDBObj::dbObj(); $tabf = $db->pre.$tab.$db->ext; $tfix = substr($tab,0,5); if(in_array($tfix,array('docs_','coms_','advs_','users'))){ $tkey = substr($tfix,0,1).'id'; $tno = substr($tfix,0,1).'no'; }else{ $tkey = 'kid'; $tno = 'kno'; } $ktmp = basKeyid::kidTemp($tmp, $xTime); // 2018-mdh-1233 if($tmp=='max'){ $kno = 1; $kid = $ktmp; }else{ $pdb = substr($ktmp,0,strrpos($ktmp,'-')).'%'; $mdb = $db->query("SELECT max($tno) as $tno FROM $tabf WHERE $tkey LIKE '$pdb'"); $kno = empty($mdb[0][$tno]) ? 1 : ($mdb[0][$tno]+1) % 99; $kfix = $kno<10 ? '0'.$kno : $kno; $kid = substr($ktmp,0,strlen($ktmp)-2).$kfix; } if($n) $kid = substr($kid,0,strlen($kid)-2).basKeyid::kidRand('k',2); $rec = $db->table($tab)->where("$tkey='$kid'")->find(); if($rec) return self::dbAutID($tab, $tmp, $n+1, $xTime); else return array($kid,$kno); } static function dbNxtID($tab,$mod,$pid='0'){ $sqlm = $tab=='bext_relat' ? '' : ($tab=='base_model' ? 'pid' : 'model')."='$mod' AND "; $mcfg = glbConfig::read($mod); //"$sqlm kid REGEXP ('^{$fix}[0-9]{3}$')"; $fd = $pid ? ($mcfg['i'][$pid]['deep']+1) : '1'; $tid = ''; // 找:本pid下最大的一个ID if(!empty($mcfg['i'])){ foreach($mcfg['i'] as $ik=>$iv) { if(!empty($iv['pid']) && $iv['pid']==$pid && preg_match("/^[a-z]{1,6}\d{2,10}$/i",$ik)){ $tid = max($tid,$ik); } } } if($tid){ // 找:所有的类似最大的一个ID preg_match("/^([a-z]{1,5})(\d{2,10})$/i",$tid,$tmp); $fix = $tmp[1]; $no = $tmp[2]; $nl = strlen($no); foreach($mcfg['i'] as $ik=>$iv) { if($iv['pid']==$pid) continue; if($iv['deep']!=$fd) continue; if(preg_match("/^$fix\d{{$nl}}$/i",$ik)){ $tid = max($tid,$ik); } } //echo $tid; // 找:下一个 preg_match("/^([a-z]{1,5})(\d{2,10})$/i",$tid,$tmp); $nid = $fix.basKeyid::kidNext('',$tmp[2],$tmp[2],2,strlen($tmp[2])); // 是否存在 $whr = "$sqlm kid='$nid'"; // echo "(n=$nid"; $re = glbDBObj::dbObj()->table($tab)->where($whr)->order('kid DESC')->find(); if(!$re){ return $nid; } } $fix = substr($mod,0,1).$fd; $whr = "$sqlm kid LIKE '$fix%'"; $re = glbDBObj::dbObj()->table($tab)->where($whr)->order('kid DESC')->find(); if($re){ $nid = substr($re['kid'],2); $nid = basKeyid::kidNext('',$nid,'012',2,3); }else{ $nid = '012'; } return $fix.$nid; } // ext: 0-tab, 1-ext, kid, arr static function getTable($mod,$ext='0'){ $_groups = glbConfig::read('groups'); if(!isset($_groups[$mod])) return ''; if($_groups[$mod]['pid']=='docs'){ $tabid = $ext==1 ? 'dext_'.$mod : 'docs_'.$mod; $keyid = 'did'; }elseif($_groups[$mod]['pid']=='users'){ $tabid = 'users_'.$mod; $keyid = 'uid'; }elseif($_groups[$mod]['pid']=='advs'){ $tabid = 'advs_'.$mod; $keyid = 'aid'; }elseif($_groups[$mod]['pid']=='coms'){ $tabid = 'coms_'.$mod; $keyid = 'cid'; }elseif($_groups[$mod]['pid']=='types'){ $tabid = empty($_groups[$mod]['etab']) ? 'types_common' : 'types_'.$mod; $keyid = 'kid'; }else{ $tabid = $keyid = ''; } if(is_numeric($ext)){ // 0, 1 return $tabid; }else{ // kid,arr return $ext=='kid' ? $keyid : array($tabid,$keyid); } } static function getKids($mod,$kid='',$whr='',$ret='sub'){ $tabid = self::getTable($mod); $kid = $kid ? basStr::filKey($kid,'_-.') : self::getKeyid($mod); $list = glbDBObj::dbObj()->table($tabid)->field($kid)->where($whr)->select(); $re = array(); if($list){ foreach($list as $r){ $re[] = $r[$kid]; } } if(empty($re)){ $re[] = '(null)'; } if($ret=='sub'){ $re = "'".implode("','",$re)."'"; } return $re; } static function dbComment($tabid='~return~'){ static $dbdict,$fmod,$fdemo; $db = glbDBObj::dbObj(); $fsystem = basLang::ucfg('fsystem'); if(empty($dbdict)){ $dict = $db->table('bext_dbdict')->field("kid,tabid,title")->select(); foreach($dict as $v){ $dbdict[$v['tabid']][$v['kid']] = $v['title']; } } if(empty($fmod)){ $dict = $db->table('base_fields')->field("kid,model,title")->select(); foreach($dict as $v){ $fmod[$v['model']][$v['kid']] = $v['title']; } } if(empty($fdemo)){ $fdemo = array(); $demo = glbConfig::read('fdemo','sy'); foreach(array('init_users','init_coms','init_dext','init_docs',) as $part){ $fpart = $demo[$part]; foreach($fpart as $f=>$v){ $fdemo[$f] = $v['title']; } } } if($tabid=='~return~') return array('fsystem'=>$fsystem,'fdemo'=>$fdemo,); $fields = $db->fields($tabid); $moda = explode('_',$tabid); $modid = $moda[1]; foreach($fields as $f=>$v){ $flag = 'def'; $rem = ''; if(isset($fmod[$modid][$f])){ //模型设置 $flag = 'mod'; $rem = $fmod[$modid][$f]; }elseif(empty($dbdict[$tabid][$f])){ //dbdict为空 if(isset($fdemo[$f])){ $flag = 'demo'; $rem = $fdemo[$f]; } if(isset($fsystem[$f])){ $flag = 'sys'; $rem = $fsystem[$f]; } }else{ //dbdict设置 $rem = $dbdict[$tabid][$f]; if(isset($fsystem[$f]) || in_array($moda[0],array('active','advs','base','bext','logs'))){ $flag = 'sys'; } } $fields[$f]['_flag'] = $flag; $fields[$f]['_rem'] = basStr::filTitle($rem); } $_groups = glbConfig::read('groups'); if(isset($_groups[$modid]) && $_groups[$modid]['pid']==$moda[0]){ $fields[0]['_flag'] = 'sys'; $cfg = basLang::ucfg('cfglibs.dbext'); $fields[0]['_rem'] = $_groups[$modid]['title'].('['.$cfg[$moda[0]].']').basLang::show('dbdict_tab'); } if(isset($_groups[$modid]) && $moda[0]=='dext'){ $fields[0]['_flag'] = 'sys'; $fields[0]['_rem'] = $_groups[$modid]['title'].basLang::show('dbdict_extab'); } if(isset($fsystem['_stabs'][$tabid])){ $fields[0]['_flag'] = 'sys'; $fields[0]['_rem'] = $fsystem['_stabs'][$tabid]; } if(empty($fields[0]['_rem'])&& !empty($dbdict[$tabid][0])){ $fields[0]['_flag'] = ''; $fields[0]['_rem'] = $dbdict[$tabid][0]; } return $fields; } // 获取一组扩展参数 static function getExtp($type){ $data = array(); $whr = strpos($type,'%') ? " LIKE '$type'" : "='$type'"; $list = glbDBObj::dbObj()->table('bext_paras')->where("pid$whr AND enable=1")->order('top')->limit(99)->select(); if($list){ foreach($list as $i=>$r){ $r['i'] = $i+1; foreach(array('aip','atime','auser','eip','etime','euser','cfgs','note','enable') as $k2){ unset($r[$k2]); } $data[$r['kid']] = $r; } } return $data; } } ### file: /share_imcat/core/glib/admMpts.php cn ->翻译 $tab"; } // static function vPart($part){ global $_cbase; $cfgs = $_cbase['part']; if(isset($cfgs['tab'][$part])){ return $cfgs['tab'][$part]; } return '(Null)'; } // 同步_各part static function syncParts($dop, $kid){ global $_cbase; $cfgs = $_cbase['part']; $db = glbDBObj::dbObj(); $del = 1; $row = $db->table($dop->tbid)->where("did='$kid'")->find(); if(empty($row)) return; $rex = $dop->tbext ? $db->table($dop->tbext)->where("did='$kid'")->find() : 0; $psyn = self::dbPsyn($dop, $row); $pnow = $row['part']; $otitle = $row['title']; foreach($cfgs['tab'] as $part => $ptitle) { if($part==$pnow){ if($psyn!=$row['psyn']){ $tmp = ['psyn'=>$psyn]; $db->table($dop->tbid)->data($tmp)->where("did='$kid'")->update(); } $del = 0; continue; } $old = $db->table($dop->tbid)->where("psyn='$psyn' AND part='$part'")->find(); if(!empty($old)) return; $row['did'] = self::dbKid($dop, $row); $row['part'] = $part; $row['psyn'] = $psyn; $row['title'] = self::fmtTitle($cfgs, $pnow, $part, $otitle); $db->table($dop->tbid)->data(in($row))->insert(0); if(!empty($rex)){ $rex['did'] = $row['did']; $db->table($dop->tbext)->data(in($rex))->insert(0); } } if($del){ $db->table($dop->tbid)->where("did='$kid'")->delete(); $dop->tbext && $db->table($dop->tbext)->where("did='$kid'")->delete(); } } // 取消_各part/reset-null static function resetParts($dop, $kid=''){ static $psyns; if(empty($psyns)) $psyns = array(); $db = glbDBObj::dbObj(); $row = $db->table($dop->tbid)->where("did='$kid'")->find(); if(empty($row)) return; $kid = $row['did']; $part = $row['part']; $psyn = $row['psyn']; if(!$part || !$psyn){ return; } if(in_array($psyn,$psyns)){ return; } $psyns[] = $psyn; $rows = $db->table($dop->tbid)->where("psyn='$psyn'")->select(); // AND did!='$kid' $kids = ''; foreach($rows as $row) { if($row['did']==$kid){ $tmp['part'] = ''; $tmp['psyn'] = ''; $db->table($dop->tbid)->data($tmp)->where("did='$kid'")->update(); continue; } $kids .= ($kids ? ',' : '')."'{$row['did']}'"; } if($kids && $dop->tbext){ $db->table($dop->tbext)->where("did IN($kids)")->delete(); } $kids && $db->table($dop->tbid)->where("did IN($kids)")->delete(); } static function setDef($dop, $kid=''){ global $_cbase; $cfgs = $_cbase['part']; $db = glbDBObj::dbObj(); $old = $db->table($dop->tbid)->where("did='$kid'")->find(); if(empty($old) || $old['part']==$cfgs['def']) return; $tmp['part'] = $cfgs['def']; if(in_array($dop->mod,$cfgs['psyn'])){ $tmp['psyn'] = self::dbPsyn($dop, $old); } $db->table($dop->tbid)->data($tmp)->where("did='$kid'")->update(); } static function fmtTitle($cfgs, $pnow, $part, $otitle){ $isdef = (!$pnow) && ($part==$cfgs['def']); if($isdef) return $otitle; $pmsg = $cfgs['tab'][$part]; foreach($cfgs['tab'] as $part => $ptitle) { if(strpos($otitle,"[$ptitle]")===0){ $otitle = substr($otitle,strlen("[$ptitle]")); } } return "[$pmsg]$otitle"; } // dbKid static function dbKid($dop, $row, $no=0){ $db = glbDBObj::dbObj(); $kid = substr($row['did'],0,10).basKeyid::kidRand('24',$no?3:2); $old = $db->table($dop->tbid)->where("did='{$kid}'")->find(); if(!$old){ return $kid; }else{ $no++; return self::dbKid($dop, $row, $no); } } // dbPsyn static function dbPsyn($dop, $row, $no=0){ if(!empty($row['psyn'])){ return $row['psyn']; } $db = glbDBObj::dbObj(); $psyn = basKeyid::kidY3x5().'-'.basKeyid::kidRand('24',$no?4:3); $old = $db->table($dop->tbid)->where("psyn='$psyn'")->find(); if(!$old){ return $psyn; }else{ $no++; return self::dbPsyn($dop, $row, $no); } } } ### file: /share_imcat/core/glib/glbCUpd.php 'book','2'=>'folder-open-o','3'=>'file-text-o',); // upd rebuld static function upd_rebuld(){ self::upd_groups(); foreach($g1 as $k=>$v){ if(in_array($k,array('score','sadm','smem','suser',))){ self::upd_paras($k); } if($v['pid']=='groups') continue; //if($v['pid']=='types' && !empty($v['etab'])) continue; self::upd_model($k); self::upd_menus($mod); } } // upd config static function upd_groups(){ $grps = glbDBObj::dbObj()->table('base_model')->where("enable=1")->order('pid,top,kid')->select(); $str = ''; foreach($grps as $k=>$v){ $arr[$v['kid']] = array('pid'=>$v['pid'],'title'=>$v['title'],'top'=>$v['top'],); $arr[$v['kid']]['etab'] = $v['etab']; //'docs','types' $arr[$v['kid']]['deep'] = $v['deep']; //'docs','types','menus','advs' foreach(array('pmod') as $k){ //'cfgs','pmod','cradd','crdel' if(!empty($v[$k])) $arr[$v['kid']][$k] = $v[$k]; } } glbConfig::save($arr,'groups'); } // upd grade static function upd_grade(){ $_groups = glbConfig::read('groups'); $list = glbDBObj::dbObj()->table('base_grade')->where("enable='1'")->order('model,top')->select(); $arr = array(); foreach($list as $k=>$v){ $v['grade'] = $v['kid']; $dfs = array('top','enable','note','aip','atime','auser','eip','etime','euser'); foreach($dfs as $fk) unset($v[$fk]); foreach($v as $vk=>$vv) if(!$vv) $v[$vk] = ''; $arr[$v['kid']] = $v; //self::upd_ipfile($arr[$v['kid']]); } glbConfig::save($arr,'grade','dset'); } // upd model static function upd_model($mod=0){ $_groups = glbConfig::read('groups'); if(empty($mod)) return; $v = glbDBObj::dbObj()->table('base_model')->where("kid='$mod'")->find(); $arr = array('kid'=>$v['kid'],'pid'=>$v['pid'],'title'=>$v['title'],'enable'=>$v['enable']); $arr['etab'] = $v['etab']; //'docs','types' $arr['deep'] = $v['deep']; //'docs','types','menus','advs' foreach(array('cfgs','pmod','cradd','crdel') as $k){ if(!empty($v[$k])) $arr[$k] = $v[$k]; } if(in_array($v['pid'],array('docs','users','coms','types','score','sadm','smem','suser',))){ $arr['f'] = self::upd_fields($mod); } if(in_array($v['pid'],array('docs','users'))){ $ccfg = self::upd_cfield($mod); if(!empty($ccfg)) glbConfig::save($ccfg,"c_$mod",'modex'); } $_cfg = array('advs'=>'itype','docs'=>'itype','users'=>'iuser','types'=>'itype','menus'=>'imenu'); if(isset($_cfg[$v['pid']])){ $func = 'upd_'.$_cfg[$v['pid']]; $itms = self::$func($mod,$v); if(is_array($itms)){ $arr['i'] = $itms; }else{ glbConfig::tmpItems($mod,$itms); $arr['i'] = "$mod"; } if($v['pid']=='advs'){ $arr['f'] = self::upd_afield($v); } } if(!empty($v['cfgs'])) $arr['cfgs']=$v['cfgs']; glbConfig::save($arr,$mod); } static function upd_afield($cfg){ $f = glbConfig::read('fadvs','sy'); if($cfg['etab']==1){ unset($f['mpic']); $f['detail']['title'] = 'cfgs'; $f['detail']['vreg'] = ''; $f['detail']['vtip'] = ''; } if($cfg['etab']==2){ $f['detail']['title'] = 'cfgs'; $f['detail']['vreg'] = ''; $f['detail']['vtip'] = ''; } if($cfg['etab']==3){ unset($f['mpic']); $f['url']['title'] = basLang::show('core.cupd_reprule'); $f['url']['vreg'] = ''; $f['url']['vtip'] = basLang::show('core.msg_eg').'{root}[=]http://txjia.com/
'.basLang::show('core.msg_or').'/path/[=]/peace/dev/imcat/root/'; } return $f; } // upd fields(考虑继承父级参数?) static function upd_cfield($mod=0){ $f = array(); $list = glbDBObj::dbObj()->field(self::$_fields.",catid")->table('bext_fields')->where("model='$mod' AND enable='1'")->order('catid,top')->select(); foreach($list as $k=>$v){ $cid = $v['kid']; $catid = $v['catid']; foreach($v as $i=>$u){ //kid,top,cfgs $f[$catid][$cid][$i] = $u; } if(!empty($v['cfgs'])) $f[$catid][$cid]['cfgs'] = $v['cfgs']; if(!empty($v['fmextra'])) $f[$catid][$cid]['fmextra'] = $v['fmextra']; if(!empty($v['fmexstr'])) $f[$catid][$cid]['fmexstr'] = $v['fmexstr']; } return $f; } // upd fields static function upd_fields($mod=0){ $_groups = glbConfig::read('groups'); if(isset($_groups[$mod]) && in_array($_groups[$mod]['pid'],array('docs','users','coms','types'))){ $tabid = 'base_fields'; $fields = self::$_fields; }else{ $tabid = 'base_paras'; $fields = self::$_fields.",`key`,val"; } $f = array(); $list = glbDBObj::dbObj()->field($fields)->table($tabid)->where("model='$mod' AND enable='1'")->order('top')->select(); foreach($list as $k=>$v){ $cid = $v['kid']; foreach($v as $i=>$u){ //kid,top,cfgs $f[$cid][$i] = $u; } if(!empty($v['cfgs'])) $f[$cid]['cfgs'] = $v['cfgs']; if(!empty($v['fmextra'])) $f[$cid]['fmextra'] = $v['fmextra']; if(!empty($v['fmexstr'])) $f[$cid]['fmexstr'] = $v['fmexstr']; } return $f; } // upd itype,icatalog static function upd_itype($mod,$cfg,$pid=0){ $db = glbDBObj::dbObj(); if(in_array($cfg['pid'],array('docs','advs'))){ $tabid = 'base_catalog'; }else{ $tabid = (empty($cfg['etab']) ? 'types_common' : 'types_'.$mod); } $filed = 'kid,pid,title,deep,frame,`char`,cfgs'.($tabid=='base_catalog'?',icon':''); if(strstr($cfg['cfgs'],'cats=')){ preg_match("/cats=(\w+)/",$cfg['cfgs'],$pts); $mod = $pts[1]; //dump($cfg); die('xx'); } $where = "model='$mod' AND enable='1'"; $arr = $db->field($filed)->table($tabid)->where($where)->order('deep,top,kid')->select(); $res = comTypes::arrLays($arr,self::$_mitems); return $res; } // upd iuser static function upd_iuser($mod,$cfg,$pid=0){ $db = glbDBObj::dbObj(); $tabid = 'base_grade'; $arr = array(); $where = "model='$mod' AND enable='1'"; $list = $db->field('kid,title')->table($tabid)->where($where)->order('top')->select(); if($list){ foreach($list as $v){ $k = $v['kid']; if(!empty($v['cfgs'])) $arr[$k]['cfgs'] = $v['cfgs']; $arr[$k] = $v; }} return $arr; } // upd imenu static function upd_imenu($mod,$cfg,$pid=0){ $db = glbDBObj::dbObj(); $tabid = 'base_menu'; $fileds = 'kid,pid,title,icon,deep,cfgs'; $where = "model='$mod' AND enable='1'"; $arr = $db->field($fileds)->table($tabid)->where($where)->order('deep,top')->select(); $res = comTypes::arrLays($arr,self::$_mitems); return $res; } // upd relat static function upd_relat(){ $list = glbDBObj::dbObj()->table('bext_relat')->order('top,kid')->select(); $re = array(); foreach($list as $r){ $kid = $r['kid']; $re[$kid] = array(); foreach($r as $k=>$v){ if(in_array($k,array('mod1','mod2','title','note'))){ $re[$kid][$k] = $v; } } glbConfig::tmpItems($kid,basElm::text2arr($r['cfgs'])); } glbConfig::tmpItems('relat',$re); return $re; } static function upd_paras($pid, $re='save'){ global $_cbase; $_groups = glbConfig::read('groups'); $str = ''; $arr = array(); foreach($_groups as $k=>$v){ if($v['pid']==$pid){ $cfg = glbConfig::read($k); if(empty($cfg['f'])) continue; foreach($cfg['f'] as $k2=>$v2){ $k3 = strstr($v2['key'],'[') ? str_replace(array('[',']'),array("['","']"),$v2['key']) : "['".$v2['key']."']"; $res = glbDBObj::dbObj()->table('base_paras')->where("kid='$k2'")->find(); $val = str_replace(array('"',"\\"),array("\\\"","\\\\"),$res['val']); $str .= "\n\$_cbase$k3 = \"$val\";"; $arr[$k2] = $res['val']; if(isset($v2['kid']) && substr($v2['kid'],0,5)=='safe_'){ $_sk = substr($v2['kid'],5); $_cbase['run']['_safe'][$_sk] = $val; } } $str .= "\n"; } } if($re=='save'){ glbConfig::save($str,$pid,'dset'); }else{ return $arr; } } static function upd_menus($mod,$cfg=array()){ if(empty($cfg)) $cfg = glbConfig::read($mod); if($mod=='muadm'){ $s0 = $s1 = $js1 = $js2 = $js3 = ''; $mperm = array(); foreach($cfg['i'] as $k1=>$v1){ if(!empty($v1['cfgs']) && strstr($v1['cfgs'],'?mkv')){ $mperm[$k1] = self::upd_imperm($v1['cfgs']); } if($v1['deep']=='1'){ $icon = " "; $s1 .= "$icon $v1[title]"; $js1 .= ",$k1"; $js2 .= ",$v1[title]"; $js3 .= ",$v1[icon]"; $s0 .= "
"; if(method_exists('\\imcat\\exaFunc',$func="admenu_$k1")){ exaFunc::$func($s0); } elseif($k1=='m1adv'){ self::upd_madvs($s0); } else{ self::upd_mitms($s0,$cfg,$k1); } $s0 .= "
"; } } $data = "\nvar admNavTab = '$js1';"; $data .= "\nvar admNavName = '$js2';"; $data .= "\nvar admNavIcon = '$js3';"; $data .= "\nvar admHtmTop = '".basJscss::jsShow($s1,0)."';"; $data .= "\nvar admHtmLeft = '".basJscss::jsShow($s0,0)."';"; // $data .= "\ndocument.write(admHtmTop);"; glbConfig::save($data,"{$mod}",'dset','.js'); glbConfig::save($mperm,"{$mod}_perm",'dset'); return $s0; } } static function upd_madvs(&$s0){ //按栏目显示菜单项 $_groups = glbConfig::read('groups'); foreach($_groups as $k2=>$v2){ if($v2['pid']=='advs'){ $cfg = glbConfig::read($k2); $icon = ""; $s0 .= ""; }} } static function upd_mitms(&$s0,$cfg,$k1){ //后台配置的菜单项 foreach($cfg['i'] as $k2=>$v2){ if($v2['pid']==$k1){ $icon = " "; $s0 .= ""; }} } static function upd_mlink($v3){ //处理一项链接 $t = str_replace(array('{root}','{$root}',),array(PATH_PROJ,PATH_PROJ,),$v3['cfgs']); if(strstr($t,'')){ if(!strstr($t,'target=')){ $t = str_replace("$tb[0]"; }elseif(strstr($tb[2],'blank')){ $t .= (empty($t) ? '' : ' - ')."$tb[0]"; }elseif(strstr($tb[2],'jsadd')){ $t .= (empty($t) ? '' : ' - ')."$tb[0]"; }else{ $t .= (empty($t) ? '' : ' - ')."$tb[0]"; } } }else{ $t = "$v3[title]"; } return $t; } static function upd_imperm($cfgs){ preg_match_all("/\?([\w|\/|\-]{5,36})/i",$cfgs,$ma); if(!empty($ma[1])){ $rea = array_unique($ma[1]); $re = implode(',',$rea); } return empty($re) ? array() : $re; } // static function upd_parex($pid){ $db = glbDBObj::dbObj(); $tabid = 'bext_paras'; $keys = array('pid','title','detail','numa','numb','cfgs','note'); $arr = array(); $list = $db->table($tabid)->where("pid='$pid' AND enable='1'")->order('top')->select(); foreach($list as $v){ $kid = str_replace('-','_',$v['kid']); foreach($keys as $k){ $arr[$kid][$k] = $v[$k]; } } if(!empty($arr)) glbConfig::save($arr,"parex_$pid",'dset'); } } ### file: /share_imcat/core/glib/fldCfgs.php table('base_fields')->where("model='$mod'")->select(); $amods = array(-1); $b = array(); $s = '   '.basLang::show('flow.fc_rftype'); $a = array(); if($list) foreach($list as $r) $amods[] = $r['kid']; foreach($_groups as $k=>$v){ if($v['pid']=='types'){ if(in_array("type_$k",$amods)) continue; $data = "$k|input|winpop|0"; $s .= " | $v){ if(in_array($k,$amods)) continue; if(!in_array($k,$a)){ $data = "$k|$v[type]|".@$v['fmextra']."|".@$v['etab'].""; $s .= (($no && $no%8==0) ? '
' : ' | ')."
'扩展参数-text-1', //$v){ if(strstr($k,'exp_')){ $a = explode('-',$v); $type = str_replace("checkbox","cbox",$a[1]); $data = "$k|$type||0"; $sp = ($no && $no%8==0) ? '
' : ' | '; if(isset($ccfg[$catid][$k])){ $s .= "$sp$v\r\n"; }else{ $s .= "$sp
$fv){ if(in_array($fk,$skips)){ continue; } if($fv['type']=='parts'){ // 分段开始标记 $key = $fk; $res[$key] = []; }elseif($key){ $res[$key][] = $fk; } } return $res; } static function getSizeArray($cfg=array()){ if(empty($cfg['fmsize'])){ $size = array(); }elseif(strpos($cfg['fmsize'],'.')){ //news.8 $size = explode('.',$cfg['fmsize']); }else{ //360x8 $size = explode('x',$cfg['fmsize'].'x'); } return $size; } } ### file: /share_imcat/core/glib/safComm.php 0 && $enc==$ck; return $res ? '' : 'VCode-Error[vsms4]!'; }else{ //check $cookie = comCookie::mget('vcodes',$mod); $stamp = substr($cookie,0,strpos($cookie,',')); $encode = $stamp.','.comConvert::sysEncode($sform.strtoupper($vcode),$stamp); if(strlen($cookie)<24 || $cookie!=$encode){ $re = "VCode-Error[1]!"; }elseif(($_cbase['run']['stamp']-$stamp)>$timeout){ $re = "VCode-Timeout[2]!"; }else{ $re = ''; } $clear && comCookie::mset('vcodes',0,$mod,'null'); return $re; } } // 检查表单项 --- 表单时间戳 static function formCInit($act='init', $time=3600, $novcode=0){ global $_cbase; $stamp = $_cbase['run']['stamp']; $sform = $_cbase['safe']['safil']; $safix = $_cbase['safe']['safix']; $rdnum = $_cbase['safe']['rnum']; $re = ''; $len1 = 34; $len2 = 16; //偶数 $st = date('H',$stamp)>22 ? ($stamp + 5400) : $stamp; //23:xx -> 3600+1800 $sdate = explode('_',date('m_d',$st)); $dval = (substr($rdnum,1,4)+substr($rdnum,4,4)*$sdate[0]); $dval .= '_'.(substr($rdnum,6,4)+substr($rdnum,9,4)*$sdate[1]); if($act=='init'){ $encode = comConvert::sysEncode($sform,$stamp,$len1); $restr = ""; $restr .= ""; $restr .= ""; if($novcode){ return $restr; } $fmid = basReq::val('fmid',''); $tabi = basReq::val('tabi',19790); $pos = basReq::val('pos',''); $css1 = basReq::val('css1','form-control'); // txt w60 $css2 = basReq::val('css2','fs_vimg'); $senc = comConvert::sysEncode($sform,$stamp,$len2); $vstr = "maxlength='5' reg='vimg:3-5' tip='".basLang::show('core.safcomm_vcode')."' url='".PATH_BASE."?ajax-cajax&act=chkVImg&mod={$fmid}&key={$senc}'"; $restr .= ""; $restr .= ""; //samp,span, style='width:50px;' return $restr; }else{ $re_date = basReq::ark($safix,'dt'); $re_stamp = basReq::ark($safix,'tm'); $re_encode = basReq::ark($safix,'enc'); $enc = comConvert::sysEncode($sform,$re_stamp,$len2); if(empty($re_stamp) || empty($re_encode)){ $re = 'Error-Null'; }elseif($stamp-$re_stamp>$time){ $re = 'Timeout'; }elseif(!($re_encode==comConvert::sysEncode($sform,$re_stamp,$len1))){ $re = 'Error-E'; }elseif(!($re_date==$dval)){ $re = 'Error-D'; } return array($re,$enc); } } // QUERY-7参数检测 static function urlQstr7($re=0){ $q = basEnv::serval("QUERY_STRING"); $q = urldecode($q); if($q!=str_replace(array('<','>','"',"'","\\","\r","\n"),'',$q)){ $msg = "[QUERY]Error!"; if($re) return $msg; basMsg::show($msg,'die'); } return 0; } //检测是否外部提交过来的Url //expath : 路径匹配部分,可为空 //die : 默认直接die, 如为空则返回用于判断 //return : 默认直接die; false:不是外部提交来的地址; true(string):相关信息,表示是外部提交或直接输入网址过来 //demo: if(xxx::urlFrom('',0)) die("不是来自{PATH_ROOT}的请求!"); //demo: if(xxx::urlFrom('/dgpeace/_php_test.php')); static function urlFrom($expath='',$die=1){ $re = ''; $ref = basEnv::serval('ref'); if(empty($ref)){ //为空:(输入地址等) $re = 'Null'; }else{ $from = self::urlParse($ref); $hnow = self::urlParse($_SERVER['HTTP_HOST']); if(@$from['host']!==@$hnow['host']){ // 匹配:主机/域名+端口 $re = $from['host']; }else{ // 匹配:路径 $npath = PATH_PROJ; //cls_env::mconfig('cmsurl'); // 如:/house/ if($expath) $npath = str_replace(array('///','//'),'/',"$npath/$expath"); if(strlen($npath)>0 && !preg_match('/^'.preg_quote($npath,"/").'/i',$from['p'])){ $re = $npath; } } } if($re && $die){ safBase::Stop('urlFrom',$re); } return $re; } static function urlParse($url){ $aurl = parse_url($url); $top = basEnv::TopDomain(@$aurl['host']); if(!empty($top)){ //IP(含ipv6) $aurl['host'] = $top; } $host = @$aurl['host'].(isset($aurl['port']) ? ':'.$aurl['port'] : ''); $path = empty($aurl['path']) ? '' : $aurl['path']; return array('h'=>$host,'p'=>$path); } // 注入项扫描关键字 static function urlScan(){ $filters = "(and|or)\\b.+?(>|<|=|in|like)|<\\s*script\\b|UNION.+?SELECT|UPDATE.+?SET|INSERT\\s+INTO.+?VALUES|(SELECT|DELETE).+?FROM|(CREATE|ALTER|DROP|TRUNCATE)\\s+(TABLE|DATABASE)"; $paras = basEnv::serval("QUERY_STRING"); if(empty($paras)) return; if(preg_match("/".$filters."/is",$paras)){ safBase::Stop('urlScan'); } } // \\bEXEC\\b| , \\/\\*.+?\\*\\/| , '| // --- act=init,stop,flag static function urlStamp($act='init', $time=3600){ global $_cbase; $stamp = $_cbase['run']['stamp']; $sform = $_cbase['safe']['safil']; $safix = $_cbase['safe']['safix']; if($act=='init'){ $encode = comConvert::sysEncode($sform, $stamp); return "{$safix}[tm]=$stamp&{$safix}[enc]=$encode"; }else{ $flag = 0; $re_stamp = basReq::ark($safix, 'tm'); $re_encode = basReq::ark($safix, 'enc'); if(empty($re_stamp) || empty($re_encode)){ $flag = 'empty'; }elseif($stamp-$re_stamp>$time){ $flag = 'timeout'; }elseif(!($re_encode==comConvert::sysEncode($sform, $re_stamp))){ $flag = 'encode'; } if($flag){ return ($act=='flag') ? $flag : safBase::Stop('urlStamp-'.$flag); } } } static function signVeryfy($data=60,$keys=''){ global $_cbase; $stamp = $_cbase['run']['stamp']; $snid = $_cbase['safe']['rnum']; $skey = $_cbase['safe']['api']; $safix = $_cbase['safe']['safix']; $udata = is_array($data) ? $data : $_GET; $keys || implode(',',array_keys($data)); $akey = explode(',',$keys); $schk = ''; $sret = ''; foreach($udata as $key=>$val){ if(is_array($val)) continue; $sret .= "&$key=$val"; if(in_array($key,$akey)){ $schk .= "&$key=$val"; } } if(is_array($data)){ $encode = comConvert::sysEncode($schk,"$snid.$skey.$stamp"); return "{$safix}[tm]=$stamp&{$safix}[enc]=$encode{$sret}"; }else{ $ustamp = basReq::ark($safix,'tm'); if($stamp-$ustamp>intval($data)) return 'timeout'; $usign = basReq::ark($safix,'enc'); $encode = comConvert::sysEncode($schk,"$snid.$skey.$ustamp"); return $encode==$usign ? '' : 'error'; } } // --- act=init,stop,flag static function signApi($act='init',$time=3600){ global $_cbase; $stamp = $_cbase['run']['stamp']; $safix = $_cbase['safe']['safix']; $keyapi = $_cbase['safe']['api']; if($act=='init'){ $encode = md5("$keyapi.$stamp"); return "{$safix}[tm]=$stamp&{$safix}[enc]=$encode"; }else{ $flag = 0; $re_stamp = intval(basReq::ark($safix,'tm')); $re_encode = basReq::ark($safix,'enc'); if(empty($re_stamp) || empty($re_encode)) $flag = 'empty'; if($stamp-$re_stamp>$time) $flag = 'timeout'; if(!($re_encode==md5("$keyapi.$re_stamp"))) $flag = 'encode'; if($flag){ return ($act=='flag') ? $flag : safBase::Stop('urlStamp'); } } } // --- End ---------------------------------------- } ### file: /share_imcat/core/glib/glbData.php 1 ?$data : [$data] ; foreach($tarr as $rk=>$row){ $vtype = $row['vtype']; $vext = $row['vext']; if($vtype=='kv'){ $vdata = basElm::text2arr($vext); }elseif($vtype=='md'){ $vdata = extMkdown::pdorg($vext); }elseif($vtype=='json'){ $vdata = comParse::jsonDecode($vext); }elseif($vtype=='sec'){ $vext = preg_replace_callback("/\s+\[\-\-\-\]+\s+/i", function($itms){ return "[---]"; // 去=号两边空白 }, $vext); $vdata = explode('[---]', $vext); }else{ // text $vdata = ''; } if(!empty($row['exfile'])){ $tarr[$rk]['exfile'] = comStore::picsTab($row['exfile'],0); } $tarr[$rk]['vdata'] = $vdata; } return $lmt>1 ? $tarr : $tarr[0]; } // static function get($mod, $whr='', $lmt='10', $ord='', $ops=[]){ self::imod($mod); self::iwhr($whr); self::ilmt($lmt); self::iord($ord); return self::data(); } static function data(){ $db = glbDBObj::dbObj(); $sfrom = "* FROM ".$db->pre.self::$cfg['tab'].$db->ext; $where = empty(self::$whr) ? '' : self::$whr; // data if(self::$type=='count'){ $res = $db->table(self::$cfg['tab'])->where($where)->count(); self::$sql = $db->getSql(); return $res; }elseif(self::$type=='page'){ $pres = self::dpage($sfrom, $where); self::$sql = $pres[1]; $res = $pres[0]; }else{ $where && $where = "WHERE ".self::$whr; $limit = self::$type=='list' ? self::$lmt : '1'; self::$sql = "SELECT $sfrom $where ORDER BY ".self::$ord." LIMIT $limit"; $res = $db->query(self::$sql); } //dump(self::$sql); // join $fpk = self::$cfg['fpk']; if(!empty(self::$cfg['join']) && in_array($fpk, ['did','kid'])){ dopFunc::joinDext($res, self::$mod, $fpk); } if(self::$type=='1' && $res) $res = $res[0]; return $res ?: []; } static function dpage($sfrom, $where){ global $_cbase; $ord = str_replace([' ASC','DESC'], '', self::$ord); $pg = new comPager($sfrom, $where, self::$lmt, $ord); $pg->set('odesc', strpos(self::$ord,' ASC')?0:1); // ? 1,0 $pg->set('opkey', 0); $res = $pg->exe(); $sql = $pg->sql; $idfirst = ''; $idend = ''; if($res){ $i = current($res); $idfirst = current($i); $i = end($res); $idend = current($i); } $scname = basEnv::serval("REQUEST_URI"); //REQUEST_URI,SCRIPT_NAME $burl = basReq::getUri(-1,'','page|prec|ptype|pkey'); $_cbase['page']['bar'] = "
".$pg->show($idfirst,$idend,'',$burl)."
"; $_cbase['page']['prec'] = $pg->prec; $_cbase['page']['pcnt'] = intval($pg->pcnt); return [$res, $sql[0]]; } // ord: atime-1, atime static function iord($ord){ if(strpos($ord,',')){ self::$ord = $ord; return; } $ord || $ord = self::$cfg['ord'].'-1'; if(strpos($ord,'-')){ $tmp = explode('-',$ord); $ord = "$tmp[0] ".(empty($tmp[1]) ? 'ASC' : 'DESC'); }else{ $ord = "$ord DESC"; } self::$ord = $ord; } // lmt: 1, 10, 3,10, 10.page, count static function ilmt($lmt){ if($lmt=='count'){ self::$lmt = ''; self::$type = 'count'; }elseif(strpos($lmt,'.')){ self::$lmt = intval($lmt); self::$type = 'page'; }else{ self::$lmt = $lmt; self::$type = self::$lmt!='1' ? 'list' : '1'; } } // whr: `show`='all' static function iwhr($whr){ $whr = $whr ?: ''; $_groups = glbConfig::read('groups'); $pid = self::$cfg['pid']; if(in_array($pid,array('docs','users','coms','advs'))){ if(strstr($whr,"`show`='all'")){ $whr = str_replace([" AND `show`='all'","`show`='all' AND ","`show`='all'"],'',$whr); }elseif(strstr($whr,'`show`')){ // }else{ //if(!strstr($whr,'`show`=')){ $whr .= " AND (`show`='1')"; } } if(substr($whr,0,5)==' AND ') $whr = substr($whr,5); self::$whr = $whr; return $whr; } // mod: news, news.join static function imod($mod){ $_groups = glbConfig::read('groups'); self::$cfg['join'] = strpos($mod,'.'); $tmp = explode('.', $mod); self::$mod = $mod = $tmp[0]; if(empty($_groups[$mod])){ glbError::show("{$mod} NOT Found!",0); } self::$cfg['pid'] = $pid = $_groups[$mod]['pid']; // infos if($pid=='docs'){ $tab = 'docs_'.$mod; $ord = $fpk = 'did'; }elseif($pid=='users'){ $tab = 'users_'.$mod; $ord = 'atime'; $fpk = 'uid'; }elseif($pid=='advs'){ $tab = 'advs_'.$mod; $ord = 'atime'; $fpk = 'aid'; }elseif($pid=='coms'){ $tab = 'coms_'.$mod; $ord = $fpk = 'cid'; }elseif($pid=='types'){ $tab = empty($_groups[$mod]['etab']) ? 'types_common' : 'types_'.$mod; $ord = $fpk = 'kid'; //不使用 } foreach(['tab','ord','fpk'] as $k0){ self::$cfg[$k0] = $$k0; } return self::$cfg; } // 得到一笔数据:docs','users','coms','advs','types static function getRow($mod, $key, $pid=''){ if(!$pid){ $_groups = glbConfig::read('groups'); $pid = $_groups[$mod]['pid']; } $kid = $pid=='types' ? 'kid' : substr($pid,0,1).'id'; $db = glbDBObj::dbObj(); $tabid = glbDBExt::getTable($mod); $res = $db->table($tabid)->where("$kid='{$key}'")->find(); if(empty($res)){ return array(); } if(in_array($pid,array('docs'))){ $tabid = glbDBExt::getTable($mod,1); $dext = $db->table($tabid)->where("did='{$key}'")->find(); $dext && $res += $dext; } return $res; } static function fmtRow($row, $mod, $opts=array()){ foreach($row as $k => $val){ if($k=='catid'){ $row["{$k}Name"] = vopCell::cOpt($val, $mod, ','); } if($k=='mpic'){ // cPic($val,$def='',$resize=0) $resize = isset($opts['mpic_resize']) ? $opts['mpic_resize'] : 0; $mpic = vopCell::cPic($val, '', $resize); $row["mpic"] = self::fmtUrl($mpic); } if(in_array($k,['atime','etime'])){ $row["{$k}Str"] = vopCell::cTime($val); } if($k=='detail'){ $row["detail"] = basStr::filHWap($row["detail"]); } if(!empty($opts[$k])){ $cfg = $opts[$k]; $mod = empty($cfg['mod']) ? $mod : $cfg['mod']; if($cfg['type']=='cOpt'){ $row["{$k}Name"] = vopCell::cOpt($val, $cfg['mod'], ','); } if($cfg['type']=='cTime'){ $fmt = empty($cfg['fmt']) ? 'auto' : $cfg['fmt']; $row["{$k}Name"] = vopCell::cTime($val, $fmt); } } } return $row; } static function fmtList($list, $mod, $opts=array()){ foreach($list as $k => $row){ $list[$k] = self::fmtRow($row, $mod, $opts); } return $list; } static function fmtUrl($url){ if(!$url) return ''; global $_cbase; $rc = $_cbase['run']; return $rc['iss'].':'.$rc['rsite'].$url; } } ### file: /share_imcat/core/glib/admAFunc.php table('base_menu')->where("model='$muid' AND enable='1'")->order('deep,top')->select(); foreach($arr as $k=>$row){ if(!empty($row['cfgs']) &&strpos($mprm,','.$row['kid'].',')){ preg_match_all("/mkv\=([\w|\-]+)/", $row['cfgs'], $ms); if(!empty($ms[1])){ foreach($ms[1] as $mv){ if(!in_array($mv,$pmarr)){ $pmarr[] = $mv; } } } }else{ //echo $row['kid'].':flag
'; } } return implode(',',$pmarr); } static function mkvInit($mod='adm'){ $db = glbDBObj::dbObj(); $tabid = 'base_menu'; $tpl = $mod=='mkvu' ? 'umc' : 'adm'; $mlist = vopTpls::entry($tpl); if($tpl=='adm') $mlist = array_merge($mlist,vopTpls::enflow()); $dbcfg = $db->table($tabid)->where("model='$mod'")->order('pid,top,kid')->select(); $mcfg = array(); foreach($dbcfg as $k=>$v){ $mcfg[$v['kid']] = $v; } foreach($mlist as $key=>$val){ $mpos = strpos("$key)","-m)"); $pid = $mpos ? 0 : substr($key,0,strpos($key,"-")).'-m'; $deep = $mpos ? 1 : 2; $fm = array('pid'=>$pid,'enable'=>'1','deep'=>$deep,'note'=>$val,); if(isset($mcfg[$key])){ unset($mcfg[$key]); $db->table($tabid)->data(basReq::in($fm))->where("model='$mod' AND kid='$key'")->update(); }else{ $fm = array_merge($fm,array('kid'=>$key,'title'=>'','model'=>$mod,'cfgs'=>'','top'=>'888',)); $db->table($tabid)->data(basReq::in($fm))->insert(); } } foreach($mcfg as $key=>$val){ $db->table($tabid)->where("model='$mod' AND kid='$key'")->delete(); } } // umcVmods // 所有[关联模型]为$mod的模型 static function pmodSuns($mod='',$re='a'){ $_groups = glbConfig::read('groups'); $a = array(); if(!$mod) return $a; foreach($_groups as $k=>$v){ if($mod==$v['pmod']){ $a[] = $k; } } return $a; } // [关联模型]保存 static function pmodSave($omod,$pmod=''){ $oldPid = basReq::val('oldPid'); if($oldPid && $oldPid===$pmod) return; if(empty($pmod)){ //取消 glbDBExt::setOneField($omod,'pid','del'); }else{ //关联 drem(pid),demo(cnt_drem) $r = array('dbtype'=>'varchar(24)','dbdef'=>'','vreg'=>'0'); glbDBExt::setOneField($omod,'pid','check',$r); } } // modCopy, // $fm:is_del,mod_id, // $cid:modid(pro),'',reset static function modCopy($mod, $tabid, $fm, $cid=''){ $_groups = glbConfig::read('groups'); $db = glbDBObj::dbObj(); $org_arr = array('coms'=>'nrem','docs'=>'news','users'=>'person','types'=>'common','advs'=>'adpic'); if($fm=='is_del'){ $fm = $db->table($tabid)->where("kid='$cid'")->find(); $dcnt = $db->table($tabid)->where("issys='0' AND kid='$cid'")->delete(); if($dcnt){ //删除成功... if(isset($org_arr[$mod])) glbDBExt::setfieldDemo($cid, "{$mod}_$cid"); if($mod=='docs' && $fm['etab']) glbDBExt::setfieldDemo($cid, "dext_$cid"); @unlink(DIR_DTMP."/modcm/_$cid.cfg.php"); //删除缓存 if($mod=='docs' || $mod=='advs') $db->table('base_catalog')->where("model='$cid'")->delete(); if($mod=='users') $db->table('base_grade')->where("model='$cid'")->delete(); } return $dcnt ? basLang::show('admin.aaf_delok') : basLang::show('admin.aaf_errkeep'); }elseif(is_string($fm) && isset($_groups[$fm]) && is_string($cid) && isset($_groups[$cid])){ $fm_org = $db->table($tabid)->where("kid='$fm'")->find(); $fm_now = $db->table($tabid)->where("kid='$cid'")->find(); self::modCopy($mod, $tabid, 'is_del', $cid); //del self::modCopy($mod, $tabid, $fm_now, $fm); //copy return basLang::show('admin.aaf_resetok'); }elseif(is_array($fm) && $cid && empty($fm['org_tab'])){ //copy $fm_org = $db->table($tabid)->where("kid='$cid'")->find(); $fm['etab'] = $fm_org['etab']; $fm['org_tab'] = "{$mod}_$cid"; self::modCopy($mod, $tabid, $fm, $cid); //add return basLang::show('admin.aaf_copyok'); }elseif(is_array($fm)){ //add $id = basReq::in(@$fm['kid']); $org_tab = @$fm['org_tab']; unset($fm['org_tab']); $db->table($tabid)->data(basReq::in($fm))->insert(); if(isset($org_arr[$mod])){ $org_tab = empty($org_tab) ? "{$mod}_".$org_arr[$mod] : $org_tab; glbDBExt::setfieldDemo($id, "{$mod}_$id", $org_tab); if($mod=='docs' && !empty($fm['etab'])){ glbDBExt::setfieldDemo($id, "dext_$id", str_replace('docs_','dext_',$org_tab)); } } return basLang::show('admin.aaf_addok'); }else{ return basLang::show('admin.aaf_error'); } return $msg; } // upd config static function grpNav($pid,$mod){ global $_cbase; $_groups = glbConfig::read('groups'); $mkv = $_cbase['mkv']['mkv']; $str = ''; $ggap = ''; $top0 = '1'; foreach($_groups as $k=>$v){ if($v['pid']==$pid){ $top1 = substr($v['top'],0,1); $str .= (($top0!=$top1)?'
':$ggap)."
$v[title]"; $ggap = ' | '; $top0 = $top1; } } $str = str_replace("?mod=","?$mkv&mod=",$str); $str = str_replace("&mod=$mod","&mod=$mod' class='cur",$str); return $str; } // types,catalog,menus使用 static function typLay($cfg,$aurl,$pid){ if(empty($pid)){ return basLang::show('admin.aaf_ttype'); }else{ $str = "".basLang::show('admin.aaf_top')."»"; $lnk = "[v]"; $str .= comTypes::getLnks(comTypes::getLays($cfg['i'],$pid),$lnk); } return $str; } } ### file: /share_imcat/core/glib/admPFunc.php table($tabid)->order('kid DESC')->find(); if(empty($dbr)){ $kid = $def; }else{ $kid = is_numeric($dbr['kid']) ? intval($dbr['kid'])+1 : substr(basKeyid::kidAuto(12),2,10); } return $kid; } static function safeFils($vars, $ucfg, $type='exts'){ if($type=='dops'){ return $vars; } // exts,dops $fields = ['cfgs','note','gtab']; $deelA = ['admin-catalog-cfgs','admin-menus-cfgs']; foreach($vars as $key => $val) { if($key!='fm' || !is_array($val)){ continue; } foreach ($vars[$key] as $fk => $fv) { if(!in_array($fk,$fields)){ continue; } if(in_array("$ucfg[mkv]-$fk",$deelA)){ $fv = str_replace(['<'], ['<'], $fv); $fv = str_replace(['<a','</a'], ['$v){ if($v['pid']==$pmod){ if($pid!=$v['pid'] && count($pmods)>1){ $a["^group^$v[pid]"] = "$v[pid]-{$_groups[$v['pid']]['title']}"; } $a[$k] = "[$k]$v[title]"; $pid = $v['pid']; } } } return $a; } // fileNav static function fileNav($now,$cfg=array()){ $gap = "|"; $_cfg = basLang::ucfg('nava'); if(is_string($cfg) && isset($_cfg[$cfg])) $cfg = $_cfg[$cfg]; $str = ''; foreach($cfg as $file=>$title){ $file = str_replace('/','-',$file); $cur = strstr($file,$now) ? "class='cur'" : ''; if(strpos($file,'root}')){ $file = str_replace(array('{root}','{$root}',),array(PATH_PROJ,PATH_PROJ,),$file); }else{ $file = "?$file"; } $str .= ($str ? $gap : '')."$title"; } return $str; } // fileNav static function fileNavTitle($now,$cfg=array()){ $_cfg = basLang::ucfg('nava'); if(is_string($cfg) && isset($_cfg[$cfg])) $cfg = $_cfg[$cfg]; foreach($cfg as $file=>$title){ if(strstr($file,$now)){ return $title; } } return ''; } // ------------------- used in cajax.php // fieldExists static function fieldExists($kid,$mod,$_groups){ $db = db(); $sy_kids = read('keepid','sy'); if($re=basKeyid::keepCheck($kid,1,1,0)){ //$key,$chk,$fix,$grp die($re); }elseif($cmod = $db->table('base_fields')->where("model='$mod' AND kid='$kid'")->find()){ die(lang('plus.cajax_field')."[$kid]".lang('plus.cajax_exsists')); }elseif(isset($_groups[$kid]) && $_groups[$kid]['pid']=='types'){ //系统模型 die("success"); }elseif(isset($_groups[$kid]) || strstr($sy_kids,",$kid,")){ //系统模型 die("[$kid]".lang('plus.cajax_sysuesed')."[mod]"); }elseif(isset($_groups[$kid]) && $_groups[$kid]['pid']!='types'){ //系统模型 die(lang('plus.cajax_field')."[$kid]".lang('plus.cajax_syskeep')."[k1])"); }elseif(in_array($kid,fldCfgs::setKeeps())){ die("[$kid]".lang('plus.cajax_mykeys')); }else{ die("success"); } } static function fieldCatid($kid,$mod){ $catid = req('catid',''); $ccfg = read($mod,'_c'); $mfields = @$ccfg[$catid]; if($re=basKeyid::keepCheck($kid,1,0,1)){ //$key,$chk,$fix,$grp die($re); }elseif(!empty($mfields) && isset($mfields[$kid])){ die(lang('plus.cajax_field')."[$kid]".lang('plus.cajax_exsists')); }else{ die("success"); } } static function keyExists($kid,$mod,$_groups){ $db = db(); $tab = req('tab'); $_f1 = in_array($tab,array('base_catalog','base_fields','base_grade','base_menu','base_model','base_paras','types_common')); $_k2 = str_replace('types_','',$tab); $_f2 = isset($_groups[$_k2]); if(!$_f1 && !$_f2) die(lang('plus.cajax_erparam')); $kre = strtolower(basReq::ark('fm','kre','Key')); //@$fm['kre'] if(!$kid && $kre) $kid=$kre; $old = req('old_val'); if($re=basKeyid::keepCheck($kid,1,0,1,($_k2?2:3))){ //$key,$chk,$fix,$grp die($re); }elseif($kid===$old){ die("success"); }elseif(in_array($kid, fldCfgs::setKeeps())){ echo "[$kid]".lang('plus.cajax_mykeys')."[mysql]"; }elseif($flag=$db->table($tab)->where((empty($mod) ? '' : "model='$mod' AND ")."kid='$kid'")->find()){ echo "[$kid]".lang('plus.cajax_beuesed'); }else{ die("success"); } } static function infoRepeat($mod,$_groups){ $db = db(); $fid = req('fid'); $kwd = req('kwd'); // mod,kid(docs,user,coms,advs) $msg = lang('plus.cajax_erparam'); if(!isset($_groups[$mod])) die("var _repeat_res = '$msg';"); $mcfg = read($mod); $para = "[$mod:$fid=$kwd]"; if(empty($mcfg['f'][$fid])){ $re = "$para $msg!"; }elseif($kwd && $tab=glbDBExt::getTable($mod)){ $whr = "$fid='$kwd'"; $vk = glbDBExt::getTable($mod,'kid'); $vv = req('vv'); if($vv){ $whr .= " AND $vk!='$vv'"; } $flag = $db->table($tab)->where($whr)->find(); //dump($whr); $re = empty($flag) ? "success" : lang('plus.cajax_repeat'); }else{ $re = "$para $msg!"; } echo "var _repeat_res = '$re';"; } static function cfield($kid,$mod){ $db = db(); $_cfg = read($mod); $_pid = $_cfg['pid']; $_tmp = array( 'docs' =>'did', 'users'=>'uid', ); //'coms' =>'cid', if(!isset($_tmp[$_pid])) glbHtml::end(lang('plus.cajax_erparam').':mod@dop.php'); $data = $db->table("{$_pid}_$mod")->where("$_tmp[$_pid]='$kid'")->find(); fldView::lists($mod,$data,req('catid')); } } ### file: /share_imcat/core/clib/comTypes.php 个数-json字串, N<个数-数组 static function arrLays($arr,$re='json'){ $res = ''; $cnt = count($arr); foreach($arr as $k=>$row){ $kid = $row['kid']; $pid = $row['pid']; $itm = "\"$kid\":".comParse::jsonEncode($row).",\n(i_{$kid})\n"; if(empty($pid)){ $res .= $itm; }else{ $res = str_replace("\n(i_{$pid})\n","\n$itm(i_{$pid})\n",$res); } unset($arr[$k]); } $res = preg_replace("/\(i_[\w\-]{2,36}\)[\n]{1}/",'',$res); $res = "{\n".substr($res,0,strlen($res)-2)."\n}"; if(is_int($re)) $re = $cnt>=$re ? 'json' : 'arr'; $res = $re=='arr' ? comParse::jsonDecode($res) : $res; return $res; } // $arr 从db取得,ordby:deep,top static function arrSubs($arr){ $res = array(); foreach($arr as $k=>$v){ $kid = $v['kid']; $pid = $v['pid']; $v['subids'] = ','; $v['subnum'] = 0; $v['subarr'] = array(); if(empty($pid)){ $res[$kid] = $v; }else{ $res[$pid]['subarr'][$kid] = $v; while(!empty($pid)){ $res[$pid]['subids'] .= "$kid,"; //小递归到所有pid $res[$pid]['subnum']++; //小递归到所有pid $pid = $res[$pid]['pid']; } } unset($arr[$k]); } return $res; } // xxx static function getChars($arr,$deep='12345'){ $a = array(); foreach($arr as $k=>$v){ if(!strstr($deep,$v['deep'])) continue; $v['kid'] = $k; $a[$v['char']][] = $v; } ksort($a); return $a; } // getSubs,所有pid以下的子分类 static function getSubs($arr, $pid='0', $deep='12345', $ra=1){ $start = '0'; $fdeep = '-1'; $a = array(); if(empty($arr)) return empty($ra) ? 0 : $a; foreach($arr as $k=>$v){ if(!isset($v['deep'])) $v['deep'] = '1'; if(!isset($v['pid'])) $v['pid'] = '0'; if($start && $fdeep>$v['deep']) break; if($v['pid']===$pid){ $start = '1'; $fdeep = $v['deep']; } if($start && strstr($deep,"$v[deep]")){ $a[$k] = $v; } } $re = empty($ra) ? count($a) : $a; return $re; } // getPars(所有最大级别pmax外的父分类) static function getPars($arr,$pmax='3'){ $a = array(); foreach($arr as $k=>$v){ if($pmax==$v['deep']) continue; $a[$k] = $v; } return $a; } // getLays(id对应的树形分类:键值下标) static function getLays($arr, $id, $a=array()){ $a[$id] = empty($arr[$id]['title']) ? '' : $arr[$id]['title']; $pid = empty($arr[$id]['pid']) ? '' : $arr[$id]['pid']; if($pid){ return self::getLays($arr, $pid, $a); }else{ if(count($a)>1) $a = array_reverse($a, true); return $a; } } // getLarr(id对应的树形分类:数组下标) static function getLarr($arr, $id, $key='kid', $a=array()){ foreach($arr as $ik=>$iv) { if($iv[$key]==$id){ $a[$id] = $iv['title']; if(!empty($iv['pid'])){ return self::getLarr($arr, $iv['pid'], $key, $a); } } } if(count($a)>1) $a = array_reverse($a, true); return $a; } // getLnks(arr对应的连接) static function getLnks($arr,$tpl="[v]",$gap='»'){ $str = ''; foreach($arr as $k=>$v){ $lnk = str_replace(array('[k]','[v]'),array($k,$v),$tpl); $str .= (empty($str) ? '' : $gap).$lnk; } return $str; } // getOptions(Select) static function getOpt($arr,$def='',$msg='',$frame=1){ $_groups = glbConfig::read('groups'); if(is_string($arr) && isset($_groups[$arr])){ $imod = glbConfig::read($arr); $arr = $imod['i']; } $a = basArray::opaItems($arr,'',$frame); return basElm::setOption($a,$def,empty($msg) ? '-(def)-' : $msg); } } ### file: /share_imcat/core/clib/comImage.php $row) { $full = "$dir/$file"; $res[] = self::compcut($full, $max); if(strpos($file,'.jpg') && $row[1]>$size*1024){ self::compress($full, 80); } } return $res; } // 限制图片大小, 针对jpg public static function compcut($full, $max=2400){ $info = self::info($full); if($info['width']>$max || $info['height']>$max){ if($info['width']>$info['height']){ $h = $info['height']*$max/$info['width']; $w = $max; }else{ $w = $info['width']*$max/$info['height']; $h = $max; } self::thumb($full, $full, $w, $h); } return $info; } public static function compress($target, $quality=75){ if($srcInfo = @getimagesize($target)){ switch ($srcInfo[2]){ case 1: break; case 2: $srcim =imagecreatefromjpeg($target); imagejpeg($srcim,$target,$quality); break; case 3: $srcim =imagecreatefrompng($target); $pngQuality = ($quality - 100) / 11.111111; $pngQuality = round(abs($pngQuality)); imagepng($srcim,$target,$pngQuality); break; default: return; } } } static function info($img) { $imageInfo = getimagesize($img); // riff webpvp8 格式,不能获取到信息 if( $imageInfo!== false) { $imageType = strtolower(substr(image_type_to_extension($imageInfo[2]),1)); $imageSize = filesize($img); $info = array( "width"=>$imageInfo[0], "height"=>$imageInfo[1], "type"=>$imageType, "size"=>$imageSize, "mime"=>$imageInfo['mime'] ); return $info; }else { return false; } } static function thumb($image,$thumbname,$maxWidth=120,$maxHeight=90,$interlace=true,$type=''){ $ire = self::_thpos($image, $maxWidth, $maxHeight); if(!$ire) return false; extract($ire); // 载入原图 $func = 'ImageCreateFrom'.($type=='jpg'?'jpeg':$type); $srcImg = $func($image); // 创建缩略图 $func = ($type!='gif' && function_exists('imagecreatetruecolor')) ? 'imagecreatetruecolor' : 'imagecreate'; $thumbImg = $func($maxWidth, $maxHeight); // 填充白底 $bg_color = imagecolorallocate($thumbImg, 204,204,204); imagefill($thumbImg,0,0,$bg_color); // 复制图片 $func = function_exists("ImageCopyResampled") ? "ImageCopyResampled" : "ImageCopyResized"; $func($thumbImg,$srcImg, $ox,$oy, $ix,$iy, $ow,$oh, $iw,$ih); if('gif'==$type || 'png'==$type) { // 设置为透明色 imagecolortransparent($thumbImg,$bg_color); }else{ // 对jpeg图形设置隔行扫描 if('jpg'==$type || 'jpeg'==$type) imageinterlace($thumbImg, $interlace?1:0); } // 生成图片 $func = 'image'.($type=='jpg'?'jpeg':$type); $func($thumbImg,$thumbname); imagedestroy($thumbImg); imagedestroy($srcImg); return $thumbname; } // {staticroot}/icons/basic/demo_pic1.jpg // http://img.domain.com/imcat/demo/abc.jpg // {ures}/demo/abc.jpg static function thpic($val,$resize){ // 还原完整路径 $orgd = str_replace(array('{uresroot}','{staticroot}'),array(DIR_URES,DIR_STATIC),$val); $orgp = str_replace(array('{uresroot}','{staticroot}'),array(PATH_URES,PATH_STATIC),$val); $repath = read('repath','sy'); $redir = empty($repath['dir']) ? array() : $repath['dir']; $reatt = empty($repath['att']) ? array() : $repath['att']; if(!empty($redir)){ $orgd = str_replace(array_keys($redir),array_values($redir),$orgd); } if(!empty($reatt)){ $orgp = str_replace(array_keys($reatt),array_values($reatt),$orgp); } // 目标路径 $ext = strrchr($val,'.'); $objd = str_replace($ext,"-$resize$ext",$orgd); $objp = str_replace($ext,"-$resize$ext",$orgp); if(strpos($objp,'://')>0){ // out-cdn/ftp:根据具体情况修改了... if(strpos($orgp,PATH_URES)===false) return $orgp; // http://img.xcdn.com/dir/file.ext $scfg = glbConfig::read('store','ex'); if(!isset($scfg[$scfg['type']]['cut_ures'])) return $orgp; $cutp = $scfg[$scfg['type']]['cut_ures']; // http://domain.com/cut.php? return str_replace(array("(size)","(img)"),array($resize,$orgp),$cutp); }elseif(file_exists($objd)){ // 有缩略图 return $objp; }elseif(file_exists($orgd)){ // (本地)有原图片, $size = explode('x',$resize); $res = self::thumb($orgd,$objd,$size[0],$size[1]); return $res ? $objp : $orgp; } return $orgp; } // 描边文字水印 static function wmtext($image, $text, $waterPos=array(9,10)){ //读取原图像文件 $imageInfo = self::info($image); $image_w = $imageInfo['width']; //取得水印图片的宽 $image_h = $imageInfo['height']; //取得水印图片的高 //读取水印文字配置 $waterInfo = glbConfig::read('wmark','sy'); $w = $waterInfo['width']; //取得水印图片的宽 $h = $waterInfo['height']; //取得水印图片的高ctext if($image_w<=$w || $image_h<=$h){ return 'file too SMALL!'; } $func = "imagecreatefrom" . $imageInfo['type']; $image_im = $func($image); $pos = self::_wpos($image_w, $image_h, $w, $h, $waterPos); $posX = $pos[0]; $posY = $pos[1]; //设定图像的混色模式 imagealphablending($image_im, true); foreach(array('ctext','cborder') as $k){ $$k = imagecolorallocate($image_im, $waterInfo[$k], $waterInfo[$k], $waterInfo[$k]); } $tfont = DIR_STATIC.$waterInfo['font']; $ia = array(1,-1,-1,1,0); $ja = array(1,1,-1,-1,0); for($i=0;$i<5;$i++){ //先4个象限移动1px,再到0,实现描边(Peace) $tcolor = empty($ia[$i]) ? $ctext : $cborder; imagettftext($image_im, $waterInfo['size'], 0, $posX+$ia[$i], $posY+$ja[$i], $tcolor, $tfont, $text); } //生成水印后的图片 $func = "image" . $imageInfo['type']; $func($image_im, $image); //释放内存 $imageInfo = NULL; imagedestroy($image_im); } // 图片水印 static function wmpic($image, $water, $waterPos=array(9,10)){ //读取原图像文件 $imageInfo = self::info($image); $image_w = $imageInfo['width']; //取得水印图片的宽 $image_h = $imageInfo['height']; //取得水印图片的高 //读取水印文件 $waterInfo = self::info($water); $w = $waterInfo['width']; //取得水印图片的宽 $h = $waterInfo['height']; //取得水印图片的高 if($image_w<=$w || $image_h<=$h){ return 'file too SMALL!'; } $func = "imagecreatefrom" . $imageInfo['type']; $image_im = $func($image); $func = "imagecreatefrom" . $waterInfo['type']; $water_im = $func($water); $pos = self::_wpos($image_w, $image_h, $w, $h, $waterPos); $posX = $pos[0]; $posY = $pos[1]; //设定图像的混色模式 imagealphablending($image_im, true); imagecopy($image_im, $water_im, $posX, $posY, 0, 0, $w, $h); //拷贝水印到目标文件 //生成水印后的图片 $func = "image" . $imageInfo['type']; $func($image_im, $image); //释放内存 $waterInfo = $imageInfo = NULL; imagedestroy($image_im); imagedestroy($water_im); } static function wmark($image, $type=0, $waterPos=array()){ if(!file_exists($image)){ //检查图片是否存在 return 'file NOT exists!'; } $wcfgs = glbConfig::read('wmark','sy'); if(empty($waterPos)) $waterPos = $wcfgs['pos']; if(empty($type) || in_array($type,array('pic','text'))){ if(empty($type)) $type = $wcfgs['type']; if($type=='pic' && file_exists(DIR_VIEWS.$wcfgs['plogo'])){ return self::wmpic($image, DIR_VIEWS.$wcfgs['plogo'], $waterPos); }else{ return self::wmtext($image, $wcfgs['stext'], $waterPos); } }elseif(file_exists($type)){ return self::wmpic($image, $type, $waterPos); }else{ return self::wmtext($image, $type, $waterPos); } } // 水印位置(0-9,margin=10), (+-x,+-y) static function _wpos($image_w, $image_h, $w, $h, $waterPos=array(0,10)){ $pos = $x = $waterPos[0]; //九宫格位置,坐标位置x $gap = $y = $waterPos[1]; //九宫格边距,坐标位置y $posX = $posY = 0; if(abs($pos)<10){ switch ($pos) { case 1: //1为顶端居左 $posX = $gap; $posY = $gap; break; case 2: //2为顶端居中 $posX = ($image_w - $w) / 2; $posY = $gap; break; case 3: //3为顶端居右 $posX = $image_w - $w - $gap; $posY = $gap; break; case 4: //4为中部居左 $posX = $gap; $posY = ($image_h - $h) / 2; break; case 5: //5为中部居中 $posX = ($image_w - $w) / 2; $posY = ($image_h - $h) / 2; break; case 6: //6为中部居右 $posX = $image_w - $w - $gap; $posY = ($image_h - $h) / 2; break; case 7: //7为底端居左 $posX = $gap; $posY = $image_h - $h - $gap; break; case 8: //8为底端居中 $posX = ($image_w - $w) / 2; $posY = $image_h - $h - $gap; break; case 9: //9为底端居右 $posX = $image_w - $w - $gap; $posY = $image_h - $h - $gap; break; default: //0,随机 $posX = rand(0, ($image_w - $w)); $posY = rand(0, ($image_h - $h)); break; } if($posX<0) $posX = rand(0, ($image_w - $w)); if($posY<0) $posX = rand(0, ($image_h - $h)); }else{ $posX = $x<0 ? $image_w + $x: $x; $posY = $y<0 ? $image_h + $y: $y; } return array($posX, $posY); } static function _thpos($image, $ow, $oh){ $img = self::info($image); if(!$img) return false; $iw = $img['width']; $ih = $img['height']; $res = array( 'type'=>$img['type'], 'ix'=>0,'iy'=>0,'iw'=>$iw,'ih'=>$ih, 'ox'=>0,'oy'=>0,'ow'=>$ow,'oh'=>$oh, ); if($iw>$ow && $ih>$oh){ $is = $iw/$ih; $os = $ow/$oh; if($is>$os){ // 太宽(截取) $ew = $ih * $os; $dw = intval(($iw-$ew)/2); $res['ix'] = $dw; $res['iw'] = $ew; }elseif($os>$is){ // 太高(截取) $eh = $iw / $os; $dh = intval(($ih-$eh)/2); $res['iy'] = $dh; $res['ih'] = $eh; } }elseif($iw>$ow){ // 太宽(截取+补边) $dw = intval(($iw-$ow)/2); $dh = intval(($oh-$ih)/2); $res['oy'] = $dh; $res['oh'] = $ih; $res['ix'] = $dw; $res['iw'] = $ow; }elseif($ih>$oh){ // 太高(截取+补边) $dw = intval(($ow-$iw)/2); $dh = intval(($ih-$oh)/2); $res['ox'] = $dw; $res['ow'] = $iw; $res['iy'] = $dh; $res['ih'] = $oh; }else{ // return false; //$res } return $res; } } ### file: /share_imcat/core/clib/comSession.php ', return $xStr; } static function guid($flg='',$nsp='',$mode=0){ //mode:Cook,Sess,UIP global $_cbase; $sipck = empty($mode) ? $_cbase['ucfg']['guid'] : $mode; if(empty($sipck) || !in_array($sipck,array('Sess','UIP','Cook'))) $sipck = 'Cook'; $func = "get$sipck"; $sipck = self::$func($nsp); $ua = $_cbase['run']['userag']; $fix = empty($nsp) ? (@$_cbase['safe']['site']) : $nsp; strstr($flg,'time') && $fix .= '@'.$_cbase['run']['timer']; strstr($flg,'safil') && $fix .= '@'.$_cbase['safe']['safil']; $enc = md5($sipck.$fix.$ua); //,'fix'=>$fix return array('sip'=>$sipck,'sua'=>$ua,'sid'=>$enc); } // cookie static function getCook($nsp=''){ global $_cbase; if(!empty(self::$guid_ck[$nsp])) return self::$guid_ck[$nsp]; $ua = md5($_cbase['run']['userag'].$nsp); $ckey = "{$nsp}_".substr($ua,0,12); $cval = comCookie::oget($ckey); if(strlen($cval)<32){ $cval = basKeyid::kidTemp().'-'.basKeyid::kidRand('24',9).'-'.substr($ua,9,9); comCookie::oset($ckey,$cval,31622400); //86400*366 = 31 622 400 } self::$guid_ck[$nsp] = $cval; return self::$guid_ck[$nsp]; } // session_id static function getSess($nsp=''){ return session_id(); } // 获取客户端真实IP(用于guid,session判断) static function getUIP($nsp=''){ return basEnv::userIP(); } } ### file: /share_imcat/core/clib/comPager.php sfrom = $sfrom; $this->where = $where; $this->psize = $psize; $this->order = $order; if(strpos($order,'.') || strpos($order,' ')){ $this->orderb = substr($order,strpos($order,'.')+1); }else{ $this->orderb = $order; } // init; $a = array('page','prec','ptype','pkey',); // 'odesc','opkey', foreach($a as $k){ if(isset($_GET[$k])){ $__v = basReq::val($k,'Key',24); if(in_array($k,array('page',))) $__v = max(1,intval($__v)); if(in_array($k,array('prec',))) $__v = max(0,intval($__v)); $this->$k = $__v; } } if(''!==$om=basReq::val('odesc','N',1)){ $this->odesc = $om; } } function set($key,$value=0){ if(is_array($key)){ foreach($key as $k=>$v) $this->set($k,$v); }else{ $this->$key = $value; } } function sql($cnt=''){ $sfrom = ' SELECT '.$this->sfrom; if($cnt){ $where = $this->where ? ' WHERE '.$this->where : ''; $this->sql[1] = basSql::fmtCount($sfrom.$where,$cnt); return $this->sql[1]; }else{ $where = ' WHERE '.($this->where ? $this->where : '1=1'); $ptype = $this->ptype; $pkey = $this->pkey; $odesc = $this->odesc; if($this->opkey&&$ptype){ if($ptype=='start'){ //$where .= ""; }else if($ptype=='end'){ //$where .= ""; }else if($ptype=='next'){ if($odesc) $where .= " AND {$this->order}<'$pkey'"; if(!$odesc) $where .= " AND {$this->order}>'$pkey'"; }else if($ptype=='prev'){ if($odesc) $where .= " AND {$this->order}>'$pkey'"; if(!$odesc) $where .= " AND {$this->order}<'$pkey'"; } if($ptype=='end'){ $lcnt = $this->prec%$this->psize; $lcnt = $lcnt ? $lcnt : $this->psize; $limit = ' LIMIT '.$lcnt; }else{ $limit = ' LIMIT '.$this->psize; } }else{ $offset = ($this->page-1)*$this->psize; $limit = " LIMIT $offset,".$this->psize; } if($where==' WHERE 1=1') $where = ""; if($ptype=='end'||$ptype=='prev'){ $ord_in = ' ORDER BY '.$this->order.($this->odesc ? '' : ' DESC'); $ord_out = ' ORDER BY '.$this->orderb.($this->odesc ? ' DESC' : ''); $this->sql[0] = "SELECT * FROM ($sfrom $where $ord_in $limit) _tab__ $ord_out "; }else{ $order = ' ORDER BY '.$this->order.($this->odesc ? ' DESC' : ''); $this->sql[0] = $sfrom.$where.$order.$limit; } return $this->sql[0]; } } function exe($dbkey=''){ $db = glbDBObj::dbObj($dbkey); $rs = $db->query($this->sql()); if(!$this->prec){ $rec = $db->query($this->sql('_rc_recs_')); $this->prec = $rec[0]['_rc_recs_']; } $this->pcnt = ceil($this->prec/$this->psize); $this->bar = $this->links(); return $rs; } function show($kfirst='',$klast='',$type='',$pbase=''){ $pbase = empty($pbase) ? basReq::getUri(-1,'','page|prec|ptype|pkey') : $pbase; $a = $this->bar; $bar = ''; $para = "&prec=$this->prec&page="; $p0 = array("{pfirst}","{pprev}","{pnext}","{plast}",); $p1 = array("{$para}1","$para".($this->page-1),"$para".($this->page+1),"$para".$this->pcnt,); if($this->opkey){ $p1[0] .= "&ptype=start"; $p1[1] .= "&ptype=prev&pkey=$kfirst"; $p1[2] .= "&ptype=next&pkey=$klast"; $p1[3] .= "&ptype=end"; } $a['pjump'] = str_replace("{pjump}","{$para}0&ptype=0",$a['pjump']); foreach($a as $k=>$v){ $v = str_replace("
  • ","\n
  • ",$v); if(in_array($k,array('first','prev','next','last'))){ $v = str_replace($p0,$p1,$v); } $bar .= $v; } //echo $pbase; $bar = str_replace(["{url}&",'{url}'], [strpos($pbase,'?')>0?"$pbase&":"$pbase?","$pbase"], $bar); foreach ($this->cfg as $ck => $cv) { $this->cfg[$ck] = str_replace($p0, $p1, $this->cfg[$ck]); $this->cfg[$ck] = str_replace(["{url}&",'{url}'], [strpos($pbase,'?')>0?"$pbase&":"$pbase?","$pbase"], $this->cfg[$ck]); } return "
      \n$bar
    \n"; } function links(){ $pcnt = intval($this->pcnt); $a = array(); $sFirst = ''; $sPrev = '«'; $sNext = '»'; $sLast = ''; $a['pagno'] = "
  • $this->page/$pcnt
  • \n"; $a['first'] = "
  • $sFirst
  • \n"; $a['prev'] = "
  • $sPrev
  • \n"; $a['pjump'] = "
  • \n"; $a['next'] = "
  • $sNext
  • \n"; $a['last'] = "
  • $sLast
  • \n"; $a['total'] = "
  • $this->prec
  • \n"; $cfg['page'] = $this->page; $cfg['pcnt'] = $pcnt; $cfg['first'] = $cfg['prev'] = $cfg['next'] = $cfg['last'] = ' if($pcnt<=1) return $a; if($this->page==$pcnt){ $a['first'] = "
  • $sFirst
  • \n"; $a['prev'] = "
  • $sPrev
  • \n"; $cfg['first'] = "{url}{pfirst}"; $cfg['prev'] = "{url}{pprev}"; }elseif($this->page==1){ $a['next'] = "
  • $sNext
  • \n"; $a['last'] = "
  • $sLast
  • \n"; $cfg['next'] = "{url}{pnext}"; $cfg['last'] = "{url}{plast}"; }else{ $a['first'] = "
  • $sFirst
  • \n"; $a['prev'] = "
  • $sPrev
  • \n"; $a['next'] = "
  • $sNext
  • \n"; $a['last'] = "
  • $sLast
  • \n"; // $cfg['first'] = "{url}{pfirst}"; $cfg['prev'] = "{url}{pprev}"; $cfg['next'] = "{url}{pnext}"; $cfg['last'] = "{url}{plast}"; } $this->cfg = $cfg; return $a; } static function fixUrl($key='home'){ global $_cbase; $bar = &$_cbase['page']['bar']; if(!strpos($bar,"?$key&")){ $bar = str_replace('?',"?$key&",$bar); } return $bar; } } ### file: /share_imcat/core/clib/comVCode.php 0, '5'=>85, 'A'=>170, 'F'=>255]; self::$ctabN['5'] = ['00'=>0, '40'=>64, '80'=>128, 'C0'=>192, 'F0'=>255]; self::$ctabN['6'] = ['0'=>0, '3'=>51, '6'=>102, '9'=>153, 'C'=>204, 'F'=>255]; // self::$ctabA['6'] = [ '0'=>['6','9','C','F'], '3'=>[ '9','C','F'], '6'=>['0', 'C','F'], '9'=>['0','3', 'F'], 'C'=>['0','3','6' ], 'F'=>['0','3','6','9'], ]; self::$ctabB['6'] = [ '0'=>['3'], '3'=>['0','6'], '6'=>['3','9'], '9'=>['6','C'], 'C'=>['9','F'], 'F'=>['C'], ]; } static function tabrc($n=6, $rc3=0, $rx=0){ $tbcn = self::$ctabN['6']; $tbkn = array_keys($tbcn); $tban = self::$ctabA['6']; $tbbn = self::$ctabB['6']; if(!$n){ return $rc3 ? implode('',$tb3) : [$tbcn[$tb3[0]],$tbcn[$tb3[1]],$tbcn[$tb3[2]]]; } $tb3 = $ts1 = []; shuffle($tbkn); $xb3 = $xs1 = []; for($i=0;$i<3;$i++){ $tb3[] = $k1 = $tbkn[$i]; $ts1[] = $tban[$k1]; $xb3[] = $k1 = $tbkn[$i]; $xs1[] = $tbbn[$k1]; } $ts3[] = $rc3 ? implode('',$tb3) : [$tbcn[$tb3[0]],$tbcn[$tb3[1]],$tbcn[$tb3[2]]]; for($i=0;$i<$n;$i++){ $k1 = array_rand($ts1[0],1); $c1=$ts1[0][$k1]; $k2 = array_rand($ts1[1],1); $c2=$ts1[1][$k2]; $k3 = array_rand($ts1[2],1); $c3=$ts1[2][$k3]; $ts3[] = $rc3 ? "$c1$c2$c3" : [$tbcn[$c1],$tbcn[$c2],$tbcn[$c3]]; $k1 = array_rand($xs1[0],1); $c1=$xs1[0][$k1]; $k2 = array_rand($xs1[1],1); $c2=$xs1[1][$k2]; $k3 = array_rand($xs1[2],1); $c3=$xs1[2][$k3]; $xs3[] = $rc3 ? "$c1$c2$c3" : [$tbcn[$c1],$tbcn[$c2],$tbcn[$c3]]; } return [$ts3, $xs3]; } function __construct($mod='(istest)', $ttf='', $corg='0'){ $this->mod = $mod; $this->ttf = $ttf; $this->corg = $corg; self::initTab(); // 显示图片一般图片 if(function_exists('imagecreate')){ $this->show(); }else{ //bmp glbError::show("NO function:imagecreate!"); } } function init(){ if($this->mod=='(emtel)'){ $this->code = $this->corg; $this->imw = 20+strlen($this->corg)*20; }else{ $this->code = self::strRand(); } $this->im = imagecreate($this->imw, $this->imh); // 填充 $this->ctbs = $this->tabrc(strlen($this->code), 0, 1); $this->bgColor = $this->rndCimg($this->ctbs[0][0]); imagefill($this->im,0,0,$this->bgColor); } // 输出 function output(){ $typa = array(1=>'gif', 2=>'png', 3=>'jpeg'); $type = $typa[rand(1,3)]; basEnv::obClean(); $func = "image$type"; //imagejpeg $func($this->im); } // 显示 function show(){ $this->init(); safComm::formCVimg($this->mod, $this->code, 'save'); // 干扰: 点,线,特殊字符,雪花 if($this->mod!='(emtel)'){ $r = rand(1,4); if($r==1) $this->_rndPixels(); if($r==2) $this->_rndLines(); if($r==3) $this->_rndChars(); if($r==4) $this->_rndSnow(); } $this->drawStr(); // Draw字符,划边框 //$this->distOrtion(); // 扭曲文字 $this->output(); imagedestroy($this->im); if(is_resource($this->dis)){ imagedestroy($this->dis); } } // Draw字符 function drawStr(){ for($i=0;$icode);$i++) { $chr = $this->code[$i]; if($this->mod=='(emtel)'){ $size = 20; }elseif(ord($chr)>96){ $size = mt_rand(22,26); }else{ $size = mt_rand(16,20); } $angle = $this->mod=='(emtel)' ? 0 : mt_rand(-20,20); $x = $this->mod=='(emtel)' ? $i*20+8 : mt_rand(15,20)+$i*26; $y = $this->mod=='(emtel)' ? mt_rand(24,30) : mt_rand(27,30); $ffile = $this->rndFonts(); $tcolor = $this->rndCimg($this->ctbs[0][$i+1]); if($this->mod!='(emtel)'){ // 外围描边(空心效果) ctab -> ctbs $cb = $this->rndCimg($this->ctbs[1][$i]); imagettftext($this->im, $size, $angle, $x+1, $y, $cb, $ffile, $chr); // x imagettftext($this->im, $size, $angle, $x, $y+1, $cb, $ffile, $chr); // y } // 文字本身 imagettftext($this->im, $size, $angle, $x, $y, $tcolor, $ffile, $chr); } } function rndCimg($ctab){ $cl = imagecolorallocate($this->im, $ctab[0], $ctab[1], $ctab[2]); if($cl===false){ $cl = imagecolorclosest($this->im, $ctab[0], $ctab[1], $ctab[2]); } return $cl; } // 随机颜色 function rndColor($no=0){ $ct = []; for($i=0;$i<3;$i++){ $ct[]=mt_rand(2,254); } $cl = $this->rndCimg($ct); return $cl; } // 随机Font public function rndFonts(){ if(is_string($this->ttf)){ $tti = $this->ttf; }else{ $tti = $this->ttf[mt_rand(0,count($this->ttf)-1)]; while($this->ttOld==$tti){ $tti = $this->ttf[mt_rand(0,count($this->ttf)-1)]; } $this->ttOld = $tti; } $ffile = DIR_STATIC.'/media/fonts/'.$tti.'.ttf'; return $ffile; } // 干扰象素 function _rndPixels(){ //加入干扰象素 for($i=0;$i<200;$i++){ imagesetpixel($this->im, rand()%160 , rand()%100 , $this->rndColor()); } } // 干扰线 function _rndLines(){ $w = $this->imw-2; $h = $this->imh-2; $cnt = mt_rand(5,8); for($j=2;$j<$cnt;$j++){ imageline($this->im, rand(2,$w),rand(2,$h),rand(2,$w),rand(2,$h), $this->rndColor() ); //18 } imagerectangle($this->im, 0, 0, $this->imw-1, $this->imh-1, $this->rndColor()); // 边框 } // 干扰字符 function _rndChars(){ if(empty($this->ttf)){ return; } $cnt = mt_rand(5,10); //《!" $chars = array('!',"'",'(',')',',','/',";","?","^","`","~"); for($i=1; $i<=$cnt; $i++){ imagestring($this->im,mt_rand(1,5),mt_rand(1,$this->imw),mt_rand(1,$this->imh),$chars[mt_rand(0,4)],$this->rndColor()); } } // 雪花 function _rndSnow(){ for ($i=0;$i<30;$i++) { $color = imagecolorallocate($this->im,mt_rand(200,255),mt_rand(200,255),mt_rand(200,255)); imagestring($this->im,mt_rand(2,5),mt_rand(0,$this->imw),mt_rand(0,$this->imh),'*',$color); } } // 扭曲文字 public function distOrtion(){ $rate = floor(0.08 * $this->imh); // 扭曲程度 $this->dis = imagecreatetruecolor($this->imw, $this->imh); imagefill($this->dis, 0, 0, $this->bgColor); for ($x = 0; $x < $this->imw; $x++) { for ($y = 0; $y < $this->imh; $y++) { $rgb = imagecolorat($this->im, $x, $y); if( (int)($x + sin($y / $this->imh * 2 * M_PI) * $rate) <= $this->imw && (int)($x + sin($y / $this->imh * 2 * M_PI) * $rate) >= 0 ) { imagesetpixel($this->dis, (int)($x + sin($y / $this->imh * 2 * M_PI - M_PI * 0.1) * $rate) , $y, $rgb); } } } $this->im = $this->dis; } // *** 随机码 static function strRand(){ global $_cbase; $vimg = $_cbase['ucfg']['vimg']; $type = in_array($vimg,array('0','H','K')) ? $vimg : 'K'; $str = basKeyid::kidRand($type,rand(4,5)); return strtoupper($str); } // 颜色表 //basDebug::bugLogs('vcode', $this->code, 'vcode.txt', 'file'); } ### file: /share_imcat/core/clib/comStore.php moveUres($org, $obj, $fmove); } return $cfg['spre'].$obj.$cfg['sfix']; } // 删除:删除id下的附件资源 static function delFiles($mod, $kid){ if(empty($kid)){ return; } $dir = comStore::getResDir($mod, $kid, 0); $re = comFiles::delDir(DIR_URES.'/'.$dir, 1); $tabs = self::rsType($dir); foreach($tabs as $cls=>$cfg) { $rsObj = self::rsCobj($cls); $re = $rsObj->delFiles($dir); } return $re; } static function rsType($fpdir){ // news/2018/9k-dj1t/2018-9k-dj41.jpg // news/2018/9k-dj1t/2018-9k-dj41 self::storeCfgs(); $clsName = 'rsLocal'; // default $tmp = explode('/', $fpdir); $dfix = $tmp[0].'/'; if(strpos($fpdir,'.')>0){ $ticon = comFiles::getTIcon($fpdir); // type,icon $ftype = $ticon['type']; foreach(self::$cfgs['types'] as $cls=>$cfg) { $indir = empty($cfg['mdirs']) || in_array($dfix,$cfg['mdirs']); $intype = empty($cfg['ftypes']) || in_array($ftype,$cfg['ftypes']); if($indir && $intype){ return $cls; } } return $clsName; }else{ $res = array(); foreach(self::$cfgs['types'] as $cls=>$cfg) { if(empty($cfg['mdirs']) || in_array($dfix,$cfg['mdirs'])){ $res[$cls] = $cfg; } } return empty($res) ? $clsName : $res; } } static function rsCobj($fname){ if(empty(self::$objs[$fname])){ require_once DIR_IMCAT."/adpt/store/$fname.php"; $class = "\\imcat\\$fname"; self::$objs[$fname] = new $class(); } return self::$objs[$fname]; } static function getTmpDir($isfull=1){ $user = usrBase::userObj(); $sid = empty($user->sinit['sid']) ? usrPerm::getUniqueid('Cook','sip') : $user->sinit['sid']; $path = "@udoc/$sid"; //$modFix- comFiles::chkDirs($path, 'dtmp', 0); return ($isfull ? DIR_DTMP.'/' : '')."$path"; //PATH_ROOT } static function fixTmpDir($path){ $pos = strpos($path,"/@udoc/"); $path = PATH_DTMP.substr($path, $pos); return $path; } static function getResDir($mod, $kid, $isfull=1, $chkdir=0){ $grs = glbConfig::read('groups'); $mcfgs = empty($grs[$mod]) ? array() : $grs[$mod]; if(empty($kid)){ die(__FUNCTION__); } $kpath = $kid; $fmts = glbConfig::read('frame.resfmt', 'sy'); // docs,users; types; advs,coms $fmt = (!empty($mcfgs['pid']) && in_array($mcfgs['pid'],array('docs','users'))) ? 1 : 0; foreach($fmts as $k=>$v){ // 默认:fmt=1 : yyyy/md-noid if(in_array($mod,$v)){ $fmt=$k; break; } } if(!empty($fmt) && strpos($kid,'-')>0){ $ka = explode('-',$kid); if($fmt==1) $kpath = $ka[0].'/'.$ka[1].(empty($ka[2])?'':'-'.$ka[2]); if($fmt==2) $kpath = $ka[0].'-'.$ka[1].(empty($ka[2])?'':'/'.$ka[2]); if($fmt==3) $kpath = $ka[0].'/'.$ka[1].(empty($ka[2])?'':'/'.$ka[2]); if($fmt==6){ // /html/news-16/ab-8899.html $repath = "$mod-".substr($kpath,2,2)."/".substr($kpath,5); }else{ $repath = "$mod/$kpath"; } }else{ $repath = "$mod/$kpath"; //empty($kpath); } $chkdir && comFiles::chkDirs($repath, 'ures', 0); return ($isfull ? DIR_URES.'/' : '').$repath; } // 移动一个字段的附件文件:comStore::moveTmpField($dop,'exp_t01'); static function moveTmpField(&$dop, $fid, $mod, $did, $ishtml=0){ if(!strpos($dop->fmv[$fid],'/@udoc/')){ return; } $dop->fmv[$fid] = self::moveTmpDir($dop->fmv[$fid], $mod, $did, $ishtml); } //移动临时文件夹中的文件 static function moveTmpDir($str, $mod, $kid, $ishtml=0){ self::storeCfgs(); $ar2 = self::moveTmpFmt($str, $ishtml); if(empty($ar2)) return $str; foreach($ar2 as $v){ if(self::moveTmpOne($str, $v, $mod, $kid)) continue; $cfg = array( array('ures', "/$mod"), array('html', "/$mod"), array('static', "/"), array('root', "/"), ); foreach($cfg as $cv){ $str = self::moveRepRoot($str, $v, $cv[0], $cv[1]); } } foreach(self::$cfgs['types'] as $tk=>$row){ if(!empty($row['vpre']) && !empty($row['spre']) && strpos($str,$row['vpre'])>=0){ $str = str_replace($row['vpre'], $row['spre'], $str); } } return $str; } // deel:@udoc static function moveTmpOne(&$str, $v, $mod, $kid){ global $_cbase; $fix = PATH_DTMP."/@udoc/"; $flag = 0; if($org=strstr($v,$fix)){ $orgfile = DIR_DTMP.substr($org, strlen(PATH_DTMP)); $obj = self::getResDir($mod,$kid,0,1)."/".basename($org); // 可能:mpic,content:有同一个图片,第一次移动后,第二次就不存在了,所以也要替换 $fmove = is_file($orgfile); $rmove = self::moveUres($orgfile, $obj, $fmove); $str = str_replace($v, $rmove, $str); $flag = 1; } return $flag; } // str2arr static function moveTmpFmt($str, $ishtml=0){ if($ishtml){ //a,img,embed,value?, preg_match_all("/\s+(src|href|value)=(\S+)[\s|>]+/i", $str, $arr); //3 $ar2 = empty($arr[2]) ? array() : str_replace(array("\\",'"',"'"), array(), $arr[2]); }else{ if(strpos($str,';')){ //pics $ar2 = explode(';', $str); foreach($ar2 as $k=>$v){ $art = explode(',', $v); if(empty($art[0])) unset($ar2[$k]); else $ar2[$k] = str_replace(array("\r","\n",' '), array('','',''), $ar2[$k]); } }else{ $ar2 = array($str); } } $ar2 = array_unique(array_filter($ar2)); return $ar2; } //替换root路径 static function moveRepRoot($str, $v, $key, $fix=''){ global $_cbase; $rmain = $_cbase['run']['rmain']; $cfg = self::cfgDirPath($key, 'arr'); $res = $v; if(strpos($res,$cfg[1].$fix)===0 && !empty($cfg[1])){ $res = '{'.$key.'root}'.substr($res, strlen($cfg[1])); //echo "$key, ($v, $res, $str)
    "; $str = str_replace($v, $res, $str); } $reps = glbConfig::read('repath', 'sy'); foreach (array('att','tpl') as $k0) { if(!empty($reps[$k0])){ $str = str_replace(array_values($reps[$k0]), array_keys($reps[$k0]), $str); } } //$str = self::revSaveDir($str); return $str; } //part:dir,arr,else static function cfgDirPath($key, $part='dir'){ $cfg = array( 'root' => array(DIR_ROOT, PATH_ROOT), 'imcat' => array(DIR_IMCAT, PATH_IMCAT), 'views' => array(DIR_VIEWS, PATH_VIEWS), 'ctpl' => array(DIR_CTPL, ''), 'dtmp' => array(DIR_DTMP, PATH_DTMP), 'vars' => array(DIR_VARS, PATH_VARS), 'ures' => array(DIR_URES, PATH_URES), 'html' => array(DIR_HTML, PATH_HTML), 'vendor' => array(DIR_VENDOR, PATH_VENDOR), 'vendui' => array(DIR_VENDUI, PATH_VENDUI), 'static' => array(DIR_STATIC, PATH_STATIC), 'tpl' => array(vopTpls::path('tpl'), ''), //可能没有定义 'tpc' => array(vopTpls::path('tpc'), ''), ); $re = isset($cfg[$key]) ? $cfg[$key] : $cfg; if($part=='arr') return $re; $id = $part=='dir' ? 0 : 1; return empty($re[$id]) ? $key : $re[$id]; } //还原保存的路径 static function revSaveDir($str, $part=''){ self::storeCfgs(); $paths = self::cfgDirPath(0, 'arr'); foreach($paths as $ck=>$itm){ if(in_array($ck,array('tpl','tpc','ctpl','code'))) continue; $path = $part=='dir' ? $itm[0] : $itm[1]; $str = str_replace(array('{'.$ck.'root}','{$'.$ck.'root}'), $path, $str); } $reps = glbConfig::read('repath', 'sy'); foreach (array('att','tpl') as $k0) { if(!empty($reps[$k0])){ $str = str_replace(array_keys($reps[$k0]), array_values($reps[$k0]), $str); } } foreach(self::$cfgs['types'] as $tk=>$row){ // && strpos($str,$row['spre'])>=0 if(!empty($row['vpre']) && !empty($row['spre'])){ $str = str_replace($row['spre'], $row['vpre'], $str); } } return $str; } // 图片集转数组: dext:del-ext static function picsTab($exfile, $dext=1){ if(empty($exfile)) return []; $exfile = str_replace(["\r\n","\r"], ["\n","\n"], $exfile); $exfps = explode("\n", self::revSaveDir($exfile)); if(empty($exfps)){ return []; } foreach($exfps as $fk=>$fp){ $fp = trim(str_replace(';','',$fp)); if(!$fp){ unset($exfps[$fk]); } else{ $msg = ''; if(strpos($fp,',')>0){ $tmp = explode(',', $fp); $fp = $tmp[0]; //substr($fp,0,strpos($fp,',')); $msg = $tmp[1]; } $exfps[$fk] = $dext ? $fp : [$fp,$msg]; } } return $exfps; } } ### file: /share_imcat/core/clib/comToken.php table('token_rest')->where("token='$token'")->find(); if($row){ if($row['exp']<$_SERVER["REQUEST_TIME"]){ // 过期 glbError::show("Token Expired [".(date('Y-m-d H:i:s',$row['exp']))."]"); } // demo=table,list,check; $perm = basElm::text2arr(str_replace(';','&',$row['perm'])); if(!isset($perm[$mod])){ glbError::show("No Permission for [$mod]"); }elseif(!strstr($perm[$mod],$key)){ glbError::show("No Permission [$key] in [$mod]"); }else{ $pmod = $perm[$mod]; // 用于返回 } $row['perm'] = $perm; $row['pmod'] = $pmod; }else{ glbError::show("Token Error [$token]"); } return $row; } // 检测:limit频率 static function limit($token,$mod,$key){ $db = glbDBObj::dbObj(); // 频率: $arr = array('kid'=>$token,'mod'=>$mod,'act'=>$key); $rli = $db->table('token_limit')->where($arr)->find(); if($rli){ $gap = $_SERVER["REQUEST_TIME"]-$rli['etime']; $rate = empty($row['rate']) ? self::$rate : intval($row['rate']); if($gap<$rate*60){ $wait = $rate*60 - $gap; glbError::show("Too many Request! Please Wait $wait(s)"); } }else{ $gap = $_SERVER["REQUEST_TIME"]-1; $db->table('token_limit')->data($arr)->insert(0); } return $gap; } // 更新:limit static function upd($token,$mod,$key){ $db = glbDBObj::dbObj(); $arr = array('kid'=>$token,'mod'=>$mod,'act'=>$key); $db->table('token_limit')->data(array('etime'=>$_SERVER["REQUEST_TIME"]))->where($arr)->update(0); } } ### file: /share_imcat/core/clib/comHook.php 0){ // call('exuUser::reg',$user) $tmp = explode('::',$act); $cls = $tmp[0]; $method = $tmp[0]; $hook = new $cls($paras); $re = $hook->$method(); }else{ // [user_act]('reg',$user) $row['kid'] = "hook_$act"; $re = self::rone($row,$paras); } } //function __destory(){ } mkv+tpl url+file function __construct($mkv,$tpl,$upd=1){ if(empty($mkv)||empty($tpl)) return; if(strpos('.',$mkv)){ $tmp = explode('.',$mkv); $tmp[1] = 'detail'; $mkv = implode('.',$tmp); } $this->init($mkv,$tpl); $this->rlist(); $upd && $this->update(); } // init function init($mkv='',$tpl=''){ $this->db = glbDBObj::dbObj(); $this->stamp = $_SERVER["REQUEST_TIME"]; if(!extCache::cfGet($this->frun,$this->rgap)){ $whr = " exnext<'".$this->stamp."' AND enable=1 AND hkflag=1"; $whr .= $mkv ? " AND (hkmkv='0' OR hkmkv='$mkv')" : " AND hkmkv='0'"; $whr .= $tpl ? " AND (hktpl='0' OR hktpl='$tpl')" : " AND hktpl='0'"; $this->jobs = $this->db->table($this->tab)->where($whr)->select(); } } // 运行列表 function rlist(){ if(!empty($this->jobs)){ foreach($this->jobs as $row){ $rdo = $this->rone($row); $next = $this->stamp + extCache::CTime($row['excycle'].$row['excunit']); $this->jres[$row['kid']] = array( 'rdo' => $rdo, 'next' => $next, ); } } } } ### file: /share_imcat/core/clib/comJwt.php 'HS256', //生成signature的算法 'typ' => 'JWT' //类型 ); static function make($payload) { if(is_array($payload)) { $enchd = self::enc64(json_encode(self::$header,JSON_UNESCAPED_UNICODE)); $encpl = self::enc64(json_encode($payload,JSON_UNESCAPED_UNICODE)); $token = "$enchd.$encpl." . self::sign("$enchd.$encpl",self::$header['alg']); return $token; }else{ return false; } } static function check($Token) { $tokens = explode('.', $Token); if (count($tokens) != 3) return false; // '3seg: Wrong Token Segments' list($enchd, $encpl, $sign) = $tokens; //获取jwt算法 $dechd = json_decode(self::dec64($enchd), 1); if (empty($dechd['alg'])) return false; // head: Invalid header encoding //签名验证 if (self::sign("$enchd.$encpl", $dechd['alg']) !== $sign) return false; // head: Invalid body encoding $payload = json_decode(self::dec64($encpl), 1); //签发时间大于当前服务器时间验证失败 if (isset($payload['iat']) && $payload['iat'] > time()) return false; // //过期时间小宇当前服务器时间验证失败 if (isset($payload['exp']) && $payload['exp'] < time()) return false; //该nbf时间之前不接收处理该Token if (isset($payload['nbf']) && $payload['nbf'] > time()) return false; return $payload; } static function enc64($input) { return comConvert::sysBase64($input); // sysBase64,sysRevert } static function dec64($input) { return comConvert::sysBase64($input, 1); // sysBase64,sysRevert } static function sign($input, $alg='HS256') { global $_cbase; $key = $_cbase['safe']['other']; $calg = array( 'HS256' => 'sha256' ); $res = hash_hmac($calg[$alg], $input, $key, true); return self::enc64($res); } static function req($key='autok'){ $key = 'HTTP_' . strtoupper(str_replace(['-'], ['_'], $key)); $jwt = empty($_SERVER[$key]) ? '' : $_SERVER[$key]; return $jwt; } } ### file: /share_imcat/core/clib/comConvert.php "sha512", "private_key_bits" => 1024, //字节数:512, 1024, 2048, 4096 等 "private_key_type" => OPENSSL_KEYTYPE_RSA, //加密类型 ); if(!empty($cfg['openssl_cnf']) && file_exists($cfg['openssl_cnf'])){ $config['config'] = $cfg['openssl_cnf']; } //创建公私钥 $res = openssl_pkey_new($config); //获取私钥 $passKey = empty($cfg['pass']) ? null : $cfg['pass']; openssl_pkey_export($res, $private_key, $passKey, $config); //获取公钥 $public_key = openssl_pkey_get_details($res)['key']; //组合rsa $rsa = [ 'public_key' => $public_key, 'private_key' => $private_key, ]; return $rsa; } // 加载-table数据 static function impData($data,$part=''){ $f1 = 'start(!@~)'; $f2 = '(!@~)isend'; $f0 = '(split!@~flag)'; // 标记 if(empty($data)) return ''; $p1 = strpos($data,$f1); $p2 = strpos($data,$f2); if($p1) $data = substr($data,$p1+10,$p2-$p1+10); if($part){ $len = strlen($part)+2; $p1 = strpos($data,"[$part]")+$len; $p2 = strpos($data,"[/$part]"); $data = ($p1 && $p2) ? substr($data,$p1,$p2-$p1) : ''; } if(strpos($data,$f0)>0) $data = explode($f0,$data); return $data; } // 自动转换字符集 支持数组转换 static function autoCSet($str,$from='gbk',$to='utf-8'){ if(empty($str) || empty($from) || empty($to)) return $str; $from = strtoupper($from)=='UTF8'? 'utf-8':$from; $to = strtoupper($to)=='UTF8'? 'utf-8':$to; if( strtoupper($from) === strtoupper($to) || (is_scalar($str) && !is_string($str)) ){ return $str; //如果编码相同或者非字符串标量则不转换 } if(is_string($str) ) { if(function_exists('iconv')){ return iconv($from,$to."//IGNORE",$str); }elseif(function_exists('mb_convert_encoding')){ return mb_convert_encoding ($str, $to, $from); }else{ return $str; } }elseif(is_array($str)){ foreach ( $str as $key => $val ) { $str[$key] = self::autoCSet($val,$from,$to); // 不考虑key转化 } return $str; }else{ return $str; } } // sn:3369512d-e369-czyx-xmao-2016-5w76dm47 static function sysSn($area='czyx',$corp='xmao'){ $time = str_replace('-','',basKeyid::kidTemp('6')); $enc = md5("$area.$time.$corp"); $res = substr($enc,7,8).'-'.substr($enc,23,4); $res .= "-$area-$corp-"; $res .= substr($time,0,4).'-'.substr($time,4,8); return $res; } static function sysPass($uid='',$upw='',$mod=''){ global $_cbase; if(empty($uid) || empty($upw)) return '(null)'; $pfix = $mod=='adminer' ? $_cbase['safe']['pass'].$mod : 'pass'; return self::sysEncode("$upw@$uid",$pfix,24); } // *** 加密MD5 // $methods:md5,sha1,(md5比sha1快点) // $ukey = in_array($ukey,array('pass','form','api','js','other')) static function sysEncode($str,$ukey='other',$len=16){ global $_cbase; $safe = $_cbase['safe']; $str = md5($str); $str = sha1($str); $str = sha1($str); $ukey || $ukey = 'other'; $ukey = isset($safe[$ukey]) ? $safe[$ukey] : $ukey; $skey = $safe['site']; $ostr = "$skey@$str@$len@$ukey"; $str = sha1($ostr).hash('ripemd128',$ostr); // 72位 $len || $len = 16; return substr($str,(strlen($str)-$len)/2,$len); } //加密解密,$key:密钥;$de:是否解密;$expire 过期时间 static function sysRevert($str, $de=0, $key='', $exp=0){ global $_cbase; $key || $key = $_cbase['safe']['other']; $nn = 4; $key = md5($key); $res = ''; $keya = md5(substr($key,0,16)); $keyb = md5(substr($key,16,16)); if($de){ $str = str_replace(array('-','_',),array('+','/',),$str); $keyc = substr($str,0,$nn); $ckey = $keya.md5($keya.$keyc); $ckn = strlen($ckey); $str = base64_decode(substr($str,$nn)); }else{ $str = serialize($str); $keyc = substr(md5($_SERVER["REQUEST_TIME"]), -$nn); $ckey = $keya.md5($keya.$keyc); $ckn = strlen($ckey); $str = sprintf('%010d', $exp ? $exp+$_SERVER["REQUEST_TIME"] : 0).substr(md5($str.$keyb),0,16).$str; } $mm = strlen($str); $box = range(0,255); $rnd = array(); for($i=0; $i<=255; $i++){ $rnd[$i] = ord($ckey[$i % $ckn]); } for($j=$i=0; $i<256; $i++) { $j = ($j + $box[$i] + $rnd[$i]) % 256; $tmp = $box[$i]; $box[$i] = $box[$j]; $box[$j] = $tmp; } for($a=$j=$i=0; $i<$mm; $i++) { $a = ($a + 1) % 256; $j = ($j + $box[$a]) % 256; $tmp = $box[$a]; $box[$a] = $box[$j]; $box[$j] = $tmp; $res .= chr(ord($str[$i]) ^ ($box[($box[$a] + $box[$j]) % 256])); } if($de){ $ires = intval(substr($res,0,10)); if($ires==0 || $ires-$_SERVER["REQUEST_TIME"]>0) { return @unserialize(substr($res,26)); } return ''; }else{ $res = base64_encode($res); return $keyc.str_replace(array('+','/','='),array('-','_',''),$res); } } //base64编码(并加密/解密) static function sysBase64($s,$de=0,$key=''){ global $_cbase; if(empty($s)) return $s; $safe = $_cbase['safe']; $org = basKeyid::kidRTable('f','org'); $rnd = $safe['rndtab'].'.-'; $re = ''; $fix = ($key ? $key : $safe['rndch6'])."^"; if($de){ for($i=0;$i=$len) break; } return $jf; } static function pinyinOne($chr){ $tab = self::pycfgTab(); $p = strpos($tab,$chr); $t = substr($tab,0,$p); $t = strrchr($t,"("); $p = strpos($t,")"); $t = substr($t,1,$p-1); return $t; } // 内页广告: 0-neiyeguanggao, 1-n, 9-nygg static function pinyinMain($str,$cset='3',$first=0){ $cset = $cset=='3' ? 'utf-8' : 'gbk'; $arr = basStr::strArr($str, $cset); $len = count($arr); $py=""; for($i=0;$i<$len;$i++){ if(ord($arr[$i])<128){ $py .= preg_replace("/\W/",'_',$arr[$i]); }else{ $tmp = self::pinyinOne($arr[$i]); $py .= $first ? substr($tmp,0,1) : $tmp; } if($first===1 && $py) return substr($py,0,1); } return $py; } static function jfcfgTab($key){ static $jfcfg_tab; if(!isset($jfcfg_tab)){ $file = DIR_STATIC.'/ximp/utabs/jianfan.imp_txt'; $tmp = comFiles::get($file); $tmp = explode('(split!@~flag)',$tmp); $jfcfg_tab[0] = trim($tmp[1]); $jfcfg_tab[1] = trim($tmp[2]); unset($tmp); } $id = $key=='Fan' ? 1 : 0; return $jfcfg_tab[$id]; } static function pycfgTab(){ static $pycfg_tab; if(!isset($pycfg_tab)){ $file = DIR_STATIC.'/ximp/utabs/pinyin.imp_txt'; $pycfg_tab = comFiles::get($file); } return $pycfg_tab; } } ### file: /share_imcat/core/clib/comJifen.php init($file); } static function update(){ $list = glbDBObj::dbObj()->table('bext_paras')->where("pid='jifen_grade'")->order('top')->select(); $arr = array(); foreach($list as $r){ $arr[$r['kid']] = array('title'=>$r['title'],'numa'=>$r['numa'],'icon'=>$r['cfgs'],); } glbConfig::save($arr,'jifen','dset'); return $arr; } static function grade($mark=0,$re='title'){ $jfcfg = glbConfig::read('jifen','dset'); $jftitle = basLang::show('core.no_rank'); $jfnow = array('kid'=>'-null-','title'=>$jftitle,'icon'=>'-null-'); foreach($jfcfg as $k=>$v){ if($v['numa']>=$mark){ $jftitle = $v['title']; $jfnow = array('kid'=>$k,'title'=>$jftitle,'icon'=>$v['cfgs']); return; } } return $re=='arr' ? $jfnow : $jftitle; } // act : add,del static function main($mcfg,$act,$msg=''){ $db = glbDBObj::dbObj(); $key = "cr$act"; if(empty($mcfg[$key])){ return; }else{ $mcfg[$key] = intval($mcfg[$key]); } $auser = empty($mcfg['auser']) ? '' : basStr::filTitle($mcfg['auser']); // addcr $op = $act=='add' ? '+' : '-'; $sql = "UPDATE ".$db->table('users_uacc',2)." SET ujifen=ujifen{$op}".$mcfg[$key]." WHERE uname='$auser'"; $db->query($sql); // logger $data = basSql::logData('a'); $data['kid'] = basKeyid::kidTemp('3.4').basKeyid::kidRand('24',4); $data['act'] = $act; $data['uto'] = $auser; $data['jifen'] = $mcfg[$key]; $data['jfmod'] = $mcfg['kid']; $data['note'] = $msg ? $msg : "{$mcfg['kid']}:$act"; $db->table("logs_jifen")->data($data)->insert(); } } ### file: /share_imcat/core/clib/comFiles.php $v){ if(in_array($ext,$v)){ $icon = $v[0]; $type = $k; break; } } return array('type'=>$type,'icon'=>$icon); //'unknow'; } // glob效率比readdir低 static function listFast($dir){ $re = array(); $list = glob(str_replace('//','/',"$dir/*")); foreach ($list as $file) { if($file=='.'||$file=='..') continue; if(is_dir($file)){ //不用:file_exists $re = array_merge($re,self::listFast($file)); }else{ $re[] = $file; } } return $re; } static function listScan($dir,$sub='',$skips=array()){ $re = array(); $mCount = 6400; if(!is_dir($dir)) return []; $handle = opendir($dir); while ($file = readdir($handle)) { if($file=='.'||$file=='..') continue; $key = "{$sub}$file"; $fp = "$dir/$file"; if(count($re)<$mCount && is_dir($fp)){ //不用:file_exists if(empty($sub) && !empty($skips) && in_array($file,$skips)) continue; $re = array_merge($re,self::listScan($fp,"$sub$file/")); }else{ $mtime = filemtime($fp); if(count($re)<$mCount){ $re[$key] = array($mtime,filesize($fp)); } } } closedir($handle); return $re; } static function listDir($dir,$key=''){ $re = array('dir'=>array(),'file'=>array()); if(!is_dir($dir)) return $re; // --- scandir(); $handle = opendir($dir); while ($file = readdir($handle)) { if($file=='.'||$file=='..') continue; $fp = "$dir/$file"; $mtime = filemtime($fp); if(is_file($fp)){ $re['file'][$file] = array($mtime,filesize($fp)); }else{ $re['dir'][$file] = $mtime; } } closedir($handle); if($key){ return $re[$key]; } return $re; } // 目录状态统计(大小,文件数,目录数) static function statDir($path){ $msize = 0; $fcount = 0; $dcount = 0; if ($handle = opendir ($path)){ while (false !== ($file = readdir($handle))){ $nextpath = $path . '/' . $file; if ($file != '.' && $file != '..' && !is_link ($nextpath)){ if (is_dir ($nextpath)){ $dcount++; $result = self::statDir($nextpath); $msize += $result['nsize']; $fcount += $result['cfile']; $dcount += $result['cdir']; }elseif (is_file ($nextpath)){ $msize += filesize ($nextpath); $fcount++; } } } } closedir($handle); $total['nsize'] = $msize; $total['cfile'] = $fcount; $total['cdir'] = $dcount; return $total; } static function chkDirs($subs, $flag='', $isfile=1){ if(empty($subs)) return; if(strstr($subs,'../')) return; if($isfile){ return self::chkDirs(dirname($subs),$flag,0); } $check = basStr::filKey($subs,'!()-@_~/'); //.+,;^` if($check!=$subs) return; $path = comStore::cfgDirPath($flag,'dir'); $path || $path = DIR_DTMP; $a = explode('/',$subs); $i = 0; $tmp = ''; if(count($a)>0){ foreach($a as $d){ //if(empty($d)) return; if(!is_dir($path."$tmp/$d")){ mkdir($path."$tmp/$d", 0777, true); foreach(array('htm','html') as $var) @touch($path."$tmp/$d".'/index.'.$var); } $tmp .= "/$d"; $i++; if($i==12) break; } } } //遍历删除目录和目录下所有文件 static function delDir($dir,$delself=0,$keep='',$first=1){ if(strlen($dir)<6) return false; // /a/b c:/a/b if(!defined('indo_Verset')){ if(strstr($dir,DIR_IMCAT) || strstr($dir,DIR_ROOT) || strstr($dir,DIR_STATIC) || strstr($dir,DIR_VENDUI) || strstr($dir,DIR_VENDOR)) return false; } if($first){ if(is_file($dir)){ return @unlink($dir); }; if(in_array(substr($dir,-1,1),array('/',"\\"))){ $dir = substr($dir,strlen($dir)-1); } if(!is_dir($dir)){ return false; }; } $handle = opendir($dir); while (($file = readdir($handle)) !== false){ if ($file != "." && $file != ".."){ if(in_array($file,array('index.htm','index.html')) && empty($delself)) continue; if($keep && strstr($keep,$file)) continue; is_dir("$dir/$file") ? self::delDir("$dir/$file",1,'',0):@unlink("$dir/$file"); } } if(!empty($delself)){ if (readdir($handle) == false){ closedir($handle); @rmdir($dir); } } } // 是否可写 //if(is_writable($pfile)){} static function canWrite($dir){ if(is_dir($dir)){ $pfile = str_replace('','',$dir.'/@can_Write.test'); @unlink($pfile); if($fp = @fopen($pfile, 'w')) { @fclose($fp); $fwrite = 1; }else $fwrite = 0; }elseif(is_file($dir)){ $fwrite = is_writable($dir); }else{ $fwrite = 0; } return $fwrite; } // 复制目录 : $src -> $dst // $skip : 忽略目录 static function copyDir($src,$dst,$skip=array(),$skfile=array()) { // 原目录,复制到的目录 $dir = opendir($src); @mkdir($dst); while(false !== ( $file = readdir($dir)) ) { if (( $file != '.' ) && ( $file != '..' )) { if(is_dir($src.'/'.$file)){ if(!empty($skip) && in_array($file,$skip)) continue; self::copyDir($src.'/'.$file, $dst.'/'.$file,$skip,$skfile); }else{ if(!empty($skfile) && in_array($file,$skfile)) continue; @copy($src.'/'.$file, $dst.'/'.$file); } } } closedir($dir); } } ### file: /share_imcat/core/clib/comParse.php ','"',"'","\r","\n"),'',$str);, 不是参数 $c = array( '+' , ' ' , '"' ,"'" , '<' , '>' , "\r" , "\n" , "\\" ); $d = array( '%2B' , '+' , '%22' ,'%27' , '%3C' , '%3E' , '%0D' , '%0A' , '%5C' ); if($ext){ $str = str_replace($c,$d,$str); } return $str; } // csv static function csvGets($file) { $handle = fopen($file,'r'); $arr = array(); while ($data = fgetcsv($handle)) { //每次读取CSV里面的一行内容 $arr = $data; //此为一个数组,要获得每一个数据,访问数组下标即可 } fclose($handle); return $arr; } static function csvPuts($file, $data) { $handle = fopen($file, 'r+'); foreach ($data as $line) { fputcsv($handle, $line); } fclose($handle); } // xml(node) static function nodeParse($data, $cset='', $nobj='', $opt=LIBXML_NOCDATA) { if(is_string($data)){ $hfix = $cset ? "" : ''; $data = simplexml_load_string($hfix.$data, null, $opt); // obj(自动转:utf-8) } $json = json_encode($data); if($nobj==''){ // 空对象转化为空字符串 $json = str_replace(['":{},','":{}}'], ['":"",','":""}'], $json); } $arr = json_decode($json, true); return $arr; } // 将数组转换为JSON字符串(兼容中文) static function jsonEncode($array) { $pmj = defined('JSON_UNESCAPED_UNICODE') ? JSON_UNESCAPED_UNICODE : 0; $json = @json_encode($array, $pmj); // JSON_UNESCAPED_UNICODE:PHP>=5.4生效 $json = str_replace("\"},\"","\"}\n,\"",$json); $json = str_replace(",\",\"",",\"\n,\"",$json); return $json; } static function jsonDecode($str) { $str = comFiles::killBOM($str); $str = trim($str); $arr = json_decode($str,1); return $arr; } // 反序列化(将某些特殊字符的utf8编码转为asc码解析)不建议使用原生的unserialize。 static function serEncode($str) { $str = str_replace("\r", "", $str); $str = preg_replace_callback('/s:(\d+):"(.*?)";/s', function($arr){ return 's:'.strlen($arr[2]).':"'.$arr[2].'";'; }, $str); return unserialize($str); } private function uniEncode($str, $fix='%u'){ preg_match_all('/./u', $str, $matches); $reStr = ""; foreach($matches[0] as $m){ $itm = bin2hex(iconv('UTF-8',"UCS-4",$m)); $reStr .= $fix.strtoupper(substr($itm,4)); } return $reStr; } // unicode static function uniDecode($str, $type='u'){ if($type=='u'){ // '\u4E00' $reg = '/\\\\u([0-9a-f]{4})/i'; }else{ // '& $reg = '/\&\ } $str = preg_replace_callback($reg, function($arr){ return mb_convert_encoding(pack('H*', $arr[1]), 'UTF-8', 'UCS-2BE'); }, $str); return $str; } } ### file: /share_imcat/core/clib/comHttp.php array('curl_init','curlCrawl'), '2' => array('fsockopen','socketCrawl'), '3' => array('file_get_contents','fileCrawl'), ); public static $cache = 0; public static $savep = ''; //手动设置访问方式 static function setWay($way){ self::$way = intval($way); } //手动设置缓存 static function setCache($exp){ self::$cache = intval($exp); } //通过get方式获取数据 static function doGet($url, $params=array()) { return self::doPost($url, array(), $params); } //通过POST方式发送数据 static function doPost($url, $data=array(), $params=array()) { if(empty($url)) return false; if(!preg_match('/^(http|https)/is',$url)) $url = "http://".$url; $method = ''; if(isset(self::$ways[self::$way])){ $method = self::$ways[self::$way][1]; }else{ foreach(self::$ways as $item) { if(function_exists($item[0])){ $method = $item[1]; break; } } } return $method ? self::$method($url, $data, $params) : false; } //通过 curl get/post数据 ($data: str:xml,str:json,array) static function curlCrawl($url, $data=array(), $opt=array()) { // getCache $cres = self::getCache($url, $data); if(!empty($cres[1])) return $cres[1]; // init $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); self::_timeout($opt, $ch); // Timeout self::curlProxy($ch, $opt); // ref/proxy curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $header = self::_heads($opt, $data); // header/cookie/type curl_setopt($ch, CURLOPT_HTTPHEADER, $header); self::curlData($ch, $opt, $data); // data,gzip // https if(substr($url,0,8)=='https://'){ curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); if(isset($opt['sslv'])){ // 2-7, 默认情况下PHP会自己检测这个值 curl_setopt($ch, CURLOPT_SSLVERSION, $opt['sslv']); } // ['TLSv1_3','TLSv1_2','TLSv1_1','TLSv1_0','SSLv3','SSLv2','SSLv1'] } // saveCache & return $result = curl_exec($ch); if(!empty($cres[0])) self::saveCache($cres[0], $result); curl_close($ch); return $result; } // data,gzip static function curlData(&$ch, &$opt=array(), $data=array()){ if(!empty($data)){ if(isset($opt['type']) && in_array($opt['type'],array('xml','json'))){ curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST"); }else{ curl_setopt($ch, CURLOPT_POST, true); } curl_setopt($ch, CURLOPT_POSTFIELDS, $data); } if(isset($opt['gzip'])){ //模拟来源地址 $gzip = empty($opt['gzip']) ? 'gzip,deflate' : $opt['gzip']; curl_setopt($ch, CURLOPT_ENCODING, $gzip); //curl解压gzip页面内容 } } // ref/proxy static function curlProxy(&$ch, &$opt=array()){ if(isset($opt['ref'])){ //模拟来源地址 curl_setopt($ch, CURLOPT_REFERER, $opt['ref']); } if(isset($opt['proxy'])){ $proxy = $opt['proxy']; curl_setopt($ch, CURLOPT_PROXYAUTH, CURLAUTH_BASIC); //代理认证模式 curl_setopt($ch, CURLOPT_PROXY, $proxy[0]); //代理服务器地址 curl_setopt($ch, CURLOPT_PROXYPORT, $proxy[1]); //代理服务器端口 } } //通过 socket get/post数据 static function socketCrawl($url, $data=array(), $opt=array()) { // getCache $cres = self::getCache($url, $data); if(!empty($cres[1])) return $cres[1]; // timeout/header $timeout = self::_timeout($opt); $header = self::_heads($opt, $data); $url = parse_url($url); $errno = 0; $errstr = ''; $url["path"] = ($url["path"] == "" ? "/" : $url["path"]); $url["port"] = empty($url["port"]) ? 80 : $url["port"]; $url["query"] = isset($url["query"]) ? $url["query"] : ""; if(($fsock = fsockopen(gethostbyname($url["host"]), $url['port'], $errno, $errstr, $timeout)) < 0){ return false; } $request = $url["path"].($url["query"] ? "?" . $url["query"] : ""); $eol = PHP_EOL; $eol2 = $eol.$eol; $in = (empty($data) ? 'GET' : 'POST')." $request HTTP/1.0$eol"; $in .= "Host: " . $url["host"] . "$eol".implode($eol,$header); if(!empty($data)){ $pstr = http_build_query($data); $in .= "Content-type: application/x-www-form-urlencoded$eol"; $in .= "Content-Length: " . strlen($pstr) . $eol; $in .= "Connection: Close$eol2$pstr$eol2"; }else{ $in .= "Connection: Close$eol2"; } if(!fwrite($fsock, $in, strlen($in))){ fclose($fsock); return false; } $out = null; while($buff = @fgets($fsock, 2048)){ $out .= $buff; } fclose($fsock); $pos = strpos($out, $eol2); $head = substr($out, 0, $pos); $status = substr($head, 0, strpos($head, $eol)); if(preg_match("/^HTTP\/\d\.\d\s([\d]+)\s.*$/", $status, $matches)){ if(intval($matches[1]) / 100 == 2){ $result = substr($out, $pos + 4, strlen($out) - ($pos + 4)); // saveCache self::saveCache($cres[0], $result); return $result; }else{ return false; } }else{ return false; } } //通过 file_get_contents 函数post数据 static function fileCrawl($url, $data=array(), $opt=array()){ // getCache $cres = self::getCache($url, $data); if(!empty($cres[1])) return $cres[1]; // timeout/header $timeout = self::_timeout($opt); $header = self::_heads($opt, $data); $opts = array( 'http'=>array( 'protocol_version'=>'1.0',//http协议版本(若不指定php5.2系默认为http1.0) 'timeout' => $timeout , 'header'=> implode(PHP_EOL,$header), 'method'=> (empty($data) ? 'GET' : 'POST'), ) ); if(!empty($data)){ $pstr = http_build_query($data); $opts['http']['header'] = "Content-length: ".strlen($pstr); $opts['http']['content'] = $pstr; } $context = stream_context_create($opts); $result = file_get_contents($url, false, $context); // saveCache $cres && self::saveCache($cres[0], $result); // return return $result; } // exp static function _timeout(&$opt=array(), &$ch='re'){ $exp = 5; if(is_numeric($opt)){ $exp = $opt; $opt = array(); }elseif(!empty($opt['exp'])){ $exp = $opt; } if($ch=='re') return $exp; curl_setopt($ch, CURLOPT_TIMEOUT, $exp); curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $exp); } // head/cookie: 'null', empty(), cookie static function _heads(&$opt=array(), &$data=array()){ $header = self::_defHeader($opt); if(!empty($opt['head'])){ $uhead = is_array($opt['head']) ? $opt['head'] : implode(PHP_EOL, $opt['head']); $header = array_merge($header, $uhead); } if(isset($opt['cookie'])){ // cookie设置 $header[] = "Cookie: ".$opt['cookie']; } $tag = array( 'html'=>'text/html', // plain 'xml'=>'text/xml', 'json'=>'application/json', 'down'=>'application/octet-stream', ); if(isset($opt['type']) && isset($tag[$opt['type']])){ // json $header[] = "Content-Type: ".$tag[$opt['type']]; if($opt['type']=='json'){ if(is_array($data)) $data = json_encode($data); $header['json'] = "Content-Length: ".strlen($data); } } //dump($header); return $header; } //默认模拟的header头 static function _defHeader($ops=[]){ //if(!empty($header)) return $header; $defs = array( 'HTTP_USER_AGENT' => 'comHttp@imcat.txjia.com', ); $cfgs = array( 'HTTP_ACCEPT' => 'Accept', 'HTTP_ACCEPT_LANGUAGE' => 'Accept-Language', 'HTTP_ACCEPT_CHARSET'=>'Accept-Charset', 'HTTP_USER_AGENT' => 'User-Agent', ); $header = array(); foreach($cfgs as $ks=>$kn){ if(isset($ops[$ks])){ $header[] = "$kn: ".$ops[$ks]; }elseif(isset($_SERVER[$ks])){ $header[] = "$kn: ".$_SERVER[$ks]; }elseif(isset($defs[$ks])){ $header[] = "$kn: ".$defs[$ks]; } } //dump($header); echo "
    "; // 乱码问题: 遇到了外部$_cbase中加入,这里添加 // 'HTTP_ACCEPT_ENCODING' = 'Accept-Encoding: gzip, deflate'; return $header; } // 下载web中的(或URL)文件 static function downLoad($realname, $showname='', $expire=1800){ $size = self::downCheck($realname, $showname, 1); set_time_limit(0); header('Content-Description: File Transfer'); header('Content-Type: application/octet-stream'); header('Content-Transfer-Encoding: binary'); header('Accept-Ranges: bytes'); header('Expires: 0'); header('Cache-Control: must-revalidate, post-check=0, pre-check=0'); header('Pragma: public'); header('Content-Length: ' . $size); header('Content-Disposition: attachment; filename=' . $showname); $fp = fopen($realname, 'rb'); ob_clean(); ob_end_flush(); while (!feof($fp)) { echo fread($fp, $size); ob_flush(); // 刷新PHP缓冲区到Web服务器 flush(); // 刷新Web服务器缓冲区到浏览器 } fclose($fp); return true; } // 保存远程页面(图片)到本地 static function downSave($url, $showname='', $curl=0){ if(!$url) return; self::downCheck($url, $showname); if($curl){ $data = self::curlCrawl($url); }else{ ob_start(); readfile($url); $data = ob_get_contents(); ob_end_clean(); } comFiles::put($showname, $data); return $showname; } // downCheck static function downCheck(&$url, &$showname, $chkexists=0){ $fsize = 0; if(preg_match('/^https?:\/\//',$url)){ ini_set('allow_url_fopen', 'On'); } if(empty($url) || ($chkexists && !file_exists($url))) { throw new \Exception("[$url]Not Exists!"); }else{ $fsize = @filesize($url); } if(empty($showname)){ $info = parse_url($url); $_path = explode("/",$info['path']); $showname = end($_path); } return $fsize; } // 格式化返回数据 static function fmtContent($content){ $content = trim($content); // BOM标记?空白行? if (!$content) { return ''; } // json if(substr($content,0,1)=='{'){ $response = json_decode($content, true); if (JSON_ERROR_NONE !== json_last_error()) { parse_str($content, $response); return $response; } } // xml if(substr($content,0,1)=='<'){ $xml = @simplexml_load_string($content); if(is_object($xml)) return $xml; } // html, text return $content; } static function fpCache($url, $data=[]) { $fp = extCache::fName($url, 1, 2); return $fp.'---'.md5($url.'+'.json_encode($data)).'.htm'; } // 缓存处理 static function getCache($url, $data) { if(!self::$cache) return false; $fp = self::fpCache($url, $data); $data = extCache::cfGet("/remote/$fp", self::$cache, 'vars', 'str'); return [$fp, $data]; } static function saveCache($fp, $data) { if(!self::$cache) return false; extCache::cfSet("/remote/$fp", $data, 'vars'); } //兼容方法(后续去掉) static function curlGet($url, $params=array()) { return self::curlCrawl($url, array(), $params); } static function curlPost($url, $data=array(), $params=array()) { return self::curlCrawl($url, $data, $params); } } ### file: /share_imcat/core/clib/comUpload.php stateMap = basLang::ucfg('cfglibs.upload'); $this->stateMap['ERROR_TYPE_NOT_ALLOWED'] = $this->stateMap['ERROR_TYPE_NOT_ALLOWED']; $this->fileField = $fileField; $this->config = $config; $this->type = $type; if ($type == "remote") { $this->saveRemote(); } else if($type == "base64") { $this->upBase64(); } else { $this->upFile(); } } private function upFile(){ $file = $this->file = $_FILES[$this->fileField]; if (!$file) { $this->stateInfo = $this->getStateInfo("ERROR_FILE_NOT_FOUND"); return; } if ($this->file['error']) { $this->stateInfo = $this->getStateInfo($file['error']); return; } else if (!file_exists($file['tmp_name'])) { $this->stateInfo = $this->getStateInfo("ERROR_TMP_FILE_NOT_FOUND"); return; } else if (!is_uploaded_file($file['tmp_name'])) { $this->stateInfo = $this->getStateInfo("ERROR_TMPFILE"); return; } $this->oriName = $file['name']; $this->fileSize = $file['size']; $this->fileType = $this->getFileExt(); $this->fullName = $this->getFullName(); $this->fileName = $this->getFileName(); //检查文件大小是否超出限制 if (!$this->checkSize()){ $this->stateInfo = $this->getStateInfo("ERROR_SIZE_EXCEED"); return; } //检查是否不允许的文件格式 if (!$this->checkType()) { $this->stateInfo = $this->getStateInfo("ERROR_TYPE_NOT_ALLOWED"); return; } //移动文件 if (!move_uploaded_file($file["tmp_name"], $this->fullName)) { $this->stateInfo = $this->getStateInfo("ERROR_FILE_MOVE"); }else{ $this->upEnd(); } } private function upBase64(){ $base64Data = $_POST[$this->fileField]; $img = base64_decode($base64Data); $this->fileSize = strlen($img); $this->oriName = 'base64_'.$this->fileSize.'_'.basKeyid::kidRand('f',4).'.png'; //$this->config['oriName']; // $this->fileType = $this->getFileExt(); $this->fullName = $this->getFullName(); $this->fileName = $this->getFileName(); //检查文件大小是否超出限制 if (!$this->checkSize()) { $this->stateInfo = $this->getStateInfo("ERROR_SIZE_EXCEED"); return; } //移动文件 if (!(comFiles::put($this->fullName, $img))) { //移动失败 $this->stateInfo = $this->getStateInfo("ERROR_WRITE_CONTENT"); } else { //移动成功 $this->upEnd(); } } private function saveRemote($imgUrl=''){ if(empty($imgUrl)){ $imgUrl = htmlspecialchars($this->fileField); $imgUrl = str_replace("&", "&", $imgUrl); } //http开头验证 if (strpos($imgUrl, "http") !== 0) { $this->stateInfo = $this->getStateInfo("ERROR_HTTP_LINK"); return; } //获取请求头并检测死链 $heads = get_headers($imgUrl); if (!(stristr($heads[0], "200") && stristr($heads[0], "OK"))) { $this->stateInfo = $this->getStateInfo("ERROR_DEAD_LINK"); return; } // Content-Type验证 if (@stristr($heads['Content-Type'], "image")) { $this->stateInfo = $this->getStateInfo("ERROR_HTTP_CONTENTTYPE"); return; }/ function getFileInfo(){ return array( "state" => $this->stateInfo, "url" => comStore::fixTmpDir($this->fullName), "title" => $this->fileName, "original" => $this->oriName, "type" => $this->fileType, "size" => $this->fileSize ); } } ### file: /share_imcat/core/clib/comCookie.php $v){ $n++; if(($cnt-$n) > $max) continue; $str .= "$k=$v\n"; } self::oset($gkey,$str,$glife); } // mget : static function mget($gkey, $key='(array)'){ $gtxt = self::oget($gkey); $garr = basElm::text2arr($gtxt); if($key=='(array)') return $garr; return isset($garr[$key]) ? $garr[$key] : ''; } // set(k,'v',n),get(k),del(k,''),clear() // set/del static function oset($key='', $value='', $life=0, $pre='(def)'){ global $_cbase; $kbak = $key; $fset = 0; $ckpre = isset($_cbase['ck']['pre']) ? $_cbase['ck']['pre'] : 'sysCookie'; $key = ($pre=='(def)'?$ckpre:$pre).$key; $life && $life = $_SERVER["REQUEST_TIME"] + $life; //, + 72 * 3600 $path = isset($_cbase['ck']['path']) ? $_cbase['ck']['path'] : '/'; $domain = isset($_cbase['ck']['domain']) ? $_cbase['ck']['domain'] : ''; $secure = IS_CLI ? '0' : ($_SERVER['SERVER_PORT'] == 443 ? 1 : 0); //basDebug::bugLogs('test1',"($value),($life=".date('Y-m-d H:i:s',$life)."),$path,$domain,$secure"); setcookie($key,$value,$life,$path,$domain,$secure); } static function oget($key=''){ global $_cbase; $kbak = $key; $fset = 0; $ckpre = isset($_cbase['ck']['pre']) ? $_cbase['ck']['pre'] : 'sysCookie'; $key = $ckpre.$key; return isset($_COOKIE[$key]) ? $_COOKIE[$key] : ''; } } ### file: /share_imcat/core/clib/comCron.php init(); $this->rlist(); $upd && $this->update(); } // init function init(){ $this->db = glbDBObj::dbObj(); $this->stamp = $_SERVER["REQUEST_TIME"]; if(!extCache::cfGet($this->frun,$this->rgap)){ $whr = " exnext<'".$this->stamp."' AND enable=1 AND hkflag=0"; $this->jobs = $this->db->table($this->tab)->where($whr)->select(); } } // 运行列表 function rlist(){ if(!empty($this->jobs)){ foreach($this->jobs as $row){ $rdo = $this->rone($row); $next = $this->rnext($row,$rdo); $this->jres[$row['kid']] = array( 'rdo' => $rdo, 'next' => $next, ); } } } // 计算下次运行时间 // excunit=w,d,h excycle=1-127 function rnext($row,$rdo){ $ctime = extCache::CTime($row['excycle'].$row['excunit']); $stfix = date('i')*60 + date('s'); $stfix = $stfix > 1800 ? (3600-$stfix) : ($stfix-3600); //修正整点 $exsecs = intval(substr($row['exsecs'],0,2))*60 + intval(substr($row['exsecs'],3,2)); $next = $this->stamp + $stfix + $ctime + $exsecs; return $next; } // update function update(){ if(empty($this->jres)) return; foreach($this->jres as $file=>$row){ $data = array('exlast'=>$this->stamp); if($row['rdo']=='pass') $data['exnext'] = $row['next']; $this->db->table($this->tab)->data($data)->where("kid='$file'")->update(0); } comFiles::put(DIR_DTMP.$this->frun,date('Y-m-d H:i:s')); } // 运行一个任务 static function rone($row,$data=array()){ $db = glbDBObj::dbObj(); $stamp = $_SERVER["REQUEST_TIME"]; $fp1 = DIR_ROOT."/extra/cron/{$row['kid']}.php"; $fp2 = DIR_IMCAT."/adpt/cron/{$row['kid']}.php"; if(!empty($row['cfgs'])){ // run-sql }elseif(file_exists($fp1)){ include_once $fp1; }elseif(file_exists($fp2)){ include_once $fp2; }else{ // logger??? } return empty($rdo) ? 'fail' : $rdo; } } ### file: /share_imcat/core/clib/comArr2xml.php formatOutput = true; } public static function parse($array, $rootName = 'root', $version = '1.0', $encoding = 'UTF-8') { self::init($version, $encoding); //转换 $node = self::convert($array, $rootName); self::$doc->appendChild($node); return self::$doc->saveXML(); } private static function convert($array, $nodeName, $pareNode = NULL) { if (!is_array($array)) return false; //创建父节点。数组键值为数字时,不创建父节点,父节点为上一级节点 if(is_numeric($nodeName)){ $node = $pareNode; }else{ $node = self::createNode($nodeName); } //循环数组 foreach ($array as $key => $value) { if(is_numeric($key)){ //键值为数字,创建节点。 //不以数字做节点,以上一级数组键值做节点。将上一级节点当作当前节点进行操作 $node = self::createNode($nodeName); if (!is_array($value)) { //不是数组,则创建节点的值。 $node->appendChild(self::createValue($value)); $pareNode->appendChild($node); } else { //如果是数组,则递归。 $pareNode->appendChild(self::convert($value, $key, $node)); } }else{ $element = self::createNode($key); //如果不是数组,则创建节点的值 if (!is_array($value)) { $element->appendChild(self::createValue($value)); $node->appendChild($element); } else { //如果是数组,则递归 $node->appendChild(self::convert($value, $key, $node)); } } } return $node; } private static function createNode($name) { $node = NULL; $name = $name; //strtoupper($name); //如果是字符串,则创建节点 if (!is_numeric($name)) { $node = self::$doc->createElement($name); } else { //如果是数字,则创建默认item节点 $node = self::$doc->createElement('item'); } return $node; } private static function createValue($value) { $textNode = NULL; //如果是bool型,则转换为字符串 if (true === $value || false === $value) { $textNode = self::$doc->createCDATASection($value ? 'true' : 'false'); } else { //创建CDATA节点 $textNode = self::$doc->createCDATASection($value); } return $textNode; } } ### file: /share_imcat/core/vops/vopApp.php tplCfg = $_cbase['tpl']; vopTpls::check($_cbase['tpl']['vdir'], 1); if(!$do){ return; } $mode = $do=='api' ? 'api' : 'run'; $this->$mode(); } // api输出(控制器模式) function api(){ global $_cbase; $ucfg = vopUrl::iget(); $this->ucfg = vopUrl::imkv($ucfg); //dump($this->ucfg); $_cbase['mkv'] = $this->ucfg; foreach(array('mkv','mod','key','view','type') as $k){ $this->$k = $this->ucfg[$k]; } $this->extActs(); // 控制器接管 } // js标签解析 function js($data=''){ global $_cbase; $data || $data = basReq::val($data,'',''); $temp = vopCTag::tagParas($data,'arr'); foreach($temp[2] as $tk=>$tv){ if(in_array($tv[0],['order','where'])){ die("Error `{$tv[0]}`"); } } $tagfile = @$temp[0]; $tagname = @$temp[1]; $varid = 'T_'.$tagname; $tagpath = "/$tagfile.$tagname.comjs.php"; if(!file_exists(vopTpls::path('tpc').$tagpath)){ vopComp::main($tagfile); } $temp = @$temp[2]; $tagtype = @$temp[0][0]; $tagre = @$temp[0][1]; $tagre || $tagre = 'v'; unset($temp[0]); $tagparas = $temp; $unv = in_array($tagtype,array('One')) ? $tagre : $varid; $$unv = $this->tagParse($tagname,$tagtype,$temp); //显示模板 $_groups = glbConfig::read('groups'); include vopTpls::path('tpc').$tagpath; } // 常规模板解析 function run(){ global $_cbase; $this->vars = array(); // 重新清空(初始化),连续生成静态需要 $this->ucfg = vopUrl::init(); $_cbase['mkv'] = $this->ucfg; foreach(array('mkv','mod','key','view','type','tplname',) as $k){ $this->$k = $this->ucfg[$k]; } $this->homeStatic(); // 首页静态 $this->getVars(); // 读取数据 $this->extActs(); // 操作扩展(vars,tpls) $tplfull = $this->chkTpl(); // 检查模板,编译 if(!$tplfull){ $this->ucfg = array(); // 生成静态判断 return; } extract($this->vars, EXTR_OVERWRITE); $_cbase['run']['tplname'] = $this->tplname; include $tplfull; } // 检查模板,编译 function chkTpl() { global $_cbase; if(!empty($this->tplnull)){ return ''; // 不要后续模板显示-直接返回 } if(empty($this->tplname) || is_string($this->vars) || $this->ucfg['vcfg']['vmode']=='close'){ $msgk = $this->ucfg['vcfg']['vmode']=='close' ? 'closemod' : 'parerr'; $ermsg = is_string($this->vars) ? $this->vars : "$this->mkv:".basLang::show("core.vop_$msgk"); $this->msg($ermsg); return ''; // 返回空,终止操作 } if(!empty($this->tplorg)){ $tplorg = vopTpls::tinc("{$this->tplorg}.htm",0); }else{ $tplorg = vopTpls::tinc("{$this->tplname}.htm",0); } if(!file_exists($tplorg)){ // 原始模板是否存在 $this->msg("$tplorg NOT Exists!"); return ''; // 返回空,终止操作 } if(!empty($this->tplorg)){ $tplfull = $tplorg; // 原始包含,不要解析判断 }else{ // 编译 $dtpl = strpos($this->tplname,':') ? str_replace(':','/',$this->tplname) : $_cbase['tpl']['vdir']."/$this->tplname"; $tplfull = DIR_CTPL. '/'. $dtpl.$this->tplCfg['tpc_ext']; if(empty($_cbase['tpl']['tpc_on']) || !file_exists($tplfull)){ vopComp::main($this->tplname); } } $tplfull = empty($_cbase['tpl']['fixmkv']) ? $tplfull : $tplfull.'.'.$_cbase['tpl']['fixmkv']; return $tplfull; } // 扩展操作 function extActs() { if($class=vopTpls::impCtrl($this->mod)){ $aex = new $class($this->ucfg,$this->vars); $method = empty($this->key) ? 'homeAct' : ($this->type=='detail' ? '_detailAct' : $this->key.'Act'); if(method_exists($aex,$method)){ //$method = $method; }elseif($this->type=='mtype' && method_exists($aex,'_defAct')){ $method = '_defAct'; }else{ $method = ''; } if($method){ //$exact = $method.'Before'; // 预处理数据 //if(method_exists($aex,$exact)) $aex->$exact(); $res = $aex->$method(); //$exact = $method.'After'; // 后续数据调整 //if(method_exists($aex,$exact)) $aex->$exact(); } } if(!empty($res['vars']) && is_array($this->vars)){ $this->vars = array_merge($this->vars,$res['vars']); } if(!empty($res['tplnull'])){ $this->tplnull = $res['tplnull']; }elseif(!empty($res['newtpl'])){ // newtpl = [mod/]act if(!strpos($res['newtpl'],'/')){ $res['newtpl'] = $this->ucfg['mod'].'/'.$res['newtpl']; } $this->tplname = $res['newtpl']; }elseif(!empty($res['tplorg'])){ $this->tplname = $this->tplorg = $res['tplorg']; }else{ // extActs/extTpl:取其一扩展模板 $this->extTpl(); } } // 扩展模板 function extTpl() { global $_cbase; $vars = $this->vars; $tplname = &$this->tplname; // 处理:detail 设置的模板 if(!empty($vars['tplname'.$this->view])){ $tplname = $vars['tplname'.$this->view]; }elseif($this->type=='detail'){ $cfgs = array(); if(isset($vars['grade'])){ $mcfgs = glbConfig::read('grade','dset'); $cfgs = isset($mcfgs[$vars['grade']]) ? $mcfgs[$vars['grade']] : ''; }elseif(isset($vars['catid'])){ $mcfgs = glbConfig::read($this->mod); $cfgs = isset($mcfgs['i'][$vars['catid']]) ? $mcfgs['i'][$vars['catid']] : array(); } $cfgs = empty($cfgs['cfgs']) ? array() : basElm::text2arr($cfgs['cfgs']); if(!empty($cfgs['tplname'.$this->view])){ $tplname = $cfgs['tplname'.$this->view]; } } if(!empty($this->ucfg['vcfg']['tmfix']) && basEnv::isMobile()){ $tmfix = $this->ucfg['vcfg']['tmfix']; $_cbase['run']['tmfix'] = $tmfix; // -mob标记用于css,js后缀 $tplname .= $tmfix; } } //GetVars function getVars() { $_groups = glbConfig::read('groups'); if(!($this->type=='detail') || !isset($_groups[$this->mod])) return array(); $pid = $_groups[$this->mod]['pid']; $key = in_array($pid,array('types')) ? "kid" : substr($pid,0,1).'id'; $data = $dext = array(); if(in_array($pid,array('docs','users','coms','advs','types'))){ $data = glbData::getRow($this->mod, $this->key, $pid); if(empty($data)){ return $this->vars = "[{$this->key}]".basLang::show('core.vshow_uncheck'); } } $this->vars = $data; } // 首页静态 function homeStatic() { if($this->mod=='home' && !defined('RUN_STATIC') && $this->ucfg['hcfg']['vmode']=='static'){ $file = vopStatic::getPath('home','home',0); if($data=extCache::cfGet("/$file",$this->ucfg['hcfg']['stexp'],'html','str')){ echo $data; echo "\n"; die(); // 可以终止,生成静态不走这里 } } } // 分页标签 function chkPage($tagname) { global $_cbase; $nowtpl = $_cbase['run']['tplnow']; if(empty($this->pgflag)){ $this->pgflag = array('tpl'=>$nowtpl,'tag'=>$tagname,); }else{ $msg0 = "".basLang::show('core.vshow_1pagetag').""; $msg1 = '
    tpl:'.$this->pgflag['tpl'].', tag:'.$this->pgflag['tag']; $msg2 = '
    tpl:'.$nowtpl.', tag:'.$tagname; $this->msg("$msg0$msg1$msg2"); } } // 解析 function tagParse($tagname, $type, $paras=array()){ global $_cbase; $res = tagCache::comTag($type, $this->mkv, $paras); if(!empty($res[1])){ //缓存 $data = $res[1]; if(isset($data['page_bar'])){ $_cbase['page']['bar'] = $data['page_bar']; unset($data['page_bar']); } }else{ if($type=='Page') $this->chkPage($tagname); $this->tagRun('tagnow',$tagname); $class = "\\imcat\\tag$type"; $_1tag = new $class($paras); $data = $_1tag->getData(); if($res[0]){ tagCache::setCache($res[0],$data,1,$type=='Page'); } } return $data; } // setRun function tagRun($key,$val='',$ext=''){ global $_cbase; $_cbase['run'][$key] = $val; if($ext) $_cbase['run'][substr($key,0,3).$ext][] = $val; $tpldir = $this->tplCfg['vdir']; } // unset function tagEnd($tname=''){} //模板赋值 function set($name, $value=''){} // msg分析 static function msg($msg=''){ if(!defined('RUN_STATIC')){ glbError::show($msg, 0); }else{ return $msg; } } // page-meta function pmeta($title='',$keywd='',$desc=''){ global $_cbase; $mcfg = glbConfig::read($this->mod); if($this->type=='detail'){ if(empty($title) && !empty($this->vars['title'])) $title = $this->vars['title']; if(empty($keywd) && !empty($this->vars['seo_key'])) $keywd = $this->vars['seo_key']; if(empty($desc) && !empty($this->vars['seo_des'])) $desc = $this->vars['seo_des']; }elseif(in_array($this->type,array('mhome','mext'))){ if(empty($title)) $title = @$mcfg['title']; if(isset($mcfg['i']) && empty($keywd)){ $a = comTypes::getSubs($mcfg['i'],'0','1'); $gap = ''; foreach($a as $k=>$v){ $keywd .= "$gap$v[title]"; $gap = ','; } //公司新闻,客户新闻,行业新闻 } }elseif($this->type=='mtype'){ if(empty($title) && !empty($mcfg['i'][$this->key]['title'])){ $title = $mcfg['i'][$this->key]['title']; if(!empty($mcfg['i'][$this->key]['pid'])){ $title .= '-'.$mcfg['i'][$mcfg['i'][$this->key]['pid']]['title']; } //子类3-栏目四 } } if($title){ $title = str_replace('(sys_name)',$_cbase['sys_name'],$title); if(!strstr($title,$_cbase['sys_name'])) $title .= " - ".$_cbase['sys_name']; } $ua = $this->ucfg['ua']; $up = empty($ua['page']) ? 1 : $ua['page']; //??? $ext = count($ua)>5 || $up>5; glbHtml::page('init',$ext); if($title) echo "".basStr::filTitle($title)."\n"; if($keywd) echo "\n"; if($desc) echo "\n"; } } ### file: /share_imcat/core/vops/tagFree.php paras = $paras; $this->setDbkey($paras); // 首先设置dbkey $this->db = glbDBObj::dbObj($this->dbkey); $this->setModid(); $this->pJoin(); $this->pOrder(); $this->pLimit(); $this->pOffset(); $this->pWhere(); $this->resData(); } // Dbkey: function setDbkey($paras=array()){ $this->paras = $paras; $para = $this->p1Cfg('dbkey'); $this->dbkey = empty($para[1]) ? $this->dbkey : $para[1]; } // [join,$joinstr] function pJoin(){ $cfg = $this->p1Cfg('join'); if(empty($cfg)) return; if(!empty($cfg[1])){ $this->join = $cfg[1]; } } // [where,$whrstr] function pWhere(){ $cfg = $this->p1Cfg('where'); if(empty($cfg)) return; if(!empty($cfg[1])){ $this->where = $cfg[1]; } } // resData: function resData(){ $cfg = $this->p1Cfg('pgbar'); $this->from = "m.* FROM ".glbDBObj::dbObj($this->dbkey)->table($this->modid,2)." m "; if($this->join) $this->from .= " $this->join "; return empty($cfg[1]) ? $this->resLister() : $this->resPager(); } function resLister(){ $where = $this->where ? ' WHERE '.$this->where : ''; $offset = empty($this->sqlArr['offset']) ? '' : $this->sqlArr['offset'].','; $ordLimit = "ORDER BY ".$this->sqlArr['ofull']." LIMIT $offset".$this->sqlArr['limit']; $this->sqlAll = "SELECT {$this->from} {$where} $ordLimit"; $this->re = $this->db->query($this->sqlAll); return $this->re; } function resPager(){ global $_cbase; $order = "m.".$this->sqlArr['order']; $pg = new comPager($this->from,$this->where,$this->sqlArr['limit'],$order); $pg->set('odesc',$this->sqlArr['odesc']); $pg->set('opkey',0); $this->re = $pg->exe($this->dbkey); $this->sqlAll = $pg->sql; // $idfirst = ''; $idend = ''; $burl = basReq::getUri(-1,'','page|prec|ptype|pkey'); $_cbase['page']['bar'] = "
    ".$pg->show(0,0,'',$burl)."
    "; $_cbase['page']['prec'] = $pg->prec; } function getData(){ return $this->re; } } ### file: /share_imcat/core/vops/vopStatic.php "{title}", '2'=> "{title}", '3'=> "{detail}", ); $tpl = empty($cfg['i'][$type]['cfgs']) ? $dtpl[$cfg['etab']] : $cfg['i'][$type]['cfgs']; if(!strpos($tpl,'target')) $tpl = str_replace('table("advs_$mod")->where("catid='$type' AND `show`='1'")->select(); if($list){ foreach($list as $r){ $istr = $tpl; $r['urlorg'] = $r['url']; if(in_array($cfg['etab'],array(1,2))){ $r['url'] = PATH_ROOT."/plus/api/redir.php?advs:".comConvert::sysBase64("$mod,$r[aid],$r[url]"); } foreach($rep as $key){ $istr = str_replace('{'.$key.'}',$r[$key],$istr); } $istr = str_replace(array('{root}','{$root}'),PATH_ROOT,$istr); if($cfg['etab']==3 && !empty($r['url'])){ $_arep = explode('[=]',$r['url']); $istr = str_replace($_arep[0],$_arep[1],$istr); } $data .= "$istr\r\n"; } } $data = comStore::revSaveDir($data); $file = tagCache::caPath($mod,$type,0); comFiles::chkDirs($file,'ctpl'); comFiles::put(DIR_CTPL."/$file",$data); return $data; } //广告Static(按类别) static function advMod($mod,$aids=array()){ $cfg = glbConfig::read($mod); if($cfg['etab']==4) return; if($mod=='adpush') return; $ids = ''; if(is_array($aids)){ foreach($aids as $id=>$v){ if(empty($id)) continue; $ids .= (empty($ids) ? '' : ',')."'$id'"; } }else{ $ids = "'$aids'"; } if(!$ids) return; $whr = $ids=="'(all)'" ? '1=1' : "aid IN($ids)"; $types = array(); $data = ''; $list = glbDBObj::dbObj()->field('DISTINCT catid')->table("advs_$mod")->where($whr)->select(); //frame=0 AND if($list){ foreach($list as $r){ $caid = $r['catid']; if(!isset($cfg['i'][$caid])) break; $ditm = self::advType($mod,$caid); $data .= "[$caid]-{$cfg['i'][$caid]['title']}:::
    $ditm
    "; } } return $data; } // showRes static function showRes($res){ $msg = basLang::show('core.vops_batres')."

    \n"; $msg .= $res['msg'] ? $res['msg']."
    " : basLang::show('core.vops_dores',"[{$res['ok']}/{$res['cnt']}]")."
    \n"; $msg .= "[".date('Y-m-d H:i:s')."]
    \n"; if($res['next']){ $msg .= "
    \n".basLang::show('core.vops_3secnext')."
    \n"; $js = "setTimeout(\"location.href='{$res['url']}';\",3000);"; $js = basJscss::jscode($js); }else{ $msg .= "
    \n".basLang::show('core.vops_end')."
    \n"; $js = ''; } glbHtml::page(basLang::show('core.vops_res')); glbHtml::page('body'); echo "\n

    $msg

    \n
    \n$js"; unset($res['msg']); basDebug::varShow($res); glbHtml::page('end'); } static function batList($mod,$tpl){ $re = array('msg'=>'','cnt'=>0,'ok'=>0,'next'=>'','min'=>'','max'=>'',); $lists = vopTpls::entry($tpl,'ehlist','static'); $listn = $lists[$mod]; $msg = ''; foreach($listn as $key=>$v){ if(!strpos($v,'/')) continue; //first,close $key = $key=='m' ? "" : "-$key"; $msg .= vopStatic::toFile("$mod$key")."
    \n"; } $re['msg'] = $msg; return $re; } static function batDetail($mod,$tpl){ $re = array('msg'=>'','cnt'=>0,'ok'=>0,'next'=>'','min'=>'','max'=>'',); $data = self::batKids($mod); $msg = ''; $vcfg = glbConfig::vcfg($mod); if(!empty($data)){ foreach($data as $key=>$row){ $oid = $key; if(empty($re['min']) || $oid<$re['min']) $re['min'] = $oid; if(empty($re['max']) || $oid>$re['max']) $re['max'] = $oid; if(empty($vcfg['c']['stypes']) || in_array($row['type'],$vcfg['c']['stypes'])){ $da = is_array($vcfg['d']) ? $vcfg['d'] : array('0'=>1); foreach ($da as $ka => $va) { $msg .= vopStatic::toFile("$mod.$key".(empty($ka)?'':".$ka"))."
    \n"; } $re['cnt']++; }else{ $msg .= "[$mod.$key][{$row['type']}] Skip...
    \n"; } } $re['next'] = 1; }else{ $re['msg'] = 'No Data'; $re['next'] = 0; } $re['msg'] = $msg; if($re['next']){ $offset = basReq::val('order')=='ASC' ? $re['max'] : $re['min']; $re['url'] = basReq::getURep(0,'offset',$offset); } return $re; } // mod,limit(1-500),order(did:ASC),stype,offset static function batKids($mod){ $mcfg = glbConfig::read($mod); $whrstr = ''; $stype = basReq::val('stype'); $offset = basReq::val('offset'); $limit = basReq::val('limit',10,'N'); if($limit<1) $limit = 10; $order = basReq::val('order','DESC'); if(in_array($mcfg['pid'],array('docs','advs'))){ $stype && $whrstr .= basSql::whrTree($mcfg['i'],'catid',$stype); $ftype = ',catid'; $tabid = "docs_$mod"; }elseif(in_array($mcfg['pid'],array('users'))){ $stype && $whrstr .= " AND grade='$stype'"; $ftype = ',grade'; $tabid = "users_$mod"; }else{ $ftype = ''; } $kname = substr($mcfg['pid'],0,1).'id'; $omod = in_array(strtoupper($order),array('ASC','DESC','EQ')) ? strtoupper($order) : 'DESC'; $offset = basReq::val('offset'); if($offset){ if(strstr($omod,'DESC')){ $op = '<'; }elseif(strstr($omod,'ASC')){ $op = '>'; }else{ // EQ $op = '='; } $whrstr .= " AND $kname$op'$offset'"; } $whrstr = $whrstr ? substr($whrstr,5) : '1=1'; $data = glbDBObj::dbObj()->field("$kname$ftype,`show`")->table($tabid)->where($whrstr)->order("$kname $omod")->limit($limit)->select(); $re = array(); if(!empty($data)){ foreach($data as $row){ $type = $ftype ? $row[substr($ftype,1)] : $ftype; $re[$row[$kname]] = array('show'=>$row['show'],'type'=>$type); } } return $re; } static function delList($mod,$tpl){ $re = array('msg'=>'','cnt'=>0,'ok'=>0,'next'=>'','min'=>'','max'=>'',); $lists = vopTpls::entry($tpl,'ehlist','static'); $listn = $lists[$mod]; $msg = ''; foreach($listn as $key=>$v){ $key = $key=='m' ? "" : $key; $file = self::getPath($mod,$key,0); $res = @unlink(DIR_HTML.'/'.$file); $res = var_export($res,1); $msg .= "{$res}:".$file."
    \n"; } $re['msg'] = $msg; return $re; } static function delDetail($mod,$sub=''){ static $fext, $msg; if(empty($fext)){ $mcfg = glbConfig::vcfg($mod); $fext = $mcfg['c']['stext']; $msg = ''; } $dfix = basReq::val('offset'); $elen = strlen($fext); $ndir = DIR_HTML."/$mod$sub"; if(!is_dir("$ndir")){ return false; }; $handle = opendir("$ndir"); while(($file = readdir($handle)) !== false){ if($file != "." && $file != ".."){ if(in_array($file,array('index.htm','index.html'))) continue; if(is_dir("$ndir/$file")){ if(empty($sub) && $file=='home'){ continue; } if(empty($sub) && $dfix && strstr($file,$dfix)){ continue; } self::delDetail($mod,"$sub/$file"); }else{ if(substr($file,-$elen,$elen)==$fext){ $res = @unlink("$ndir/$file"); $res = var_export($res,1); $msg .= "{$res}:$sub/$file
    \n"; } } } } $re = array('cnt'=>substr_count($msg,'
    '),'ok'=>substr_count($msg,'true:'),'next'=>'',); $re['msg'] = $msg; return $re; } //生成Static文件(当前模板) static function toFile($q=''){ basEnv::runCbase(); //重置参数 defined('RUN_STATIC') || define('RUN_STATIC',1); static $vop; if(empty($vop)) $vop = new vopApp(0); ob_start(); $err = $vop->run($q); if(empty($vop->ucfg)){ return $vop->err ? $vop->err : "($q)Error! Has NO set tpl!"; } $re = ob_get_contents(); $kid = $vop->mod=='home' ? 'home' : $vop->key; $vext = empty($vop->view) ? '' : ".$vop->view"; $file = self::getPath($vop->mod,$kid.$vext,0); $msg = $file.' : '.basStr::showNumber(strlen($re),'Byte').''; comFiles::chkDirs($file,'html'); comFiles::put(DIR_HTML.'/'.$file,"$re\n"); ob_end_clean(); return $msg; } //获得Static文件路径(当前模板): static function getPath($mod,$kid,$isfull=1){ $kid || $kid = 'home'; $dir = comStore::getResDir($mod,$kid,$isfull); if($isfull){ $dir = DIR_HTML.substr($dir,strlen(DIR_URES)); } $mcfg = glbConfig::vcfg($mod); return $dir.(empty($mcfg['c']['stext']) ? '.htm' : $mcfg['c']['stext']); } //updKid:更新(add,del,edit)一个Kid的静态 static function updKid($mod,$kid,$act='upd',$itype=''){ global $_cbase; $tplbak = $_cbase['tpl']['vdir']; $vcfg = vopTpls::etr1('tpl'); $re = array(); foreach($vcfg as $tpl=>$suit){ if(strpos($_cbase['tpl']['no_static'],$tpl)) continue; $file = DIR_VIEWS."/$tpl/_config/vc_$mod.php"; if(file_exists($file)){ include $file; $kc = "_vc_$mod"; $cfg = $$kc; if($itype && !empty($cfg['c']['stypes']) && !in_array($itype,$cfg['c']['stypes'])){ continue; // 忽略不需要生成静态的页面 } if($cfg['c']['vmode']=='static'){ if($act=='del'){ $_cbase['tpl']['vdir'] = $tpl; $re[$tpl] = self::getPath($mod,$kid,1); }else{ $re[$tpl] = "$mod.$kid"; } } } } $_cbase['tpl']['vdir'] = $tplbak; return $re; } //是否需要生成静态 static function chkNeed($mkv=''){ $moda = vopUrl::imkv(array('mkv'=>$mkv),'a'); $kid = $moda[0]=='home' ? 'home' : $moda[1]; $vcfg = glbConfig::vcfg($moda[0]); if(@$vcfg['c']['vmode']!='static') return 0; $vext = empty($moda[2]) ? '' : ".$moda[2]"; $file = self::getPath($moda[0],$kid.$vext,0); $flag = !extCache::cfGet("/$file",$vcfg['c']['stexp'],'html'); return $flag; } } ### file: /share_imcat/core/vops/tagPush.php table($this->sqlArr['tabid'],2)." m "; $where = empty($this->whrStr) ? '' : "WHERE ".$this->whrStr; $this->sqlAll = "SELECT $sfrom $where LIMIT 1"; //ORDER BY `top` $re = $this->db->query($this->sqlAll); if(empty($re[0]['detail'])){ $re = array(); }else{ $re = comParse::jsonDecode($re[0]['detail']); } $this->re = $re; return $re; } // ucfg.ctab // 1=Y;0=N static function opts($tab='1=Y;0=N',$val=''){ $ops = ''; if(strpos($tab,'.')>0){ $arr = explode(',','000,'.cfg($tab)); foreach ($arr as $iv) { $def = "$val"=="$iv" ? 'selected' : ''; $ops .= "\n