分析日志文件
BaZhang Platform
@Author   Jacklin@shouyiren.net
@DateTime 2019-01-31T10:59:05+0800
@param    string                   $file    日志文件
@param    string                   $outfile 分析结果文件
@return   boolean
161513
public static function analysisLogFile($logFile,$outFile='./analysis_log.csv'){
		$handle = @fopen($logFile, "r");
		if ($handle) {
			$i = 0;
		    while (($buffer = fgets($handle, 4096)) !== false) {
		       self::dealStr($buffer);
		    }
		    ksort(self::$ret);
		    foreach (self::$ret as $value) {
		    	$bandwidth = round($value['rate']/1000/128/self::$preTime,2);//单位Mbps
		    	$flow = round($value['rate']/1000/1000/1024,3);//单位GB
		    	$txt = $value['date']."\t".$flow."GB\t".$bandwidth."Mbps".PHP_EOL;//时间点
		    	try{
			    	file_put_contents($outFile,$txt, FILE_APPEND | LOCK_EX);
		    	}catch(\Exception $e){
		        throw new \Exception("Error: ".$e->getMessage());
		        return false;
		    	}
		    }
		    if (!feof($handle)) {
		        throw new \Exception("Error: unexpected fgets() fail");
		    }
		    fclose($handle);
		   return true;
		}else{
		   return false;
		}
	}
610534
public function registerFile($file)
    {
        $file = realpath($file) . DIRECTORY_SEPARATOR;
        $files = get_files_by_ext($file, 'lua');
        $sha1s = [];
        $luas = [];
        $names = [];
        foreach ($files as $file_name) {
            $lua = file_get_contents($file . $file_name);//将整个文件内容读入到一个字符串中
            list($name, $ext) = explode('.', $file_name);
            $sha1s[] = sha1($lua);
            $luas[] = $lua;
            $names[] = $name;
        }
        $this->registerLuas($sha1s, $luas, $names);
    }
918307
public function decideTargetFile()
    {
        if (empty($this->targetLogDir)) {
            return false;
        }
        if ($this->forceUseStandardOutputInCLI && LibRequest::isCLI()) {
            return false;
        }
        if (!file_exists($this->targetLogDir)) {
            @mkdir($this->targetLogDir, 0777, true);
        }
        $today = date('Y-m-d');
        return $this->targetLogDir . '/log-' . (empty($this->prefix) ? '' : $this->prefix . '-') . $today . '.log';
    }
664252
protected function fileMime($file, $rule)
    {
        if (!($file instanceof File)) {
            return false;
        }
        if (is_string($rule)) {
            $rule=explode(',', $rule);
        }
        if (is_array($file)) {
            foreach ($file as $item) {
                if (!$item->checkMime($rule)) {
                    return false;
                }
            }
            return true;
        } else {
            return $file->checkMime($rule);
        }
    }
219120
function read($file,$lf=FALSE) {
		$out=@file_get_contents($file);
		return $lf?preg_replace('/\r\n|\r/',"\n",$out):$out;
	}
143311
public function lint($file)
    {
        $template = $this->app['twig.loader.viewfinder']->getSourceContext($file);

        if (!$template) {
            throw new InvalidArgumentException('Unable to find file: '.$file);
        }

        try {
            $this->parse($this->tokenize($template, $file));
        } catch (Error $e) {
            return false;
        }

        return true;
    }
1209352
public function uploadimg($file)
    {
        if (!$file) {
            $this->setError('参数缺失');

            return false;
        }

        if (!file_exists($file)) {
            $this->setError('文件路径不正确');

            return false;
        }

        $data          = [];
        $data['media'] = '@' . realpath($file);

        $node = 'uploadimg';

        $res = $this->_post($node, $data, false);

        return $res;
    }
1181339
public function export($file, $translations)
    {
        $bytes = false;

        if (pathinfo($file, PATHINFO_EXTENSION) === 'yml') {
            $ymlDumper = new Dumper();
            $ymlContent = '';
            $ymlContent .= $ymlDumper->dump($translations, 10);
            $bytes = file_put_contents($file, $ymlContent);
        }

        return ($bytes !== false);
    }
1157222
public function setFile($file)
    {

        //Return false if file does not exists;
        if (!$this->isFile($file)) {
            return false;
        }
        //Get the file info
        $this->file = $file;
        $this->pathinfo[$file] = pathinfo($file);

        //Return an instance of the file object;
        return $this;
    }
226921
public static function run( ? string $files = '*') : bool
    {
        if (self::$status) {
            return false;
        }
        self::$status = 1;
        $config       = Linker::Config()::get('lin')['route'];
        $url          = Linker::Request()::getURL(); //当前url
        $url          = '/' . ltrim($url, '/'); //确保含有根路径
        $method       = Linker::Request()::getMethod(); //当期请求方法

        //url去掉伪后缀名
        foreach ($config['suffix'] as $pattern) {
            $n   = 0;
            $url = preg_replace("/\.$pattern$/", '', $url, 1, $n); //只踢除一次后缀名
            if ($n) {
                break;
            }
        }

        //运行解析器获得执行流程
        if (!$files) {
            $rules = null;
        } else {
            $Parser = new Parser($config);
            $rules  = $Parser->execute($files, $url, strtoupper($method)); //获得执行规则
        }

        //执行通用规则
        if (!$rules) {
            if (is_callable($config['general'])) {
                call_user_func_array($config['general'], [$url, $method]);
            }
            if ($config['debug']) {
                (new Debug)->type('general');
            }
            return true;
        }

        //执行用户规则
        $params = $rules['params'];
        $rules  = $rules['rules'];
        //存在动态参数，合并入当期请求的参数里
        if ($params) {
            $old_params = Linker::Request()::getCurrent();
            Linker::Request()::setCurrent(array_merge($old_params, $params));
        }

        //执行流程
        $return = true;
        $times  = [];
        $t      = microtime(true);
        foreach ($rules as $index => $rule) {
            if ($rule[0] instanceof Closure) {
                $r = call_user_func_array($rule[0], $params); //只有闭包才使用动态参数
            } else {
                $r = call_user_func([new $rule[0], $rule[1]]);
            }
            $times[$index] = microtime(true) - $t;
            if (in_array($r, $config['terminal'], true)) {
                $return = false; //遭遇终止符
                break;
            }
        }
        if ($config['debug']) {
            (new Debug)->process($rules, $params, $index, $times); //记录实际执行流程
        }
        return $return;
    }
779328
private function getFile($file, $type = 0)
    {
        $type == 1 && $file = $this->initBaseDir($file);//初始化路径
        //$file = str_replace([('/', '\\'], DIRECTORY_SEPARATOR, $file);
        $cacheFile = $this->getCacheFile($file);
        if ($this->options['autoUpdate']) {
            $tplFile = $this->getTplFile($file);
            if (!is_readable($tplFile)) {
                throw new FileCanNotReadableException(Lang::get('_TEMPLATE_FILE_NOT_FOUND_', $tplFile));
            }
            if (!is_file($cacheFile)) {
                if ($type !== 1 && !is_null($this->layout)) {
                    if (!is_readable($this->layout)) {
                        throw new FileCanNotReadableException(Lang::get('_TEMPLATE_FILE_NOT_FOUND_', $this->layout));
                    }
                }
                $this->compile($tplFile, $cacheFile, $type);
                return $cacheFile;
            }

            $compile = false;
            $tplMtime = filemtime($tplFile);
            $cacheMtime = filemtime($cacheFile);
            if ($cacheMtime && $tplMtime) {
                ($cacheMtime < $tplMtime) && $compile = true;
            } else {//获取mtime失败
                $compile = true;
            }

            if ($compile && $type !== 1 && !is_null($this->layout)) {
                if (!is_readable($this->layout)) {
                    throw new FileCanNotReadableException(Lang::get('_TEMPLATE_FILE_NOT_FOUND_', $this->layout));
                }
            }

            //当子模板未修改时判断布局模板是否修改
            if (!$compile && $type !== 1 && !is_null($this->layout)) {
                if (!is_readable($this->layout)) {
                    throw new FileCanNotReadableException(Lang::get('_TEMPLATE_FILE_NOT_FOUND_', $this->layout));
                }
                $layoutMTime = filemtime($this->layout);
                if ($layoutMTime) {
                    $cacheMtime < $layoutMTime && $compile = true;
                } else {
                    $compile = true;
                }
            }

            $compile && $this->compile($tplFile, $cacheFile, $type);
        }
        return $cacheFile;
    }
529483
static function log( $logline, $out = '' ) {
		// Output log line, no error checking to save performance
		// Send to descriptor or other stream if resource passed
		if( is_resource($out) && fwrite( $out, "$logline\n" ) ){
			return true;
		}
		// Log to specified file
		else if( $out && error_log( "$logline\n", 3, $out ) ){
			return $out;
		}
		// else default - probably apache error log
		else if( error_log( $logline, 0 ) ){
			$out = ini_get('error_log');
			return $out ? $out : true;
		}
		else {
			return false;
		}
	}
1185967
public function import($file) {
        $stream = new Stream($file);
        if (!$stream->openRead()->isResource()) {
            return false;
        }
        $content = '';
        while ($line = $stream->readLine(self::LINE_MAX_LENGTH)) {
            if (substr($line, 0, 2) == '--' || $line == '') {
                continue;
            }
            $content .= $line;
            if (substr(trim($line), -1, 1) !== ';') {
                continue;
            }
            $this->command()->execute($content);
            $content = '';
        }
        $stream->close();
        return true;
    }
554407
public function getLocalFile($file = '') {
        #判断数据不为空
        if (empty($file)) {
            return [];
        }
        $data = [];
        foreach ($file as $key => $value) {
            $path = ROOT_DIR . $value['name'];
            if (is_file($path)) {
                #获取文件内容
                $value['content'] = encrypt(file_get_contents($path));
                $data[]           = $value;
            }
        }
        return $data;
    }
542289
private function write(string $file, string $msg)
    {
        // 将文件名中的目录分隔符标准化
        $file = str_replace('\\', '/', $file);

        // 在日志目录下创建年目录
        $path = $this->dirRoot . date('Y-m-d') . '/' . $file . '.log';
        makeDir(dirname($path));

        // 写入文件
        return write($path, $msg, FILE_APPEND | LOCK_EX);
    }
1262191
private function save($file)
    {
        $filename = $file['savepath'].$file['savename'];
        if (!$this->config['replace'] && is_file($filename)) { //不覆盖同名文件
            $this->errorInfo = "文件已经存在{$filename}";
            return false;
        }

        //如果是图片，检查格式
        if ( in_array(strtolower($file['extension']), ['gif', 'jpg', 'jpeg', 'bmp', 'png', 'swf'])
            && false === getimagesize($file['tmp_name']) ) {
            $this->errorInfo = '非法图像文件';
            return false;
        }
        if (!move_uploaded_file($file['tmp_name'], $filename)) {
            $this->errorInfo = '文件上传错误!';
            return false;
        }

        if ($this->config['thumb'] && in_array(strtolower($file['extension']), ['gif', 'jpg', 'jpeg', 'bmp', 'png'])) {
            if ($image = getimagesize($filename)) {
                //生成缩略图
                $thumbPath = $this->config['thumbPath'] ? $this->config['thumbPath'] : dirname($filename);
                $thunbName = $this->config['thumbFile'] ? $this->config['thumbFile'] : $this->config['thumbPrefix'].basename($filename);
                Image::makeThumb($filename, $thumbPath.'/'.$thunbName, null, $this->config['thumbMaxWidth'], $this->config['thumbMaxHeight']);
            }
        }
        return true;
    }
1169628
public static function extract($file = false, $destination = false) {

        if($file) {

            if(!$destination) {
                $destination = __DIR__;
            }

            if(!Folder::isFolder($destination)) {
                if(!Folder::create($destination)) {
                    return false;
                }
            }

            $zip = new \ZipArchive;
            $res = $zip->open($file);
            if ($res === true) {
              $zip->extractTo($destination);
              $zip->close();
              return true;
            } 
        }

        return false;
    }