code stringlengths 1 2.01M | repo_name stringlengths 3 62 | path stringlengths 1 267 | language stringclasses 231 values | license stringclasses 13 values | size int64 1 2.01M |
|---|---|---|---|---|---|
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2009 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
// $Id$
/** 输入数据管理类
* 使用方法
* $Input = Input::getInstance();
* $Input->get('name','md5','0');
* $Input->session('memberId','','0');
*
* 下面总结了一些常用的数据处理方法。以下方法无需考虑magic_quotes_gpc的设置。
*
* 获取数据:
* 如果从$_POST或者$_GET中获取,使用Input::getVar($_POST['field']);,从数据库或者文件就不需要了。
* 或者直接使用 Input::magicQuotes来消除所有的magic_quotes_gpc转义。
*
* 存储过程:
* 经过Input::getVar($_POST['field'])获得的数据,就是干净的数据,可以直接保存。
* 如果要过滤危险的html,可以使用 $html = Input::safeHtml($data);
*
* 页面显示:
* 纯文本显示在网页中,如文章标题<title>$data</title>: $data = Input::forShow($field);
* HTML 在网页中显示,如文章内容:无需处理。
* 在网页中以源代码方式显示html:$vo = Input::forShow($html);
* 纯文本或者HTML在textarea中进行编辑: $vo = Input::forTarea($value);
* html在标签中使用,如<input value="数据" /> ,使用 $vo = Input::forTag($value); 或者 $vo = Input::hsc($value);
*
* 特殊使用情况:
* 字符串要在数据库进行搜索: $data = Input::forSearch($field);
*/
class Input extends Think
{
private $filter = null; // 输入过滤
private static $_input = array('get','post','request','env','server','cookie','session','globals','config','lang','call');
//html标签设置
public static $htmlTags = array(
'allow' => 'table|td|th|tr|i|b|u|strong|img|p|br|div|strong|em|ul|ol|li|dl|dd|dt|a',
'ban' => 'html|head|meta|link|base|basefont|body|bgsound|title|style|script|form|iframe|frame|frameset|applet|id|ilayer|layer|name|script|style|xml',
);
static public function getInstance() {
return get_instance_of(__CLASS__);
}
/**
+----------------------------------------------------------
* 魔术方法 有不存在的操作的时候执行
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $type 输入数据类型
* @param array $args 参数 array(key,filter,default)
+----------------------------------------------------------
* @return mixed
+----------------------------------------------------------
*/
public function __call($type,$args=array()) {
$type = strtolower(trim($type));
if(in_array($type,self::$_input,true)) {
switch($type) {
case 'get': $input =& $_GET;break;
case 'post': $input =& $_POST;break;
case 'request': $input =& $_REQUEST;break;
case 'env': $input =& $_ENV;break;
case 'server': $input =& $_SERVER;break;
case 'cookie': $input =& $_COOKIE;break;
case 'session': $input =& $_SESSION;break;
case 'globals': $input =& $GLOBALS;break;
case 'files': $input =& $_FILES;break;
case 'call': $input = 'call';break;
case 'config': $input = C();break;
case 'lang': $input = L();break;
default:return NULL;
}
if('call' === $input) {
// 呼叫其他方式的输入数据
$callback = array_shift($args);
$params = array_shift($args);
$data = call_user_func_array($callback,$params);
if(count($args)===0) {
return $data;
}
$filter = isset($args[0])?$args[0]:$this->filter;
if(!empty($filter)) {
$data = call_user_func_array($filter,$data);
}
}else{
if(0==count($args) || empty($args[0]) ) {
return $input;
}elseif(array_key_exists($args[0],$input)) {
// 系统变量
$data = $input[$args[0]];
$filter = isset($args[1])?$args[1]:$this->filter;
if(!empty($filter)) {
$data = call_user_func_array($filter,$data);
}
}else{
// 不存在指定输入
$data = isset($args[2])?$args[2]:NULL;
}
}
return $data;
}
}
/**
+----------------------------------------------------------
* 设置数据过滤方法
+----------------------------------------------------------
* @access private
+----------------------------------------------------------
* @param mixed $filter 过滤方法
+----------------------------------------------------------
* @return void
+----------------------------------------------------------
*/
public function filter($filter) {
$this->filter = $filter;
return $this;
}
/**
+----------------------------------------------------------
* 字符MagicQuote转义过滤
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @return void
+----------------------------------------------------------
*/
static public function noGPC()
{
if ( get_magic_quotes_gpc() ) {
$_POST = stripslashes_deep($_POST);
$_GET = stripslashes_deep($_GET);
$_COOKIE = stripslashes_deep($_COOKIE);
$_REQUEST= stripslashes_deep($_REQUEST);
}
}
/**
+----------------------------------------------------------
* 处理字符串,以便可以正常进行搜索
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $string 要处理的字符串
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
static public function forSearch($string)
{
return str_replace( array('%','_'), array('\%','\_'), $string );
}
/**
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $string 要处理的字符串
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
static public function forShow($string)
{
return self::nl2Br( self::hsc($string) );
}
/**
+----------------------------------------------------------
* 处理纯文本数据,以便在textarea标签中显示
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $text 要处理的字符串
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
static public function forTarea($string)
{
return str_ireplace(array('<textarea>','</textarea>'), array('<textarea>','</textarea>'), $string);
}
/**
+----------------------------------------------------------
* 将数据中的单引号和双引号进行转义
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $text 要处理的字符串
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
static public function forTag($string)
{
return str_replace(array('"',"'"), array('"','''), $string);
}
/**
+----------------------------------------------------------
* 转换文字中的超链接为可点击连接
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $text 要处理的字符串
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
function makeLink($string)
{
$validChars = "a-z0-9\/\-_+=.~!%@?#&;:$\|";
$patterns = array(
"/(^|[^]_a-z0-9-=\"'\/])([a-z]+?):\/\/([{$validChars}]+)/ei",
"/(^|[^]_a-z0-9-=\"'\/])www\.([a-z0-9\-]+)\.([{$validChars}]+)/ei",
"/(^|[^]_a-z0-9-=\"'\/])ftp\.([a-z0-9\-]+)\.([{$validChars}]+)/ei",
"/(^|[^]_a-z0-9-=\"'\/:\.])([a-z0-9\-_\.]+?)@([{$validChars}]+)/ei");
$replacements = array(
"'\\1<a href=\"\\2://\\3\" title=\"\\2://\\3\" rel=\"external\">\\2://'.Input::truncate( '\\3' ).'</a>'",
"'\\1<a href=\"http://www.\\2.\\3\" title=\"www.\\2.\\3\" rel=\"external\">'.Input::truncate( 'www.\\2.\\3' ).'</a>'",
"'\\1<a href=\"ftp://ftp.\\2.\\3\" title=\"ftp.\\2.\\3\" rel=\"external\">'.Input::truncate( 'ftp.\\2.\\3' ).'</a>'",
"'\\1<a href=\"mailto:\\2@\\3\" title=\"\\2@\\3\">'.Input::truncate( '\\2@\\3' ).'</a>'");
return preg_replace($patterns, $replacements, $string);
}
/**
+----------------------------------------------------------
* 缩略显示字符串
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $text 要处理的字符串
* @param int $length 缩略之后的长度
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
static public function truncate($string, $length = '50')
{
if ( empty($string) || empty($length) || strlen($string) < $length ) return $string;
$len = floor( $length / 2 );
$ret = substr($string, 0, $len) . " ... ". substr($string, 5 - $len);
return $ret;
}
/**
+----------------------------------------------------------
* 把换行转换为<br />标签
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $text 要处理的字符串
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
static public function nl2Br($string)
{
return preg_replace("/(\015\012)|(\015)|(\012)/", "<br />", $string);
}
/**
+----------------------------------------------------------
* 如果 magic_quotes_gpc 为关闭状态,这个函数可以转义字符串
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $text 要处理的字符串
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
static public function addSlashes($string)
{
if (!get_magic_quotes_gpc()) {
$string = addslashes($string);
}
return $string;
}
/**
+----------------------------------------------------------
* 从$_POST,$_GET,$_COOKIE,$_REQUEST等数组中获得数据
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $text 要处理的字符串
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
static public function getVar($string)
{
return Input::stripSlashes($string);
}
/**
+----------------------------------------------------------
* 如果 magic_quotes_gpc 为开启状态,这个函数可以反转义字符串
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $text 要处理的字符串
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
static public function stripSlashes($string)
{
if (get_magic_quotes_gpc()) {
$string = stripslashes($string);
}
return $string;
}
/**
+----------------------------------------------------------
* 用于在textbox表单中显示html代码
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $text 要处理的字符串
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
static function hsc($string)
{
return preg_replace(array("/&/i", "/ /i"), array('&', '&nbsp;'), htmlspecialchars($string, ENT_QUOTES));
}
/**
+----------------------------------------------------------
* 是hsc()方法的逆操作
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $text 要处理的字符串
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
static function undoHsc($text)
{
return preg_replace(array("/>/i", "/</i", "/"/i", "/'/i", '/&nbsp;/i'), array(">", "<", "\"", "'", " "), $text);
}
/**
+----------------------------------------------------------
* 输出安全的html,用于过滤危险代码
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $text 要处理的字符串
* @param mixed $tags 允许的标签列表,如 table|td|th|td
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
static public function safeHtml($text, $tags = null)
{
$text = trim($text);
//完全过滤注释
$text = preg_replace('/<!--?.*-->/','',$text);
//完全过滤动态代码
$text = preg_replace('/<\?|\?'.'>/','',$text);
//完全过滤js
$text = preg_replace('/<script?.*\/script>/','',$text);
$text = str_replace('[','[',$text);
$text = str_replace(']',']',$text);
$text = str_replace('|','|',$text);
//过滤换行符
$text = preg_replace('/\r?\n/','',$text);
//br
$text = preg_replace('/<br(\s\/)?'.'>/i','[br]',$text);
$text = preg_replace('/(\[br\]\s*){10,}/i','[br]',$text);
//过滤危险的属性,如:过滤on事件lang js
while(preg_match('/(<[^><]+)(lang|on|action|background|codebase|dynsrc|lowsrc)[^><]+/i',$text,$mat)){
$text=str_replace($mat[0],$mat[1],$text);
}
while(preg_match('/(<[^><]+)(window\.|javascript:|js:|about:|file:|document\.|vbs:|cookie)([^><]*)/i',$text,$mat)){
$text=str_replace($mat[0],$mat[1].$mat[3],$text);
}
if( empty($allowTags) ) { $allowTags = self::$htmlTags['allow']; }
//允许的HTML标签
$text = preg_replace('/<('.$allowTags.')( [^><\[\]]*)>/i','[\1\2]',$text);
//过滤多余html
if ( empty($banTag) ) { $banTag = self::$htmlTags['ban']; }
$text = preg_replace('/<\/?('.$banTag.')[^><]*>/i','',$text);
//过滤合法的html标签
while(preg_match('/<([a-z]+)[^><\[\]]*>[^><]*<\/\1>/i',$text,$mat)){
$text=str_replace($mat[0],str_replace('>',']',str_replace('<','[',$mat[0])),$text);
}
//转换引号
while(preg_match('/(\[[^\[\]]*=\s*)(\"|\')([^\2=\[\]]+)\2([^\[\]]*\])/i',$text,$mat)){
$text=str_replace($mat[0],$mat[1].'|'.$mat[3].'|'.$mat[4],$text);
}
//空属性转换
$text = str_replace('\'\'','||',$text);
$text = str_replace('""','||',$text);
//过滤错误的单个引号
while(preg_match('/\[[^\[\]]*(\"|\')[^\[\]]*\]/i',$text,$mat)){
$text=str_replace($mat[0],str_replace($mat[1],'',$mat[0]),$text);
}
//转换其它所有不合法的 < >
$text = str_replace('<','<',$text);
$text = str_replace('>','>',$text);
$text = str_replace('"','"',$text);
//反转换
$text = str_replace('[','<',$text);
$text = str_replace(']','>',$text);
$text = str_replace('|','"',$text);
//过滤多余空格
$text = str_replace(' ',' ',$text);
return $text;
}
/**
+----------------------------------------------------------
* 删除html标签,得到纯文本。可以处理嵌套的标签
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $text 要处理的html
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
static public function deleteHtmlTags($string, $br = false)
{
while(strstr($string, '>'))
{
$currentBeg = strpos($string, '<');
$currentEnd = strpos($string, '>');
$tmpStringBeg = @substr($string, 0, $currentBeg);
$tmpStringEnd = @substr($string, $currentEnd + 1, strlen($string));
$string = $tmpStringBeg.$tmpStringEnd;
}
return $string;
}
/**
+----------------------------------------------------------
* 处理文本中的换行
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $string 要处理的字符串
* @param mixed $br 对换行的处理,
* false:去除换行;true:保留原样;string:替换成string
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
static public function nl2($string, $br = '<br />')
{
if ($br == false) {
$string = preg_replace("/(\015\012)|(\015)|(\012)/", '', $string);
} elseif ($br != true){
$string = preg_replace("/(\015\012)|(\015)|(\012)/", $br, $string);
}
return $string;
}
}
?> | 0321hy | trunk/Lib/ThinkPHP/Lib/ORG/Util/Input.class.php | PHP | asf20 | 20,339 |
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2009 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
// $Id$
/**
+------------------------------------------------------------------------------
* 图像操作类库
+------------------------------------------------------------------------------
* @category ORG
* @package ORG
* @subpackage Util
* @author liu21st <liu21st@gmail.com>
* @version $Id$
+------------------------------------------------------------------------------
*/
class Image extends Think {//类定义开始
/**
+----------------------------------------------------------
* 取得图像信息
*
+----------------------------------------------------------
* @static
* @access public
+----------------------------------------------------------
* @param string $image 图像文件名
+----------------------------------------------------------
* @return mixed
+----------------------------------------------------------
*/
static function getImageInfo($img) {
$imageInfo = getimagesize($img);
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 public
+----------------------------------------------------------
* @param string $source 原文件名
* @param string $water 水印图片
* @param string $$savename 添加水印后的图片名
* @param string $alpha 水印的透明度
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
* @throws ThinkExecption
+----------------------------------------------------------
*/
static public function water($source, $water, $savename=null, $alpha=80, $pos=9) {
//检查文件是否存在
if (!file_exists($source) || !file_exists($water))
return false;
//图片信息
$sInfo = self::getImageInfo($source);
$wInfo = self::getImageInfo($water);
//如果图片小于水印图片,不生成图片
if ($sInfo["width"] < $wInfo["width"] || $sInfo['height'] < $wInfo['height'])
return false;
//建立图像
$sCreateFun = "imagecreatefrom" . $sInfo['type'];
$sImage = $sCreateFun($source);
$wCreateFun = "imagecreatefrom" . $wInfo['type'];
$wImage = $wCreateFun($water);
//设定图像的混色模式
imagealphablending($wImage, true);
//图像位置,默认为右下角右对齐
//$posY = $sInfo["height"] - $wInfo["height"];
//$posX = $sInfo["width"] - $wInfo["width"];
$ground_w = $sInfo["width"];
$ground_h = $sInfo["height"];
$w = $wInfo["width"];
$h = $wInfo["height"];
switch($pos) {
case 0://随机
$posX = rand(0,($ground_w - $w));
$posY = rand(0,($ground_h - $h));
break;
case 1://1为顶端居左
$posX = 0;
$posY = 0;
break;
case 2://2为顶端居中
$posX = ($ground_w - $w) / 2;
$posY = 0;
break;
case 3://3为顶端居右
$posX = $ground_w - $w;
$posY = 0;
break;
case 4://4为中部居左
$posX = 0;
$posY = ($ground_h - $h) / 2;
break;
case 5://5为中部居中
$posX = ($ground_w - $w) / 2;
$posY = ($ground_h - $h) / 2;
break;
case 6://6为中部居右
$posX = $ground_w - $w;
$posY = ($ground_h - $h) / 2;
break;
case 7://7为底端居左
$posX = 0;
$posY = $ground_h - $h;
break;
case 8://8为底端居中
$posX = ($ground_w - $w) / 2;
$posY = $ground_h - $h;
break;
case 9://9为底端居右
$posX = $ground_w - $w;
$posY = $ground_h - $h;
break;
default://随机
$posX = rand(0,($ground_w - $w));
$posY = rand(0,($ground_h - $h));
break;
}
//生成混合图像
imagecopymerge($sImage, $wImage, $posX, $posY, 0, 0, $wInfo['width'], $wInfo['height'], $alpha);
//输出图像
$ImageFun = 'Image' . $sInfo['type'];
//如果没有给出保存文件名,默认为原图像名
if (!$savename) {
$savename = $source;
@unlink($source);
}
//保存图像
$ImageFun($sImage, $savename);
imagedestroy($sImage);
}
function showImg($imgFile, $text='', $x='10', $y='10', $alpha='50') {
//获取图像文件信息
//2007/6/26 增加图片水印输出,$text为图片的完整路径即可
$info = Image::getImageInfo($imgFile);
if ($info !== false) {
$createFun = str_replace('/', 'createfrom', $info['mime']);
$im = $createFun($imgFile);
if ($im) {
$ImageFun = str_replace('/', '', $info['mime']);
//水印开始
if (!empty($text)) {
$tc = imagecolorallocate($im, 0, 0, 0);
if (is_file($text) && file_exists($text)) {//判断$text是否是图片路径
// 取得水印信息
$textInfo = Image::getImageInfo($text);
$createFun2 = str_replace('/', 'createfrom', $textInfo['mime']);
$waterMark = $createFun2($text);
//$waterMark=imagecolorallocatealpha($text,255,255,0,50);
$imgW = $info["width"];
$imgH = $info["width"] * $textInfo["height"] / $textInfo["width"];
//$y = ($info["height"]-$textInfo["height"])/2;
//设置水印的显示位置和透明度支持各种图片格式
imagecopymerge($im, $waterMark, $x, $y, 0, 0, $textInfo['width'], $textInfo['height'], $alpha);
} else {
imagestring($im, 80, $x, $y, $text, $tc);
}
//ImageDestroy($tc);
}
//水印结束
if ($info['type'] == 'png' || $info['type'] == 'gif') {
imagealphablending($im, FALSE); //取消默认的混色模式
imagesavealpha($im, TRUE); //设定保存完整的 alpha 通道信息
}
Header("Content-type: " . $info['mime']);
$ImageFun($im);
@ImageDestroy($im);
return;
}
//保存图像
$ImageFun($sImage, $savename);
imagedestroy($sImage);
//获取或者创建图像文件失败则生成空白PNG图片
$im = imagecreatetruecolor(80, 30);
$bgc = imagecolorallocate($im, 255, 255, 255);
$tc = imagecolorallocate($im, 0, 0, 0);
imagefilledrectangle($im, 0, 0, 150, 30, $bgc);
imagestring($im, 4, 5, 5, "no pic", $tc);
Image::output($im);
return;
}
}
/**
+----------------------------------------------------------
* 生成缩略图
+----------------------------------------------------------
* @static
* @access public
+----------------------------------------------------------
* @param string $image 原图
* @param string $type 图像格式
* @param string $thumbname 缩略图文件名
* @param string $maxWidth 宽度
* @param string $maxHeight 高度
* @param string $position 缩略图保存目录
* @param boolean $interlace 启用隔行扫描
+----------------------------------------------------------
* @return void
+----------------------------------------------------------
*/
static function thumb($image, $thumbname, $type='', $maxWidth=200, $maxHeight=50, $interlace=true) {
// 获取原图信息
$info = Image::getImageInfo($image);
if ($info !== false) {
$srcWidth = $info['width'];
$srcHeight = $info['height'];
$type = empty($type) ? $info['type'] : $type;
$type = strtolower($type);
$interlace = $interlace ? 1 : 0;
unset($info);
$scale = min($maxWidth / $srcWidth, $maxHeight / $srcHeight); // 计算缩放比例
if ($scale >= 1) {
// 超过原图大小不再缩略
$width = $srcWidth;
$height = $srcHeight;
} else {
// 缩略图尺寸
$width = (int) ($srcWidth * $scale);
$height = (int) ($srcHeight * $scale);
}
// 载入原图
$createFun = 'ImageCreateFrom' . ($type == 'jpg' ? 'jpeg' : $type);
$srcImg = $createFun($image);
//创建缩略图
if ($type != 'gif' && function_exists('imagecreatetruecolor'))
$thumbImg = imagecreatetruecolor($width, $height);
else
$thumbImg = imagecreate($width, $height);
// 复制图片
if (function_exists("ImageCopyResampled"))
imagecopyresampled($thumbImg, $srcImg, 0, 0, 0, 0, $width, $height, $srcWidth, $srcHeight);
else
imagecopyresized($thumbImg, $srcImg, 0, 0, 0, 0, $width, $height, $srcWidth, $srcHeight);
if ('gif' == $type || 'png' == $type) {
//imagealphablending($thumbImg, false);//取消默认的混色模式
//imagesavealpha($thumbImg,true);//设定保存完整的 alpha 通道信息
$background_color = imagecolorallocate($thumbImg, 0, 255, 0); // 指派一个绿色
imagecolortransparent($thumbImg, $background_color); // 设置为透明色,若注释掉该行则输出绿色的图
}
// 对jpeg图形设置隔行扫描
if ('jpg' == $type || 'jpeg' == $type)
imageinterlace($thumbImg, $interlace);
//$gray=ImageColorAllocate($thumbImg,255,0,0);
//ImageString($thumbImg,2,5,5,"ThinkPHP",$gray);
// 生成图片
$imageFun = 'image' . ($type == 'jpg' ? 'jpeg' : $type);
$imageFun($thumbImg, $thumbname);
imagedestroy($thumbImg);
imagedestroy($srcImg);
return $thumbname;
}
return false;
}
/**
+----------------------------------------------------------
* 根据给定的字符串生成图像
+----------------------------------------------------------
* @static
* @access public
+----------------------------------------------------------
* @param string $string 字符串
* @param string $size 图像大小 width,height 或者 array(width,height)
* @param string $font 字体信息 fontface,fontsize 或者 array(fontface,fontsize)
* @param string $type 图像格式 默认PNG
* @param integer $disturb 是否干扰 1 点干扰 2 线干扰 3 复合干扰 0 无干扰
* @param bool $border 是否加边框 array(color)
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
static function buildString($string, $rgb=array(), $filename='', $type='png', $disturb=1, $border=true) {
if (is_string($size))
$size = explode(',', $size);
$width = $size[0];
$height = $size[1];
if (is_string($font))
$font = explode(',', $font);
$fontface = $font[0];
$fontsize = $font[1];
$length = strlen($string);
$width = ($length * 9 + 10) > $width ? $length * 9 + 10 : $width;
$height = 22;
if ($type != 'gif' && function_exists('imagecreatetruecolor')) {
$im = @imagecreatetruecolor($width, $height);
} else {
$im = @imagecreate($width, $height);
}
if (empty($rgb)) {
$color = imagecolorallocate($im, 102, 104, 104);
} else {
$color = imagecolorallocate($im, $rgb[0], $rgb[1], $rgb[2]);
}
$backColor = imagecolorallocate($im, 255, 255, 255); //背景色(随机)
$borderColor = imagecolorallocate($im, 100, 100, 100); //边框色
$pointColor = imagecolorallocate($im, mt_rand(0, 255), mt_rand(0, 255), mt_rand(0, 255)); //点颜色
@imagefilledrectangle($im, 0, 0, $width - 1, $height - 1, $backColor);
@imagerectangle($im, 0, 0, $width - 1, $height - 1, $borderColor);
@imagestring($im, 5, 5, 3, $string, $color);
if (!empty($disturb)) {
// 添加干扰
if ($disturb = 1 || $disturb = 3) {
for ($i = 0; $i < 25; $i++) {
imagesetpixel($im, mt_rand(0, $width), mt_rand(0, $height), $pointColor);
}
} elseif ($disturb = 2 || $disturb = 3) {
for ($i = 0; $i < 10; $i++) {
imagearc($im, mt_rand(-10, $width), mt_rand(-10, $height), mt_rand(30, 300), mt_rand(20, 200), 55, 44, $pointColor);
}
}
}
Image::output($im, $type, $filename);
}
/**
+----------------------------------------------------------
* 生成图像验证码
+----------------------------------------------------------
* @static
* @access public
+----------------------------------------------------------
* @param string $length 位数
* @param string $mode 类型
* @param string $type 图像格式
* @param string $width 宽度
* @param string $height 高度
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
static function buildImageVerify($length=4, $mode=1, $type='png', $width=48, $height=22, $verifyName='verify') {
import('ORG.Util.String');
$randval = String::rand_string($length, $mode);
$_SESSION[$verifyName] = md5($randval);
$width = ($length * 10 + 10) > $width ? $length * 10 + 10 : $width;
if ($type != 'gif' && function_exists('imagecreatetruecolor')) {
$im = @imagecreatetruecolor($width, $height);
} else {
$im = @imagecreate($width, $height);
}
$r = Array(225, 255, 255, 223);
$g = Array(225, 236, 237, 255);
$b = Array(225, 236, 166, 125);
$key = mt_rand(0, 3);
$backColor = imagecolorallocate($im, $r[$key], $g[$key], $b[$key]); //背景色(随机)
$borderColor = imagecolorallocate($im, 100, 100, 100); //边框色
$pointColor = imagecolorallocate($im, mt_rand(0, 255), mt_rand(0, 255), mt_rand(0, 255)); //点颜色
@imagefilledrectangle($im, 0, 0, $width - 1, $height - 1, $backColor);
@imagerectangle($im, 0, 0, $width - 1, $height - 1, $borderColor);
$stringColor = imagecolorallocate($im, mt_rand(0, 200), mt_rand(0, 120), mt_rand(0, 120));
// 干扰
for ($i = 0; $i < 10; $i++) {
$fontcolor = imagecolorallocate($im, mt_rand(0, 255), mt_rand(0, 255), mt_rand(0, 255));
imagearc($im, mt_rand(-10, $width), mt_rand(-10, $height), mt_rand(30, 300), mt_rand(20, 200), 55, 44, $fontcolor);
}
for ($i = 0; $i < 25; $i++) {
$fontcolor = imagecolorallocate($im, mt_rand(0, 255), mt_rand(0, 255), mt_rand(0, 255));
imagesetpixel($im, mt_rand(0, $width), mt_rand(0, $height), $pointColor);
}
for ($i = 0; $i < $length; $i++) {
imagestring($im, 5, $i * 10 + 5, mt_rand(1, 8), $randval{$i}, $stringColor);
}
// @imagestring($im, 5, 5, 3, $randval, $stringColor);
Image::output($im, $type);
}
// 中文验证码
static function GBVerify($length=4, $type='png', $width=180, $height=50, $fontface='simhei.ttf', $verifyName='verify') {
import('ORG.Util.String');
$code = String::rand_string($length, 4);
$width = ($length * 45) > $width ? $length * 45 : $width;
$_SESSION[$verifyName] = md5($code);
$im = imagecreatetruecolor($width, $height);
$borderColor = imagecolorallocate($im, 100, 100, 100); //边框色
$bkcolor = imagecolorallocate($im, 250, 250, 250);
imagefill($im, 0, 0, $bkcolor);
@imagerectangle($im, 0, 0, $width - 1, $height - 1, $borderColor);
// 干扰
for ($i = 0; $i < 15; $i++) {
$fontcolor = imagecolorallocate($im, mt_rand(0, 255), mt_rand(0, 255), mt_rand(0, 255));
imagearc($im, mt_rand(-10, $width), mt_rand(-10, $height), mt_rand(30, 300), mt_rand(20, 200), 55, 44, $fontcolor);
}
for ($i = 0; $i < 255; $i++) {
$fontcolor = imagecolorallocate($im, mt_rand(0, 255), mt_rand(0, 255), mt_rand(0, 255));
imagesetpixel($im, mt_rand(0, $width), mt_rand(0, $height), $fontcolor);
}
if (!is_file($fontface)) {
$fontface = dirname(__FILE__) . "/" . $fontface;
}
for ($i = 0; $i < $length; $i++) {
$fontcolor = imagecolorallocate($im, mt_rand(0, 120), mt_rand(0, 120), mt_rand(0, 120)); //这样保证随机出来的颜色较深。
$codex = msubstr($code, $i, 1);
imagettftext($im, mt_rand(16, 20), mt_rand(-60, 60), 40 * $i + 20, mt_rand(30, 35), $fontcolor, $fontface, $codex);
}
Image::output($im, $type);
}
/**
+----------------------------------------------------------
* 把图像转换成字符显示
+----------------------------------------------------------
* @static
* @access public
+----------------------------------------------------------
* @param string $image 要显示的图像
* @param string $type 图像类型,默认自动获取
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
static function showASCIIImg($image, $string='', $type='') {
$info = Image::getImageInfo($image);
if ($info !== false) {
$type = empty($type) ? $info['type'] : $type;
unset($info);
// 载入原图
$createFun = 'ImageCreateFrom' . ($type == 'jpg' ? 'jpeg' : $type);
$im = $createFun($image);
$dx = imagesx($im);
$dy = imagesy($im);
$i = 0;
$out = '<span style="padding:0px;margin:0;line-height:100%;font-size:1px;">';
set_time_limit(0);
for ($y = 0; $y < $dy; $y++) {
for ($x = 0; $x < $dx; $x++) {
$col = imagecolorat($im, $x, $y);
$rgb = imagecolorsforindex($im, $col);
$str = empty($string) ? '*' : $string[$i++];
$out .= sprintf('<span style="margin:0px;color:#%02x%02x%02x">' . $str . '</span>', $rgb['red'], $rgb['green'], $rgb['blue']);
}
$out .= "<br>\n";
}
$out .= '</span>';
imagedestroy($im);
return $out;
}
return false;
}
/**
+----------------------------------------------------------
* 生成高级图像验证码
+----------------------------------------------------------
* @static
* @access public
+----------------------------------------------------------
* @param string $type 图像格式
* @param string $width 宽度
* @param string $height 高度
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
static function showAdvVerify($type='png', $width=180, $height=40, $verifyName='verifyCode') {
$rand = range('a', 'z');
shuffle($rand);
$verifyCode = array_slice($rand, 0, 10);
$letter = implode(" ", $verifyCode);
$_SESSION[$verifyName] = $verifyCode;
$im = imagecreate($width, $height);
$r = array(225, 255, 255, 223);
$g = array(225, 236, 237, 255);
$b = array(225, 236, 166, 125);
$key = mt_rand(0, 3);
$backColor = imagecolorallocate($im, $r[$key], $g[$key], $b[$key]);
$borderColor = imagecolorallocate($im, 100, 100, 100); //边框色
imagefilledrectangle($im, 0, 0, $width - 1, $height - 1, $backColor);
imagerectangle($im, 0, 0, $width - 1, $height - 1, $borderColor);
$numberColor = imagecolorallocate($im, 255, rand(0, 100), rand(0, 100));
$stringColor = imagecolorallocate($im, rand(0, 100), rand(0, 100), 255);
// 添加干扰
/*
for($i=0;$i<10;$i++){
$fontcolor=imagecolorallocate($im,mt_rand(0,255),mt_rand(0,255),mt_rand(0,255));
imagearc($im,mt_rand(-10,$width),mt_rand(-10,$height),mt_rand(30,300),mt_rand(20,200),55,44,$fontcolor);
}
for($i=0;$i<255;$i++){
$fontcolor=imagecolorallocate($im,mt_rand(0,255),mt_rand(0,255),mt_rand(0,255));
imagesetpixel($im,mt_rand(0,$width),mt_rand(0,$height),$fontcolor);
} */
imagestring($im, 5, 5, 1, "0 1 2 3 4 5 6 7 8 9", $numberColor);
imagestring($im, 5, 5, 20, $letter, $stringColor);
Image::output($im, $type);
}
/**
+----------------------------------------------------------
* 生成UPC-A条形码
+----------------------------------------------------------
* @static
+----------------------------------------------------------
* @param string $type 图像格式
* @param string $type 图像格式
* @param string $lw 单元宽度
* @param string $hi 条码高度
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
static function UPCA($code, $type='png', $lw=2, $hi=100) {
static $Lencode = array('0001101', '0011001', '0010011', '0111101', '0100011',
'0110001', '0101111', '0111011', '0110111', '0001011');
static $Rencode = array('1110010', '1100110', '1101100', '1000010', '1011100',
'1001110', '1010000', '1000100', '1001000', '1110100');
$ends = '101';
$center = '01010';
/* UPC-A Must be 11 digits, we compute the checksum. */
if (strlen($code) != 11) {
die("UPC-A Must be 11 digits.");
}
/* Compute the EAN-13 Checksum digit */
$ncode = '0' . $code;
$even = 0;
$odd = 0;
for ($x = 0; $x < 12; $x++) {
if ($x % 2) {
$odd += $ncode[$x];
} else {
$even += $ncode[$x];
}
}
$code.= ( 10 - (($odd * 3 + $even) % 10)) % 10;
/* Create the bar encoding using a binary string */
$bars = $ends;
$bars.=$Lencode[$code[0]];
for ($x = 1; $x < 6; $x++) {
$bars.=$Lencode[$code[$x]];
}
$bars.=$center;
for ($x = 6; $x < 12; $x++) {
$bars.=$Rencode[$code[$x]];
}
$bars.=$ends;
/* Generate the Barcode Image */
if ($type != 'gif' && function_exists('imagecreatetruecolor')) {
$im = imagecreatetruecolor($lw * 95 + 30, $hi + 30);
} else {
$im = imagecreate($lw * 95 + 30, $hi + 30);
}
$fg = ImageColorAllocate($im, 0, 0, 0);
$bg = ImageColorAllocate($im, 255, 255, 255);
ImageFilledRectangle($im, 0, 0, $lw * 95 + 30, $hi + 30, $bg);
$shift = 10;
for ($x = 0; $x < strlen($bars); $x++) {
if (($x < 10) || ($x >= 45 && $x < 50) || ($x >= 85)) {
$sh = 10;
} else {
$sh = 0;
}
if ($bars[$x] == '1') {
$color = $fg;
} else {
$color = $bg;
}
ImageFilledRectangle($im, ($x * $lw) + 15, 5, ($x + 1) * $lw + 14, $hi + 5 + $sh, $color);
}
/* Add the Human Readable Label */
ImageString($im, 4, 5, $hi - 5, $code[0], $fg);
for ($x = 0; $x < 5; $x++) {
ImageString($im, 5, $lw * (13 + $x * 6) + 15, $hi + 5, $code[$x + 1], $fg);
ImageString($im, 5, $lw * (53 + $x * 6) + 15, $hi + 5, $code[$x + 6], $fg);
}
ImageString($im, 4, $lw * 95 + 17, $hi - 5, $code[11], $fg);
/* Output the Header and Content. */
Image::output($im, $type);
}
static function output($im, $type='png', $filename='') {
header("Content-type: image/" . $type);
$ImageFun = 'image' . $type;
if (empty($filename)) {
$ImageFun($im);
} else {
$ImageFun($im, $filename);
}
imagedestroy($im);
}
}
//类定义结束
?> | 0321hy | trunk/Lib/ThinkPHP/Lib/ORG/Util/Image.class.php | PHP | asf20 | 26,745 |
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2009 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
// $Id$
class String extends Think
{
/**
+----------------------------------------------------------
* 生成UUID 单机使用
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
static public function uuid()
{
$charid = md5(uniqid(mt_rand(), true));
$hyphen = chr(45);// "-"
$uuid = chr(123)// "{"
.substr($charid, 0, 8).$hyphen
.substr($charid, 8, 4).$hyphen
.substr($charid,12, 4).$hyphen
.substr($charid,16, 4).$hyphen
.substr($charid,20,12)
.chr(125);// "}"
return $uuid;
}
/**
+----------------------------------------------------------
* 生成Guid主键
+----------------------------------------------------------
* @return Boolean
+----------------------------------------------------------
*/
static public function keyGen() {
return str_replace('-','',substr(String::uuid(),1,-1));
}
/**
+----------------------------------------------------------
* 检查字符串是否是UTF8编码
+----------------------------------------------------------
* @param string $string 字符串
+----------------------------------------------------------
* @return Boolean
+----------------------------------------------------------
*/
static public function is_utf8($str) {
$c=0; $b=0;
$bits=0;
$len=strlen($str);
for($i=0; $i<$len; $i++){
$c=ord($str[$i]);
if($c > 128){
if(($c >= 254)) return false;
elseif($c >= 252) $bits=6;
elseif($c >= 248) $bits=5;
elseif($c >= 240) $bits=4;
elseif($c >= 224) $bits=3;
elseif($c >= 192) $bits=2;
else return false;
if(($i+$bits) > $len) return false;
while($bits > 1){
$i++;
$b=ord($str[$i]);
if($b < 128 || $b > 191) return false;
$bits--;
}
}
}
return true;
}
/**
+----------------------------------------------------------
* 字符串截取,支持中文和其他编码
+----------------------------------------------------------
* @static
* @access public
+----------------------------------------------------------
* @param string $str 需要转换的字符串
* @param string $start 开始位置
* @param string $length 截取长度
* @param string $charset 编码格式
* @param string $suffix 截断显示字符
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
static public function msubstr($str, $start=0, $length, $charset="utf-8", $suffix=true)
{
if(function_exists("mb_substr"))
return mb_substr($str, $start, $length, $charset);
elseif(function_exists('iconv_substr')) {
return iconv_substr($str,$start,$length,$charset);
}
$re['utf-8'] = "/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xff][\x80-\xbf]{3}/";
$re['gb2312'] = "/[\x01-\x7f]|[\xb0-\xf7][\xa0-\xfe]/";
$re['gbk'] = "/[\x01-\x7f]|[\x81-\xfe][\x40-\xfe]/";
$re['big5'] = "/[\x01-\x7f]|[\x81-\xfe]([\x40-\x7e]|\xa1-\xfe])/";
preg_match_all($re[$charset], $str, $match);
$slice = join("",array_slice($match[0], $start, $length));
if($suffix) return $slice."…";
return $slice;
}
/**
+----------------------------------------------------------
* 产生随机字串,可用来自动生成密码
* 默认长度6位 字母和数字混合 支持中文
+----------------------------------------------------------
* @param string $len 长度
* @param string $type 字串类型
* 0 字母 1 数字 其它 混合
* @param string $addChars 额外字符
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
static public function rand_string($len=6,$type='',$addChars='') {
$str ='';
switch($type) {
case 0:
$chars='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.$addChars;
break;
case 1:
$chars= str_repeat('0123456789',3);
break;
case 2:
$chars='ABCDEFGHIJKLMNOPQRSTUVWXYZ'.$addChars;
break;
case 3:
$chars='abcdefghijklmnopqrstuvwxyz'.$addChars;
break;
case 4:
$chars = "们以我到他会作时要动国产的一是工就年阶义发成部民可出能方进在了不和有大这主中人上为来分生对于学下级地个用同行面说种过命度革而多子后自社加小机也经力线本电高量长党得实家定深法表着水理化争现所二起政三好十战无农使性前等反体合斗路图把结第里正新开论之物从当两些还天资事队批点育重其思与间内去因件日利相由压员气业代全组数果期导平各基或月毛然如应形想制心样干都向变关问比展那它最及外没看治提五解系林者米群头意只明四道马认次文通但条较克又公孔领军流入接席位情运器并飞原油放立题质指建区验活众很教决特此常石强极土少已根共直团统式转别造切九你取西持总料连任志观调七么山程百报更见必真保热委手改管处己将修支识病象几先老光专什六型具示复安带每东增则完风回南广劳轮科北打积车计给节做务被整联步类集号列温装即毫知轴研单色坚据速防史拉世设达尔场织历花受求传口断况采精金界品判参层止边清至万确究书术状厂须离再目海交权且儿青才证低越际八试规斯近注办布门铁需走议县兵固除般引齿千胜细影济白格效置推空配刀叶率述今选养德话查差半敌始片施响收华觉备名红续均药标记难存测士身紧液派准斤角降维板许破述技消底床田势端感往神便贺村构照容非搞亚磨族火段算适讲按值美态黄易彪服早班麦削信排台声该击素张密害侯草何树肥继右属市严径螺检左页抗苏显苦英快称坏移约巴材省黑武培著河帝仅针怎植京助升王眼她抓含苗副杂普谈围食射源例致酸旧却充足短划剂宣环落首尺波承粉践府鱼随考刻靠够满夫失包住促枝局菌杆周护岩师举曲春元超负砂封换太模贫减阳扬江析亩木言球朝医校古呢稻宋听唯输滑站另卫字鼓刚写刘微略范供阿块某功套友限项余倒卷创律雨让骨远帮初皮播优占死毒圈伟季训控激找叫云互跟裂粮粒母练塞钢顶策双留误础吸阻故寸盾晚丝女散焊功株亲院冷彻弹错散商视艺灭版烈零室轻血倍缺厘泵察绝富城冲喷壤简否柱李望盘磁雄似困巩益洲脱投送奴侧润盖挥距触星松送获兴独官混纪依未突架宽冬章湿偏纹吃执阀矿寨责熟稳夺硬价努翻奇甲预职评读背协损棉侵灰虽矛厚罗泥辟告卵箱掌氧恩爱停曾溶营终纲孟钱待尽俄缩沙退陈讨奋械载胞幼哪剥迫旋征槽倒握担仍呀鲜吧卡粗介钻逐弱脚怕盐末阴丰雾冠丙街莱贝辐肠付吉渗瑞惊顿挤秒悬姆烂森糖圣凹陶词迟蚕亿矩康遵牧遭幅园腔订香肉弟屋敏恢忘编印蜂急拿扩伤飞露核缘游振操央伍域甚迅辉异序免纸夜乡久隶缸夹念兰映沟乙吗儒杀汽磷艰晶插埃燃欢铁补咱芽永瓦倾阵碳演威附牙芽永瓦斜灌欧献顺猪洋腐请透司危括脉宜笑若尾束壮暴企菜穗楚汉愈绿拖牛份染既秋遍锻玉夏疗尖殖井费州访吹荣铜沿替滚客召旱悟刺脑措贯藏敢令隙炉壳硫煤迎铸粘探临薄旬善福纵择礼愿伏残雷延烟句纯渐耕跑泽慢栽鲁赤繁境潮横掉锥希池败船假亮谓托伙哲怀割摆贡呈劲财仪沉炼麻罪祖息车穿货销齐鼠抽画饲龙库守筑房歌寒喜哥洗蚀废纳腹乎录镜妇恶脂庄擦险赞钟摇典柄辩竹谷卖乱虚桥奥伯赶垂途额壁网截野遗静谋弄挂课镇妄盛耐援扎虑键归符庆聚绕摩忙舞遇索顾胶羊湖钉仁音迹碎伸灯避泛亡答勇频皇柳哈揭甘诺概宪浓岛袭谁洪谢炮浇斑讯懂灵蛋闭孩释乳巨徒私银伊景坦累匀霉杜乐勒隔弯绩招绍胡呼痛峰零柴簧午跳居尚丁秦稍追梁折耗碱殊岗挖氏刃剧堆赫荷胸衡勤膜篇登驻案刊秧缓凸役剪川雪链渔啦脸户洛孢勃盟买杨宗焦赛旗滤硅炭股坐蒸凝竟陷枪黎救冒暗洞犯筒您宋弧爆谬涂味津臂障褐陆啊健尊豆拔莫抵桑坡缝警挑污冰柬嘴啥饭塑寄赵喊垫丹渡耳刨虎笔稀昆浪萨茶滴浅拥穴覆伦娘吨浸袖珠雌妈紫戏塔锤震岁貌洁剖牢锋疑霸闪埔猛诉刷狠忽灾闹乔唐漏闻沈熔氯荒茎男凡抢像浆旁玻亦忠唱蒙予纷捕锁尤乘乌智淡允叛畜俘摸锈扫毕璃宝芯爷鉴秘净蒋钙肩腾枯抛轨堂拌爸循诱祝励肯酒绳穷塘燥泡袋朗喂铝软渠颗惯贸粪综墙趋彼届墨碍启逆卸航衣孙龄岭骗休借".$addChars;
break;
default :
// 默认去掉了容易混淆的字符oOLl和数字01,要添加请使用addChars参数
$chars='ABCDEFGHIJKMNPQRSTUVWXYZabcdefghijkmnpqrstuvwxyz23456789'.$addChars;
break;
}
if($len>10 ) {//位数过长重复字符串一定次数
$chars= $type==1? str_repeat($chars,$len) : str_repeat($chars,5);
}
if($type!=4) {
$chars = str_shuffle($chars);
$str = substr($chars,0,$len);
}else{
// 中文随机字
for($i=0;$i<$len;$i++){
$str.= self::msubstr($chars, floor(mt_rand(0,mb_strlen($chars,'utf-8')-1)),1);
}
}
return $str;
}
/**
+----------------------------------------------------------
* 生成一定数量的随机数,并且不重复
+----------------------------------------------------------
* @param integer $number 数量
* @param string $len 长度
* @param string $type 字串类型
* 0 字母 1 数字 其它 混合
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
static public function build_count_rand ($number,$length=4,$mode=1) {
if($mode==1 && $length<strlen($number) ) {
//不足以生成一定数量的不重复数字
return false;
}
$rand = array();
for($i=0; $i<$number; $i++) {
$rand[] = rand_string($length,$mode);
}
$unqiue = array_unique($rand);
if(count($unqiue)==count($rand)) {
return $rand;
}
$count = count($rand)-count($unqiue);
for($i=0; $i<$count*3; $i++) {
$rand[] = rand_string($length,$mode);
}
$rand = array_slice(array_unique ($rand),0,$number);
return $rand;
}
/**
+----------------------------------------------------------
* 带格式生成随机字符 支持批量生成
* 但可能存在重复
+----------------------------------------------------------
* @param string $format 字符格式
* # 表示数字 * 表示字母和数字 $ 表示字母
* @param integer $number 生成数量
+----------------------------------------------------------
* @return string | array
+----------------------------------------------------------
*/
static public function build_format_rand($format,$number=1)
{
$str = array();
$length = strlen($format);
for($j=0; $j<$number; $j++) {
$strtemp = '';
for($i=0; $i<$length; $i++) {
$char = substr($format,$i,1);
switch($char){
case "*"://字母和数字混合
$strtemp .= String::rand_string(1);
break;
case "#"://数字
$strtemp .= String::rand_string(1,1);
break;
case "$"://大写字母
$strtemp .= String::rand_string(1,2);
break;
default://其他格式均不转换
$strtemp .= $char;
break;
}
}
$str[] = $strtemp;
}
return $number==1? $strtemp : $str ;
}
/**
+----------------------------------------------------------
* 获取一定范围内的随机数字 位数不足补零
+----------------------------------------------------------
* @param integer $min 最小值
* @param integer $max 最大值
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
static public function rand_number ($min, $max) {
return sprintf("%0".strlen($max)."d", mt_rand($min,$max));
}
}
?> | 0321hy | trunk/Lib/ThinkPHP/Lib/ORG/Util/String.class.php | PHP | asf20 | 13,133 |
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2009 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
// $Id$
/**
+------------------------------------------------------------------------------
* DirectoryIterator实现类 PHP5以上内置了DirectoryIterator类
+------------------------------------------------------------------------------
* @category ORG
* @package ORG
* @subpackage Io
* @author liu21st <liu21st@gmail.com>
* @version $Id$
+------------------------------------------------------------------------------
*/
class Dir extends Think implements IteratorAggregate
{//类定义开始
private $_values = array();
/**
+----------------------------------------------------------
* 架构函数
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $path 目录路径
+----------------------------------------------------------
*/
function __construct($path,$pattern='*')
{
if(substr($path, -1) != "/") $path .= "/";
$this->listFile($path,$pattern);
}
/**
+----------------------------------------------------------
* 取得目录下面的文件信息
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param mixed $pathname 路径
+----------------------------------------------------------
*/
function listFile($pathname,$pattern='*')
{
static $_listDirs = array();
$guid = md5($pathname.$pattern);
if(!isset($_listDirs[$guid])){
$dir = array();
$list = glob($pathname.$pattern);
foreach ($list as $i=>$file){
$dir[$i]['filename'] = basename($file);
$dir[$i]['pathname'] = realpath($file);
$dir[$i]['owner'] = fileowner($file);
$dir[$i]['perms'] = fileperms($file);
$dir[$i]['inode'] = fileinode($file);
$dir[$i]['group'] = filegroup($file);
$dir[$i]['path'] = dirname($file);
$dir[$i]['atime'] = fileatime($file);
$dir[$i]['ctime'] = filectime($file);
$dir[$i]['size'] = filesize($file);
$dir[$i]['type'] = filetype($file);
$dir[$i]['ext'] = is_file($file)?strtolower(substr(strrchr(basename($file), '.'),1)):'';
$dir[$i]['mtime'] = filemtime($file);
$dir[$i]['isDir'] = is_dir($file);
$dir[$i]['isFile'] = is_file($file);
$dir[$i]['isLink'] = is_link($file);
//$dir[$i]['isExecutable']= function_exists('is_executable')?is_executable($file):'';
$dir[$i]['isReadable'] = is_readable($file);
$dir[$i]['isWritable'] = is_writable($file);
}
$cmp_func = create_function('$a,$b','
$k = "isDir";
if($a[$k] == $b[$k]) return 0;
return $a[$k]>$b[$k]?-1:1;
');
// 对结果排序 保证目录在前面
usort($dir,$cmp_func);
$this->_values = $dir;
$_listDirs[$guid] = $dir;
}else{
$this->_values = $_listDirs[$guid];
}
}
/**
+----------------------------------------------------------
* 文件上次访问时间
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @return integer
+----------------------------------------------------------
*/
function getATime()
{
$current = current($this->_values);
return $current['atime'];
}
/**
+----------------------------------------------------------
* 取得文件的 inode 修改时间
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @return integer
+----------------------------------------------------------
*/
function getCTime()
{
$current = current($this->_values);
return $current['ctime'];
}
/**
+----------------------------------------------------------
* 遍历子目录文件信息
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @return DirectoryIterator
+----------------------------------------------------------
*/
function getChildren()
{
$current = current($this->_values);
if($current['isDir']){
return new Dir($current['pathname']);
}
return false;
}
/**
+----------------------------------------------------------
* 取得文件名
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
function getFilename()
{
$current = current($this->_values);
return $current['filename'];
}
/**
+----------------------------------------------------------
* 取得文件的组
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @return integer
+----------------------------------------------------------
*/
function getGroup()
{
$current = current($this->_values);
return $current['group'];
}
/**
+----------------------------------------------------------
* 取得文件的 inode
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @return integer
+----------------------------------------------------------
*/
function getInode()
{
$current = current($this->_values);
return $current['inode'];
}
/**
+----------------------------------------------------------
* 取得文件的上次修改时间
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @return integer
+----------------------------------------------------------
*/
function getMTime()
{
$current = current($this->_values);
return $current['mtime'];
}
/**
+----------------------------------------------------------
* 取得文件的所有者
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
function getOwner()
{
$current = current($this->_values);
return $current['owner'];
}
/**
+----------------------------------------------------------
* 取得文件路径,不包括文件名
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
function getPath()
{
$current = current($this->_values);
return $current['path'];
}
/**
+----------------------------------------------------------
* 取得文件的完整路径,包括文件名
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
function getPathname()
{
$current = current($this->_values);
return $current['pathname'];
}
/**
+----------------------------------------------------------
* 取得文件的权限
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @return integer
+----------------------------------------------------------
*/
function getPerms()
{
$current = current($this->_values);
return $current['perms'];
}
/**
+----------------------------------------------------------
* 取得文件的大小
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @return integer
+----------------------------------------------------------
*/
function getSize()
{
$current = current($this->_values);
return $current['size'];
}
/**
+----------------------------------------------------------
* 取得文件类型
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
function getType()
{
$current = current($this->_values);
return $current['type'];
}
/**
+----------------------------------------------------------
* 是否为目录
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @return boolen
+----------------------------------------------------------
*/
function isDir()
{
$current = current($this->_values);
return $current['isDir'];
}
/**
+----------------------------------------------------------
* 是否为文件
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @return boolen
+----------------------------------------------------------
*/
function isFile()
{
$current = current($this->_values);
return $current['isFile'];
}
/**
+----------------------------------------------------------
* 文件是否为一个符号连接
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @return boolen
+----------------------------------------------------------
*/
function isLink()
{
$current = current($this->_values);
return $current['isLink'];
}
/**
+----------------------------------------------------------
* 文件是否可以执行
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @return boolen
+----------------------------------------------------------
*/
function isExecutable()
{
$current = current($this->_values);
return $current['isExecutable'];
}
/**
+----------------------------------------------------------
* 文件是否可读
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @return boolen
+----------------------------------------------------------
*/
function isReadable()
{
$current = current($this->_values);
return $current['isReadable'];
}
/**
+----------------------------------------------------------
* 获取foreach的遍历方式
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
function getIterator()
{
return new ArrayObject($this->_values);
}
// 返回目录的数组信息
function toArray() {
return $this->_values;
}
// 静态方法
/**
+----------------------------------------------------------
* 判断目录是否为空
+----------------------------------------------------------
* @access static
+----------------------------------------------------------
* @return void
+----------------------------------------------------------
*/
function isEmpty($directory)
{
$handle = opendir($directory);
while (($file = readdir($handle)) !== false)
{
if ($file != "." && $file != "..")
{
closedir($handle);
return false;
}
}
closedir($handle);
return true;
}
/**
+----------------------------------------------------------
* 取得目录中的结构信息
+----------------------------------------------------------
* @access static
+----------------------------------------------------------
* @return void
+----------------------------------------------------------
*/
function getList($directory)
{
return scandir($directory);
}
/**
+----------------------------------------------------------
* 删除目录(包括下面的文件)
+----------------------------------------------------------
* @access static
+----------------------------------------------------------
* @return void
+----------------------------------------------------------
*/
function delDir($directory,$subdir=true)
{
if (is_dir($directory) == false)
{
exit("The Directory Is Not Exist!");
}
$handle = opendir($directory);
while (($file = readdir($handle)) !== false)
{
if ($file != "." && $file != "..")
{
is_dir("$directory/$file")?
Dir::delDir("$directory/$file"):
unlink("$directory/$file");
}
}
if (readdir($handle) == false)
{
closedir($handle);
rmdir($directory);
}
}
/**
+----------------------------------------------------------
* 删除目录下面的所有文件,但不删除目录
+----------------------------------------------------------
* @access static
+----------------------------------------------------------
* @return void
+----------------------------------------------------------
*/
function del($directory)
{
if (is_dir($directory) == false)
{
exit("The Directory Is Not Exist!");
}
$handle = opendir($directory);
while (($file = readdir($handle)) !== false)
{
if ($file != "." && $file != ".." && is_file("$directory/$file"))
{
unlink("$directory/$file");
}
}
closedir($handle);
}
/**
+----------------------------------------------------------
* 复制目录
+----------------------------------------------------------
* @access static
+----------------------------------------------------------
* @return void
+----------------------------------------------------------
*/
function copyDir($source, $destination)
{
if (is_dir($source) == false)
{
exit("The Source Directory Is Not Exist!");
}
if (is_dir($destination) == false)
{
mkdir($destination, 0700);
}
$handle=opendir($source);
while (false !== ($file = readdir($handle)))
{
if ($file != "." && $file != "..")
{
is_dir("$source/$file")?
Dir::copyDir("$source/$file", "$destination/$file"):
copy("$source/$file", "$destination/$file");
}
}
closedir($handle);
}
}//类定义结束
if(!class_exists('DirectoryIterator')) {
class DirectoryIterator extends Dir {}
}
?> | 0321hy | trunk/Lib/ThinkPHP/Lib/ORG/Io/Dir.class.php | PHP | asf20 | 15,583 |
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2010 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
// $Id: ThinkPHP.php 1829 2010-10-18 08:15:58Z liu21st $
/**
+------------------------------------------------------------------------------
* ThinkPHP公共文件
+------------------------------------------------------------------------------
*/
// 记录和统计时间(微秒)
function G($start,$end='',$dec=3) {
static $_info = array();
if(!empty($end)) { // 统计时间
if(!isset($_info[$end])) {
$_info[$end] = microtime(TRUE);
}
return number_format(($_info[$end]-$_info[$start]),$dec);
}else{ // 记录时间
$_info[$start] = microtime(TRUE);
}
}
//记录开始运行时间
G('beginTime');
if(!defined('APP_PATH')) define('APP_PATH', dirname($_SERVER['SCRIPT_FILENAME']));
if(!defined('RUNTIME_PATH')) define('RUNTIME_PATH',APP_PATH.'/Runtime/');
if(!defined('APP_CACHE_NAME')) define('APP_CACHE_NAME','app');// 指定缓存名称
if(defined('RUNTIME_ALLINONE') && is_file(RUNTIME_PATH.'~allinone.php')) {
// ALLINONE 模式直接载入allinone缓存
$result = require RUNTIME_PATH.'~allinone.php';
C($result);
// 自动设置为运行模式
define('RUNTIME_MODEL',true);
}else{
if(version_compare(PHP_VERSION,'5.0.0','<')) die('require PHP > 5.0 !');
// ThinkPHP系统目录定义
if(!defined('THINK_PATH')) define('THINK_PATH', dirname(__FILE__));
if(!defined('APP_NAME')) define('APP_NAME', basename(dirname($_SERVER['SCRIPT_FILENAME'])));
$runtime = defined('THINK_MODE')?'~'.strtolower(THINK_MODE).'_runtime.php':'~runtime.php';
if(is_file(RUNTIME_PATH.$runtime)) {
// 加载框架核心编译缓存
require RUNTIME_PATH.$runtime;
}else{
// 加载编译函数文件
require THINK_PATH."/Common/runtime.php";
// 生成核心编译~runtime缓存
build_runtime();
}
}
// 记录加载文件时间
G('loadTime');
?> | 0321hy | trunk/Lib/ThinkPHP/ThinkPHP.php | PHP | asf20 | 2,554 |
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2010 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
// $Id$
// 导入别名定义
alias_import(array(
'Model' => THINK_PATH.'/Lib/Think/Core/Model.class.php',
'Dispatcher' => THINK_PATH.'/Lib/Think/Util/Dispatcher.class.php',
'HtmlCache' => THINK_PATH.'/Lib/Think/Util/HtmlCache.class.php',
'Db' => THINK_PATH.'/Lib/Think/Db/Db.class.php',
'ThinkTemplate' => THINK_PATH.'/Lib/Think/Template/ThinkTemplate.class.php',
'Template' => THINK_PATH.'/Lib/Think/Util/Template.class.php',
'TagLib' => THINK_PATH.'/Lib/Think/Template/TagLib.class.php',
'Cache' => THINK_PATH.'/Lib/Think/Util/Cache.class.php',
'Debug' => THINK_PATH.'/Lib/Think/Util/Debug.class.php',
'Session' => THINK_PATH.'/Lib/Think/Util/Session.class.php',
'TagLibCx' => THINK_PATH.'/Lib/Think/Template/TagLib/TagLibCx.class.php',
'TagLibHtml' => THINK_PATH.'/Lib/Think/Template/TagLib/TagLibHtml.class.php',
'ViewModel' => THINK_PATH.'/Lib/Think/Core/Model/ViewModel.class.php',
'AdvModel' => THINK_PATH.'/Lib/Think/Core/Model/AdvModel.class.php',
'RelationModel' => THINK_PATH.'/Lib/Think/Core/Model/RelationModel.class.php',
)
);
?> | 0321hy | trunk/Lib/ThinkPHP/Common/alias.php | PHP | asf20 | 1,809 |
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2010 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
// $Id$
/**
+------------------------------------------------------------------------------
* Think公共函数库
+------------------------------------------------------------------------------
* @category Think
* @package Common
* @author liu21st <liu21st@gmail.com>
* @version $Id$
+------------------------------------------------------------------------------
*/
// 设置和获取统计数据
function N($key, $step=0) {
static $_num = array();
if (!isset($_num[$key])) {
$_num[$key] = 0;
}
if (empty($step))
return $_num[$key];
else
$_num[$key] = $_num[$key] + (int) $step;
}
// URL组装 支持不同模式和路由
function U($url, $params=array(), $redirect=false, $suffix=true) {
if (0 === strpos($url, '/'))
$url = substr($url, 1);
if (!strpos($url, '://')) // 没有指定项目名 使用当前项目名
$url = APP_NAME . '://' . $url;
if (stripos($url, '@?')) { // 给路由传递参数
$url = str_replace('@?', '@think?', $url);
} elseif (stripos($url, '@')) { // 没有参数的路由
$url = $url . MODULE_NAME;
}
// 分析URL地址
$array = parse_url($url);
$app = isset($array['scheme']) ? $array['scheme'] : APP_NAME;
$route = isset($array['user']) ? $array['user'] : '';
if (defined('GROUP_NAME') && strcasecmp(GROUP_NAME, C('DEFAULT_GROUP')))
$group = GROUP_NAME;
if (isset($array['path'])) {
$action = substr($array['path'], 1);
if (!isset($array['host'])) {
// 没有指定模块名
$module = MODULE_NAME;
} else {// 指定模块
if (strpos($array['host'], '-')) {
list($group, $module) = explode('-', $array['host']);
} else {
$module = $array['host'];
}
}
} else { // 只指定操作
$module = MODULE_NAME;
$action = $array['host'];
}
if (isset($array['query'])) {
parse_str($array['query'], $query);
$params = array_merge($query, $params);
}
//对二级域名的支持,待完善对*号子域名的支持
if (C('APP_SUB_DOMAIN_DEPLOY')) {
foreach (C('APP_SUB_DOMAIN_RULES') as $key => $rule) {
if (in_array($group . "/", $rule))
$flag = true;
if (in_array($group . "/" . $module, $rule)) {
$flag = true;
unset($module);
}
if (!isset($group) && in_array(GROUP_NAME . "/" . $module, $rule) && in_array($key,array(SUB_DOMAIN,"*")))
unset($module);
if ($flag) {
unset($group);
if ($key != SUB_DOMAIN && $key != "*") {
$sub_domain = $key;
}
break;
}
}
}
if (C('URL_MODEL') > 0) {
$depr = C('URL_PATHINFO_MODEL') == 2 ? C('URL_PATHINFO_DEPR') : '/';
$str = $depr;
foreach ($params as $var => $val)
$str .= $var . $depr . $val . $depr;
$str = substr($str, 0, -1);
$group = isset($group) ? $group . $depr : '';
$module = isset($module) ? $module . $depr : "";
if (!empty($route)) {
$url = str_replace(APP_NAME, $app, __APP__) . '/' . $group . $route . $str;
} else {
$url = str_replace(APP_NAME, $app, __APP__) . '/' . $group . $module . $action . $str;
}
if ($suffix && C('URL_HTML_SUFFIX'))
$url .= C('URL_HTML_SUFFIX');
}else {
$params = http_build_query($params);
$params = !empty($params) ? '&' . $params : '';
if (isset($group)) {
$url = str_replace(APP_NAME, $app, __APP__) . '?' . C('VAR_GROUP') . '=' . $group . '&' . C('VAR_MODULE') . '=' . $module . '&' . C('VAR_ACTION') . '=' . $action . $params;
} else {
$url = str_replace(APP_NAME, $app, __APP__) . '?' . C('VAR_MODULE') . '=' . $module . '&' . C('VAR_ACTION') . '=' . $action . $params;
}
}
if (isset($sub_domain)) {
$domain = str_replace(SUB_DOMAIN, $sub_domain, $_SERVER['HTTP_HOST']);
$url = "http://" . $domain . $url;
}
if ($redirect)
redirect($url);
else
return $url;
}
/**
+----------------------------------------------------------
* 字符串命名风格转换
* type
* =0 将Java风格转换为C的风格
* =1 将C风格转换为Java的风格
+----------------------------------------------------------
* @access protected
+----------------------------------------------------------
* @param string $name 字符串
* @param integer $type 转换类型
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
function parse_name($name, $type=0) {
if ($type) {
return ucfirst(preg_replace("/_([a-zA-Z])/e", "strtoupper('\\1')", $name));
} else {
$name = preg_replace("/[A-Z]/", "_\\0", $name);
return strtolower(trim($name, "_"));
}
}
// 错误输出
function halt($error) {
if (IS_CLI)
exit($error);
$e = array();
if (C('APP_DEBUG')) {
//调试模式下输出错误信息
if (!is_array($error)) {
$trace = debug_backtrace();
$e['message'] = $error;
$e['file'] = $trace[0]['file'];
$e['class'] = $trace[0]['class'];
$e['function'] = $trace[0]['function'];
$e['line'] = $trace[0]['line'];
$traceInfo = '';
$time = date("y-m-d H:i:m");
foreach ($trace as $t) {
$traceInfo .= '[' . $time . '] ' . $t['file'] . ' (' . $t['line'] . ') ';
$traceInfo .= $t['class'] . $t['type'] . $t['function'] . '(';
$traceInfo .= implode(', ', $t['args']);
$traceInfo .=")<br/>";
}
$e['trace'] = $traceInfo;
} else {
$e = $error;
}
// 包含异常页面模板
include C('TMPL_EXCEPTION_FILE');
} else {
//否则定向到错误页面
$error_page = C('ERROR_PAGE');
if (!empty($error_page)) {
redirect($error_page);
} else {
if (C('SHOW_ERROR_MSG'))
$e['message'] = is_array($error) ? $error['message'] : $error;
else
$e['message'] = C('ERROR_MESSAGE');
// 包含异常页面模板
include C('TMPL_EXCEPTION_FILE');
}
}
exit;
}
// URL重定向
function redirect($url, $time=0, $msg='') {
//多行URL地址支持
$url = str_replace(array("\n", "\r"), '', $url);
if (empty($msg))
$msg = "系统将在{$time}秒之后自动跳转到{$url}!";
if (!headers_sent()) {
// redirect
if (0 === $time) {
header("Location: " . $url);
} else {
header("refresh:{$time};url={$url}");
echo($msg);
}
exit();
} else {
$str = "<meta http-equiv='Refresh' content='{$time};URL={$url}'>";
if ($time != 0)
$str .= $msg;
exit($str);
}
}
// 自定义异常处理
function throw_exception($msg, $type='ThinkException', $code=0) {
if (IS_CLI)
exit($msg);
if (class_exists($type, false))
throw new $type($msg, $code, true);
else
halt($msg); // 异常类型不存在则输出错误信息字串
}
// 区间调试开始
function debug_start($label='') {
$GLOBALS[$label]['_beginTime'] = microtime(TRUE);
if (MEMORY_LIMIT_ON)
$GLOBALS[$label]['_beginMem'] = memory_get_usage();
}
// 区间调试结束,显示指定标记到当前位置的调试
function debug_end($label='') {
$GLOBALS[$label]['_endTime'] = microtime(TRUE);
echo '<div style="text-align:center;width:100%">Process ' . $label . ': Times ' . number_format($GLOBALS[$label]['_endTime'] - $GLOBALS[$label]['_beginTime'], 6) . 's ';
if (MEMORY_LIMIT_ON) {
$GLOBALS[$label]['_endMem'] = memory_get_usage();
echo ' Memories ' . number_format(($GLOBALS[$label]['_endMem'] - $GLOBALS[$label]['_beginMem']) / 1024) . ' k';
}
echo '</div>';
}
// 浏览器友好的变量输出
function dump($var, $echo=true, $label=null, $strict=true) {
$label = ($label === null) ? '' : rtrim($label) . ' ';
if (!$strict) {
if (ini_get('html_errors')) {
$output = print_r($var, true);
$output = "<pre>" . $label . htmlspecialchars($output, ENT_QUOTES) . "</pre>";
} else {
$output = $label . print_r($var, true);
}
} else {
ob_start();
var_dump($var);
$output = ob_get_clean();
if (!extension_loaded('xdebug')) {
$output = preg_replace("/\]\=\>\n(\s+)/m", "] => ", $output);
$output = '<pre>' . $label . htmlspecialchars($output, ENT_QUOTES) . '</pre>';
}
}
if ($echo) {
echo($output);
return null;
}else
return $output;
}
// 取得对象实例 支持调用类的静态方法
function get_instance_of($name, $method='', $args=array()) {
static $_instance = array();
$identify = empty($args) ? $name . $method : $name . $method . to_guid_string($args);
if (!isset($_instance[$identify])) {
if (class_exists($name)) {
$o = new $name();
if (method_exists($o, $method)) {
if (!empty($args)) {
$_instance[$identify] = call_user_func_array(array(&$o, $method), $args);
} else {
$_instance[$identify] = $o->$method();
}
}
else
$_instance[$identify] = $o;
}
else
halt(L('_CLASS_NOT_EXIST_') . ':' . $name);
}
return $_instance[$identify];
}
/**
+----------------------------------------------------------
* 系统自动加载ThinkPHP基类库和当前项目的model和Action对象
* 并且支持配置自动加载路径
+----------------------------------------------------------
* @param string $name 对象类名
+----------------------------------------------------------
* @return void
+----------------------------------------------------------
*/
function __autoload($name) {
// 检查是否存在别名定义
if (alias_import($name))
return;
// 自动加载当前项目的Actioon类和Model类
if (substr($name, -5) == "Model") {
require_cache(LIB_PATH . 'Model/' . $name . '.class.php');
} elseif (substr($name, -6) == "Action") {
require_cache(LIB_PATH . 'Action/' . $name . '.class.php');
} else {
// 根据自动加载路径设置进行尝试搜索
if (C('APP_AUTOLOAD_PATH')) {
$paths = explode(',', C('APP_AUTOLOAD_PATH'));
foreach ($paths as $path) {
if (import($path . $name)) {
// 如果加载类成功则返回
return;
}
}
}
}
return;
}
// 优化的require_once
function require_cache($filename) {
static $_importFiles = array();
$filename = realpath($filename);
if (!isset($_importFiles[$filename])) {
if (file_exists_case($filename)) {
require $filename;
$_importFiles[$filename] = true;
} else {
$_importFiles[$filename] = false;
}
}
return $_importFiles[$filename];
}
// 区分大小写的文件存在判断
function file_exists_case($filename) {
if (is_file($filename)) {
if (IS_WIN && C('APP_FILE_CASE')) {
if (basename(realpath($filename)) != basename($filename))
return false;
}
return true;
}
return false;
}
/**
+----------------------------------------------------------
* 导入所需的类库 同java的Import
* 本函数有缓存功能
+----------------------------------------------------------
* @param string $class 类库命名空间字符串
* @param string $baseUrl 起始路径
* @param string $ext 导入的文件扩展名
+----------------------------------------------------------
* @return boolen
+----------------------------------------------------------
*/
function import($class, $baseUrl = '', $ext='.class.php') {
static $_file = array();
static $_class = array();
$class = str_replace(array('.', '#'), array('/', '.'), $class);
if ('' === $baseUrl && false === strpos($class, '/')) {
// 检查别名导入
return alias_import($class);
} //echo('<br>'.$class.$baseUrl);
if (isset($_file[$class . $baseUrl]))
return true;
else
$_file[$class . $baseUrl] = true;
$class_strut = explode("/", $class);
if (empty($baseUrl)) {
if ('@' == $class_strut[0] || APP_NAME == $class_strut[0]) {
//加载当前项目应用类库
$baseUrl = dirname(LIB_PATH);
$class = substr_replace($class, 'Lib/', 0, strlen($class_strut[0]) + 1);
} elseif (in_array(strtolower($class_strut[0]), array('think', 'org', 'com'))) {
//加载ThinkPHP基类库或者公共类库
// think 官方基类库 org 第三方公共类库 com 企业公共类库
$baseUrl = THINK_PATH . '/Lib/';
} else {
// 加载其他项目应用类库
$class = substr_replace($class, '', 0, strlen($class_strut[0]) + 1);
$baseUrl = APP_PATH . '/../' . $class_strut[0] . '/' . LIB_DIR . '/';
}
}
if (substr($baseUrl, -1) != "/")
$baseUrl .= "/";
$classfile = $baseUrl . $class . $ext;
if ($ext == '.class.php' && is_file($classfile)) {
// 冲突检测
$class = basename($classfile, $ext);
if (isset($_class[$class]))
throw_exception(L('_CLASS_CONFLICT_') . ':' . $_class[$class] . ' ' . $classfile);
$_class[$class] = $classfile;
}
//导入目录下的指定类库文件
return require_cache($classfile);
}
/**
+----------------------------------------------------------
* 基于命名空间方式导入函数库
* load('@.Util.Array')
+----------------------------------------------------------
* @param string $name 函数库命名空间字符串
* @param string $baseUrl 起始路径
* @param string $ext 导入的文件扩展名
+----------------------------------------------------------
* @return void
+----------------------------------------------------------
*/
function load($name, $baseUrl='', $ext='.php') {
$name = str_replace(array('.', '#'), array('/', '.'), $name);
if (empty($baseUrl)) {
if (0 === strpos($name, '@/')) {
//加载当前项目函数库
$baseUrl = APP_PATH . '/Common/';
$name = substr($name, 2);
} else {
//加载ThinkPHP 系统函数库
$baseUrl = THINK_PATH . '/Common/';
}
}
if (substr($baseUrl, -1) != "/")
$baseUrl .= "/";
include $baseUrl . $name . $ext;
}
// 快速导入第三方框架类库
// 所有第三方框架的类库文件统一放到 系统的Vendor目录下面
// 并且默认都是以.php后缀导入
function vendor($class, $baseUrl = '', $ext='.php') {
if (empty($baseUrl))
$baseUrl = VENDOR_PATH;
return import($class, $baseUrl, $ext);
}
// 快速定义和导入别名
function alias_import($alias, $classfile='') {
static $_alias = array();
if ('' !== $classfile) {
// 定义别名导入
$_alias[$alias] = $classfile;
return;
}
if (is_string($alias)) {
if (isset($_alias[$alias]))
return require_cache($_alias[$alias]);
}elseif (is_array($alias)) {
foreach ($alias as $key => $val)
$_alias[$key] = $val;
return;
}
return false;
}
/**
+----------------------------------------------------------
* D函数用于实例化Model
+----------------------------------------------------------
* @param string name Model名称
* @param string app Model所在项目
+----------------------------------------------------------
* @return Model
+----------------------------------------------------------
*/
function D($name='', $app='') {
static $_model = array();
if (empty($name))
return new Model;
if (empty($app))
$app = C('DEFAULT_APP');
if (isset($_model[$app . $name]))
return $_model[$app . $name];
$OriClassName = $name;
if (strpos($name, '.')) {
$array = explode('.', $name);
$name = array_pop($array);
$className = $name . 'Model';
import($app . '.Model.' . implode('.', $array) . '.' . $className);
} else {
$className = $name . 'Model';
import($app . '.Model.' . $className);
}
if (class_exists($className)) {
$model = new $className();
} else {
$model = new Model($name);
}
$_model[$app . $OriClassName] = $model;
return $model;
}
/**
+----------------------------------------------------------
* M函数用于实例化一个没有模型文件的Model
+----------------------------------------------------------
* @param string name Model名称
+----------------------------------------------------------
* @return Model
+----------------------------------------------------------
*/
function M($name='', $class='Model') {
static $_model = array();
if (!isset($_model[$name . '_' . $class]))
$_model[$name . '_' . $class] = new $class($name);
return $_model[$name . '_' . $class];
}
/**
+----------------------------------------------------------
* A函数用于实例化Action
+----------------------------------------------------------
* @param string name Action名称
* @param string app Model所在项目
+----------------------------------------------------------
* @return Action
+----------------------------------------------------------
*/
function A($name, $app='@') {
static $_action = array();
if (isset($_action[$app . $name]))
return $_action[$app . $name];
$OriClassName = $name;
if (strpos($name, '.')) {
$array = explode('.', $name);
$name = array_pop($array);
$className = $name . 'Action';
import($app . '.Action.' . implode('.', $array) . '.' . $className);
} else {
$className = $name . 'Action';
import($app . '.Action.' . $className);
}
if (class_exists($className)) {
$action = new $className();
$_action[$app . $OriClassName] = $action;
return $action;
} else {
return false;
}
}
// 远程调用模块的操作方法
function R($module, $action, $app='@') {
$class = A($module, $app);
if ($class)
return call_user_func(array(&$class, $action));
else
return false;
}
// 获取和设置语言定义(不区分大小写)
function L($name=null, $value=null) {
static $_lang = array();
// 空参数返回所有定义
if (empty($name))
return $_lang;
// 判断语言获取(或设置)
// 若不存在,直接返回全大写$name
if (is_string($name)) {
$name = strtoupper($name);
if (is_null($value))
return isset($_lang[$name]) ? $_lang[$name] : $name;
$_lang[$name] = $value; // 语言定义
return;
}
// 批量定义
if (is_array($name))
$_lang = array_merge($_lang, array_change_key_case($name, CASE_UPPER));
return;
}
// 获取配置值
function C($name=null, $value=null) {
static $_config = array();
// 无参数时获取所有
if (empty($name))
return $_config;
// 优先执行设置获取或赋值
if (is_string($name)) {
if (!strpos($name, '.')) {
$name = strtolower($name);
if (is_null($value))
return isset($_config[$name]) ? $_config[$name] : null;
$_config[$name] = $value;
return;
}
// 二维数组设置和获取支持
$name = explode('.', $name);
$name[0] = strtolower($name[0]);
if (is_null($value))
return isset($_config[$name[0]][$name[1]]) ? $_config[$name[0]][$name[1]] : null;
$_config[$name[0]][$name[1]] = $value;
return;
}
// 批量设置
if (is_array($name))
return $_config = array_merge($_config, array_change_key_case($name));
return null; // 避免非法参数
}
// 处理标签
function tag($name, $params=array()) {
$tags = C('_TAGS_.' . $name);
if (!empty($tags)) {
foreach ($tags as $key => $call) {
$result = B($call, $params);
}
}
}
// 过滤器方法
function filter($name, &$content) {
$class = $name . 'Filter';
require_cache(LIB_PATH . 'Filter/' . $class . '.class.php');
$filter = new $class();
$content = $filter->run($content);
}
// 执行行为
function B($name, $params=array()) {
$class = $name . 'Behavior';
require_cache(LIB_PATH . 'Behavior/' . $class . '.class.php');
$behavior = new $class();
return $behavior->run($params);
}
// 渲染输出Widget
function W($name, $data=array(), $return=false) {
$class = $name . 'Widget';
require_cache(LIB_PATH . 'Widget/' . $class . '.class.php');
if (!class_exists($class))
throw_exception(L('_CLASS_NOT_EXIST_') . ':' . $class);
$widget = Think::instance($class);
$content = $widget->render($data);
if ($return)
return $content;
else
echo $content;
}
// 全局缓存设置和读取
function S($name, $value='', $expire='', $type='') {
static $_cache = array();
alias_import('Cache');
//取得缓存对象实例
$cache = Cache::getInstance($type);
if ('' !== $value) {
if (is_null($value)) {
// 删除缓存
$result = $cache->rm($name);
if ($result)
unset($_cache[$type . '_' . $name]);
return $result;
}else {
// 缓存数据
$cache->set($name, $value, $expire);
$_cache[$type . '_' . $name] = $value;
}
return;
}
if (isset($_cache[$type . '_' . $name]))
return $_cache[$type . '_' . $name];
// 获取缓存数据
$value = $cache->get($name);
$_cache[$type . '_' . $name] = $value;
return $value;
}
// 快速文件数据读取和保存 针对简单类型数据 字符串、数组
function F($name, $value='', $path=DATA_PATH) {
static $_cache = array();
$filename = $path . $name . '.php';
if ('' !== $value) {
if (is_null($value)) {
// 删除缓存
return unlink($filename);
} else {
// 缓存数据
$dir = dirname($filename);
// 目录不存在则创建
if (!is_dir($dir))
mkdir($dir);
return file_put_contents($filename, "<?php\nreturn " . var_export($value, true) . ";\n?>");
}
}
if (isset($_cache[$name]))
return $_cache[$name];
// 获取缓存数据
if (is_file($filename)) {
$value = include $filename;
$_cache[$name] = $value;
} else {
$value = false;
}
return $value;
}
// 根据PHP各种类型变量生成唯一标识号
function to_guid_string($mix) {
if (is_object($mix) && function_exists('spl_object_hash')) {
return spl_object_hash($mix);
} elseif (is_resource($mix)) {
$mix = get_resource_type($mix) . strval($mix);
} else {
$mix = serialize($mix);
}
return md5($mix);
}
//[RUNTIME]
// 编译文件
// 去除代码中的空白和注释
function strip_whitespace($content) {
$stripStr = '';
//分析php源码
$tokens = token_get_all($content);
$last_space = false;
for ($i = 0, $j = count($tokens); $i < $j; $i++) {
if (is_string($tokens[$i])) {
$last_space = false;
$stripStr .= $tokens[$i];
} else {
switch ($tokens[$i][0]) {
//过滤各种PHP注释
case T_COMMENT:
case T_DOC_COMMENT:
break;
//过滤空格
case T_WHITESPACE:
if (!$last_space) {
$stripStr .= ' ';
$last_space = true;
}
break;
default:
$last_space = false;
$stripStr .= $tokens[$i][1];
}
}
}
return $stripStr;
}
function compile($filename, $runtime=false) {
$content = file_get_contents($filename);
if (true === $runtime)
// 替换预编译指令
$content = preg_replace('/\/\/\[RUNTIME\](.*?)\/\/\[\/RUNTIME\]/s', '', $content);
$content = substr(trim($content), 5);
if ('?>' == substr($content, -2))
$content = substr($content, 0, -2);
return $content;
}
// 根据数组生成常量定义
function array_define($array) {
$content = '';
foreach ($array as $key => $val) {
$key = strtoupper($key);
if (in_array($key, array('THINK_PATH', 'APP_NAME', 'APP_PATH', 'APP_CACHE_NAME', 'RUNTIME_PATH', 'RUNTIME_ALLINONE', 'THINK_MODE')))
$content .= 'if(!defined(\'' . $key . '\')) ';
if (is_int($val) || is_float($val)) {
$content .= "define('" . $key . "'," . $val . ");";
} elseif (is_bool($val)) {
$val = ($val) ? 'true' : 'false';
$content .= "define('" . $key . "'," . $val . ");";
} elseif (is_string($val)) {
$content .= "define('" . $key . "','" . addslashes($val) . "');";
}
}
return $content;
}
//[/RUNTIME]
// 循环创建目录
function mk_dir($dir, $mode = 0777) {
if (is_dir($dir) || @mkdir($dir, $mode))
return true;
if (!mk_dir(dirname($dir), $mode))
return false;
return @mkdir($dir, $mode);
}
// 自动转换字符集 支持数组转换
function auto_charset($fContents, $from='gbk', $to='utf-8') {
$from = strtoupper($from) == 'UTF8' ? 'utf-8' : $from;
$to = strtoupper($to) == 'UTF8' ? 'utf-8' : $to;
if (strtoupper($from) === strtoupper($to) || empty($fContents) || (is_scalar($fContents) && !is_string($fContents))) {
//如果编码相同或者非字符串标量则不转换
return $fContents;
}
if (is_string($fContents)) {
if (function_exists('mb_convert_encoding')) {
return mb_convert_encoding($fContents, $to, $from);
} elseif (function_exists('iconv')) {
return iconv($from, $to, $fContents);
} else {
return $fContents;
}
} elseif (is_array($fContents)) {
foreach ($fContents as $key => $val) {
$_key = auto_charset($key, $from, $to);
$fContents[$_key] = auto_charset($val, $from, $to);
if ($key != $_key)
unset($fContents[$key]);
}
return $fContents;
}
else {
return $fContents;
}
}
// xml编码
function xml_encode($data, $encoding='utf-8', $root="think") {
$xml = '<?xml version="1.0" encoding="' . $encoding . '"?>';
$xml.= '<' . $root . '>';
$xml.= data_to_xml($data);
$xml.= '</' . $root . '>';
return $xml;
}
function data_to_xml($data) {
if (is_object($data)) {
$data = get_object_vars($data);
}
$xml = '';
foreach ($data as $key => $val) {
is_numeric($key) && $key = "item id=\"$key\"";
$xml.="<$key>";
$xml.= ( is_array($val) || is_object($val)) ? data_to_xml($val) : $val;
list($key, ) = explode(' ', $key);
$xml.="</$key>";
}
return $xml;
}
/**
+----------------------------------------------------------
* Cookie 设置、获取、清除
+----------------------------------------------------------
* 1 获取cookie: cookie('name')
* 2 清空当前设置前缀的所有cookie: cookie(null)
* 3 删除指定前缀所有cookie: cookie(null,'think_') | 注:前缀将不区分大小写
* 4 设置cookie: cookie('name','value') | 指定保存时间: cookie('name','value',3600)
* 5 删除cookie: cookie('name',null)
+----------------------------------------------------------
* $option 可用设置prefix,expire,path,domain
* 支持数组形式对参数设置:cookie('name','value',array('expire'=>1,'prefix'=>'think_'))
* 支持query形式字符串对参数设置:cookie('name','value','prefix=tp_&expire=10000')
*/
function cookie($name, $value='', $option=null) {
// 默认设置
$config = array(
'prefix' => C('COOKIE_PREFIX'), // cookie 名称前缀
'expire' => C('COOKIE_EXPIRE'), // cookie 保存时间
'path' => C('COOKIE_PATH'), // cookie 保存路径
'domain' => C('COOKIE_DOMAIN'), // cookie 有效域名
);
// 参数设置(会覆盖黙认设置)
if (!empty($option)) {
if (is_numeric($option))
$option = array('expire' => $option);
elseif (is_string($option))
parse_str($option, $option);
$config = array_merge($config, array_change_key_case($option));
}
// 清除指定前缀的所有cookie
if (is_null($name)) {
if (empty($_COOKIE))
return;
// 要删除的cookie前缀,不指定则删除config设置的指定前缀
$prefix = empty($value) ? $config['prefix'] : $value;
if (!empty($prefix)) {// 如果前缀为空字符串将不作处理直接返回
foreach ($_COOKIE as $key => $val) {
if (0 === stripos($key, $prefix)) {
setcookie($key, '', time() - 3600, $config['path'], $config['domain']);
unset($_COOKIE[$key]);
}
}
}
return;
}
$name = $config['prefix'] . $name;
if ('' === $value) {
return isset($_COOKIE[$name]) ? $_COOKIE[$name] : null; // 获取指定Cookie
} else {
if (is_null($value)) {
setcookie($name, '', time() - 3600, $config['path'], $config['domain']);
unset($_COOKIE[$name]); // 删除指定cookie
} else {
// 设置cookie
$expire = !empty($config['expire']) ? time() + intval($config['expire']) : 0;
setcookie($name, $value, $expire, $config['path'], $config['domain']);
$_COOKIE[$name] = $value;
}
}
}
?> | 0321hy | trunk/Lib/ThinkPHP/Common/functions.php | PHP | asf20 | 32,071 |
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2007 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
// $Id$
/**
+------------------------------------------------------------------------------
* Think兼容函数库 针对5.2.0以下版本
+------------------------------------------------------------------------------
* @category Think
* @package Common
* @author liu21st <liu21st@gmail.com>
* @version $Id$
+------------------------------------------------------------------------------
*/
if (!function_exists('json_encode')) {
function format_json_value(&$value)
{
if(is_bool($value)) {
$value = $value?'true':'false';
}elseif(is_int($value)) {
$value = intval($value);
}elseif(is_float($value)) {
$value = floatval($value);
}elseif(defined($value) && $value === null) {
$value = strval(constant($value));
}elseif(is_string($value)) {
$value = '"'.addslashes($value).'"';
}
return $value;
}
function json_encode($data)
{
if(is_object($data)) {
//对象转换成数组
$data = get_object_vars($data);
}else if(!is_array($data)) {
// 普通格式直接输出
return format_json_value($data);
}
// 判断是否关联数组
if(empty($data) || is_numeric(implode('',array_keys($data)))) {
$assoc = false;
}else {
$assoc = true;
}
// 组装 Json字符串
$json = $assoc ? '{' : '[' ;
foreach($data as $key=>$val) {
if(!is_null($val)) {
if($assoc) {
$json .= "\"$key\":".json_encode($val).",";
}else {
$json .= json_encode($val).",";
}
}
}
if(strlen($json)>1) {// 加上判断 防止空数组
$json = substr($json,0,-1);
}
$json .= $assoc ? '}' : ']' ;
return $json;
}
}
if (!function_exists('json_decode')) {
function json_decode($json,$assoc=false)
{
// 目前不支持二维数组或对象
$begin = substr($json,0,1) ;
if(!in_array($begin,array('{','[')))
// 不是对象或者数组直接返回
return $json;
$parse = substr($json,1,-1);
$data = explode(',',$parse);
if($flag = $begin =='{' ) {
// 转换成PHP对象
$result = new stdClass();
foreach($data as $val) {
$item = explode(':',$val);
$key = substr($item[0],1,-1);
$result->$key = json_decode($item[1],$assoc);
}
if($assoc)
$result = get_object_vars($result);
}else {
// 转换成PHP数组
$result = array();
foreach($data as $val)
$result[] = json_decode($val,$assoc);
}
return $result;
}
}
if (!function_exists('property_exists')) {
/**
+----------------------------------------------------------
* 判断对象的属性是否存在 PHP5.1.0以上已经定义
+----------------------------------------------------------
* @param object $class 对象实例
* @param string $property 属性名称
+----------------------------------------------------------
* @return boolen
+----------------------------------------------------------
*/
function property_exists($class, $property) {
if (is_object($class))
$class = get_class($class);
return array_key_exists($property, get_class_vars($class));
}
}
?> | 0321hy | trunk/Lib/ThinkPHP/Common/compat.php | PHP | asf20 | 4,333 |
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2010 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
// $Id$
/**
+------------------------------------------------------------------------------
* ThinkPHP惯例配置文件
* 该文件请不要修改,如果要覆盖惯例配置的值,可在项目配置文件中设定和惯例不符的配置项
* 配置名称大小写任意,系统会统一转换成小写
* 所有配置参数都可以在生效前动态改变
+------------------------------------------------------------------------------
* @category Think
* @package Common
* @author liu21st <liu21st@gmail.com>
* @version $Id$
+------------------------------------------------------------------------------
*/
if (!defined('THINK_PATH')) exit();
return array(
/* 项目设定 */
'APP_DEBUG' => false, // 是否开启调试模式
'APP_DOMAIN_DEPLOY' => false, // 是否使用独立域名部署项目
'APP_SUB_DOMAIN_DEPLOY' => false, // 是否开启子域名
'APP_PLUGIN_ON' => false, // 是否开启插件机制
'APP_FILE_CASE' => false, // 是否检查文件的大小写 对Windows平台有效
'APP_GROUP_DEPR' => '.', // 模块分组之间的分割符
'APP_GROUP_LIST' => '', // 项目分组设定,多个组之间用逗号分隔,例如'Home,Admin'
'APP_AUTOLOAD_REG' => false, // 是否开启SPL_AUTOLOAD_REGISTER
'APP_AUTOLOAD_PATH' => 'Think.Util.',// __autoLoad 机制额外检测路径设置,注意搜索顺序
'APP_CONFIG_LIST' => array('taglibs','routes','tags','htmls','modules','actions'),// 项目额外需要加载的配置列表,默认包括:taglibs(标签库定义),routes(路由定义),tags(标签定义),(htmls)静态缓存定义, modules(扩展模块),actions(扩展操作)
/* Cookie设置 */
'COOKIE_EXPIRE' => 3600, // Coodie有效期
'COOKIE_DOMAIN' => '', // Cookie有效域名
'COOKIE_PATH' => '/', // Cookie路径
'COOKIE_PREFIX' => '', // Cookie前缀 避免冲突
/* 默认设定 */
'DEFAULT_APP' => '@', // 默认项目名称,@表示当前项目
'DEFAULT_GROUP' => 'Home', // 默认分组
'DEFAULT_MODULE' => 'Index', // 默认模块名称
'DEFAULT_ACTION' => 'index', // 默认操作名称
'DEFAULT_CHARSET' => 'utf-8', // 默认输出编码
'DEFAULT_TIMEZONE' => 'PRC', // 默认时区
'DEFAULT_AJAX_RETURN' => 'JSON', // 默认AJAX 数据返回格式,可选JSON XML ...
'DEFAULT_THEME' => 'default', // 默认模板主题名称
'DEFAULT_LANG' => 'zh-cn', // 默认语言
/* 数据库设置 */
'DB_TYPE' => 'mysql', // 数据库类型
'DB_HOST' => 'localhost', // 服务器地址
'DB_NAME' => '', // 数据库名
'DB_USER' => 'root', // 用户名
'DB_PWD' => '', // 密码
'DB_PORT' => 3306, // 端口
'DB_PREFIX' => 'think_', // 数据库表前缀
'DB_SUFFIX' => '', // 数据库表后缀
'DB_FIELDTYPE_CHECK' => false, // 是否进行字段类型检查
'DB_FIELDS_CACHE' => true, // 启用字段缓存
'DB_CHARSET' => 'utf8', // 数据库编码默认采用utf8
'DB_DEPLOY_TYPE' => 0, // 数据库部署方式:0 集中式(单一服务器),1 分布式(主从服务器)
'DB_RW_SEPARATE' => false, // 数据库读写是否分离 主从式有效
/* 数据缓存设置 */
'DATA_CACHE_TIME' => -1, // 数据缓存有效期
'DATA_CACHE_COMPRESS' => false, // 数据缓存是否压缩缓存
'DATA_CACHE_CHECK' => false, // 数据缓存是否校验缓存
'DATA_CACHE_TYPE' => 'File', // 数据缓存类型,支持:File|Db|Apc|Memcache|Shmop|Sqlite| Xcache|Apachenote|Eaccelerator
'DATA_CACHE_PATH' => TEMP_PATH,// 缓存路径设置 (仅对File方式缓存有效)
'DATA_CACHE_SUBDIR' => false, // 使用子目录缓存 (自动根据缓存标识的哈希创建子目录)
'DATA_PATH_LEVEL' => 1, // 子目录缓存级别
/* 错误设置 */
'ERROR_MESSAGE' => '您浏览的页面暂时发生了错误!请稍后再试~',//错误显示信息,非调试模式有效
'ERROR_PAGE' => '', // 错误定向页面
/* 静态缓存设置 */
'HTML_CACHE_ON' => false, // 默认关闭静态缓存
'HTML_CACHE_TIME' => 60, // 静态缓存有效期
'HTML_READ_TYPE' => 0, // 静态缓存读取方式 0 readfile 1 redirect
'HTML_FILE_SUFFIX' => '.shtml',// 默认静态文件后缀
/* 语言设置 */
'LANG_SWITCH_ON' => false, // 默认关闭多语言包功能
'LANG_AUTO_DETECT' => true, // 自动侦测语言 开启多语言功能后有效
/* 日志设置 */
'LOG_EXCEPTION_RECORD' => true, // 是否记录异常信息日志(默认为开启状态)
'LOG_RECORD' => false, // 默认不记录日志
'LOG_FILE_SIZE' => 2097152, // 日志文件大小限制
'LOG_RECORD_LEVEL' => array('EMERG','ALERT','CRIT','ERR'),// 允许记录的日志级别
/* 分页设置 */
'PAGE_ROLLPAGE' => 5, // 分页显示页数
'PAGE_LISTROWS' => 20, // 分页每页显示记录数
/* SESSION设置 */
'SESSION_AUTO_START' => true, // 是否自动开启Session
// 内置SESSION类可用参数
//'SESSION_NAME' => '', // Session名称
//'SESSION_PATH' => '', // Session保存路径
//'SESSION_CALLBACK' => '', // Session 对象反序列化时候的回调函数
/* 运行时间设置 */
'SHOW_RUN_TIME' => false, // 运行时间显示
'SHOW_ADV_TIME' => false, // 显示详细的运行时间
'SHOW_DB_TIMES' => false, // 显示数据库查询和写入次数
'SHOW_CACHE_TIMES' => false, // 显示缓存操作次数
'SHOW_USE_MEM' => false, // 显示内存开销
'SHOW_PAGE_TRACE' => false, // 显示页面Trace信息 由Trace文件定义和Action操作赋值
'SHOW_ERROR_MSG' => true, // 显示错误信息
/* 模板引擎设置 */
'TMPL_ENGINE_TYPE' => 'Think', // 默认模板引擎 以下设置仅对使用Think模板引擎有效
'TMPL_DETECT_THEME' => false, // 自动侦测模板主题
'TMPL_TEMPLATE_SUFFIX' => '.html', // 默认模板文件后缀
'TMPL_CONTENT_TYPE' => 'text/html', // 默认模板输出类型
'TMPL_CACHFILE_SUFFIX' => '.php', // 默认模板缓存后缀
'TMPL_DENY_FUNC_LIST' => 'echo,exit', // 模板引擎禁用函数
'TMPL_PARSE_STRING' => '', // 模板引擎要自动替换的字符串,必须是数组形式。
'TMPL_L_DELIM' => '{', // 模板引擎普通标签开始标记
'TMPL_R_DELIM' => '}', // 模板引擎普通标签结束标记
'TMPL_VAR_IDENTIFY' => 'array', // 模板变量识别。留空自动判断,参数为'obj'则表示对象
'TMPL_STRIP_SPACE' => false, // 是否去除模板文件里面的html空格与换行
'TMPL_CACHE_ON' => true, // 是否开启模板编译缓存,设为false则每次都会重新编译
'TMPL_CACHE_TIME' => -1, // 模板缓存有效期 -1 为永久,(以数字为值,单位:秒)
'TMPL_ACTION_ERROR' => 'Public:success', // 默认错误跳转对应的模板文件
'TMPL_ACTION_SUCCESS' => 'Public:success', // 默认成功跳转对应的模板文件
'TMPL_TRACE_FILE' => THINK_PATH.'/Tpl/PageTrace.tpl.php', // 页面Trace的模板文件
'TMPL_EXCEPTION_FILE' => THINK_PATH.'/Tpl/ThinkException.tpl.php',// 异常页面的模板文件
'TMPL_FILE_DEPR'=>'/', //模板文件MODULE_NAME与ACTION_NAME之间的分割符,只对项目分组部署有效
// Think模板引擎标签库相关设定
'TAGLIB_BEGIN' => '<', // 标签库标签开始标记
'TAGLIB_END' => '>', // 标签库标签结束标记
'TAGLIB_LOAD' => true, // 是否使用内置标签库之外的其它标签库,默认自动检测
'TAGLIB_BUILD_IN' => 'cx', // 内置标签库名称(标签使用不必指定标签库名称),以逗号分隔
'TAGLIB_PRE_LOAD' => '', // 需要额外加载的标签库(须指定标签库名称),多个以逗号分隔
'TAG_NESTED_LEVEL' => 3, // 标签嵌套级别
'TAG_EXTEND_PARSE' => '', // 指定对普通标签进行扩展定义和解析的函数名称。
/* 表单令牌验证 */
'TOKEN_ON' => true, // 开启令牌验证
'TOKEN_NAME' => '__hash__', // 令牌验证的表单隐藏字段名称
'TOKEN_TYPE' => 'md5', // 令牌验证哈希规则
/* URL设置 */
'URL_CASE_INSENSITIVE' => false, // URL地址是否不区分大小写
'URL_ROUTER_ON' => false, // 是否开启URL路由
'URL_ROUTE_RULES' => array(), // 默认路由规则,注:分组配置无法替代
//'URL_DISPATCH_ON' => true, // 是否启用Dispatcher,不再生效
'URL_MODEL' => 1, // URL访问模式,可选参数0、1、2、3,代表以下四种模式:
// 0 (普通模式); 1 (PATHINFO 模式); 2 (REWRITE 模式); 3 (兼容模式) 默认为PATHINFO 模式,提供最好的用户体验和SEO支持
'URL_PATHINFO_MODEL' => 2, // PATHINFO 模式,使用数字1、2、3代表以下三种模式:
// 1 普通模式(参数没有顺序,例如/m/module/a/action/id/1);
// 2 智能模式(系统默认使用的模式,可自动识别模块和操作/module/action/id/1/ 或者 /module,action,id,1/...);
// 3 兼容模式(通过一个GET变量将PATHINFO传递给dispather,默认为s index.php?s=/module/action/id/1)
'URL_PATHINFO_DEPR' => '/', // PATHINFO模式下,各参数之间的分割符号
'URL_HTML_SUFFIX' => '', // URL伪静态后缀设置
//'URL_AUTO_REDIRECT' => true, // 自动重定向到规范的URL 不再生效
/* 系统变量名称设置 */
'VAR_GROUP' => 'g', // 默认分组获取变量
'VAR_MODULE' => 'm', // 默认模块获取变量
'VAR_ACTION' => 'a', // 默认操作获取变量
'VAR_ROUTER' => 'r', // 默认路由获取变量
'VAR_PAGE' => 'p', // 默认分页跳转变量
'VAR_TEMPLATE' => 't', // 默认模板切换变量
'VAR_LANGUAGE' => 'l', // 默认语言切换变量
'VAR_AJAX_SUBMIT' => 'ajax', // 默认的AJAX提交变量
'VAR_PATHINFO' => 's', // PATHINFO 兼容模式获取变量例如 ?s=/module/action/id/1 后面的参数取决于URL_PATHINFO_MODEL 和 URL_PATHINFO_DEPR
);
?> | 0321hy | trunk/Lib/ThinkPHP/Common/convention.php | PHP | asf20 | 11,676 |
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2010 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
// $Id$
/**
+------------------------------------------------------------------------------
* ThinkPHP 默认的调试模式配置文件
* 如果项目有定义自己的调试模式配置文件,本文件无效
+------------------------------------------------------------------------------
* @category Think
* @package Common
* @author liu21st <liu21st@gmail.com>
* @version $Id$
+------------------------------------------------------------------------------
*/
if (!defined('THINK_PATH')) exit();
return array(
/* 日志设置 */
'LOG_RECORD'=>true, // 进行日志记录
/* 数据库设置 */
'LOG_RECORD_LEVEL' => array('EMERG','ALERT','CRIT','ERR','WARN','NOTIC','INFO','DEBUG','SQL'), // 允许记录的日志级别
'DB_FIELDS_CACHE'=> false,
/* 运行时间设置 */
'SHOW_RUN_TIME'=>true, // 运行时间显示
'SHOW_ADV_TIME'=>true, // 显示详细的运行时间
'SHOW_DB_TIMES'=>true, // 显示数据库查询和写入次数
'SHOW_CACHE_TIMES'=>true, // 显示缓存操作次数
'SHOW_USE_MEM'=>true, // 显示内存开销
'SHOW_PAGE_TRACE'=>true, // 显示页面Trace信息 由Trace文件定义和Action操作赋值
'APP_FILE_CASE' => true, // 是否检查文件的大小写 对Windows平台有效
);
?> | 0321hy | trunk/Lib/ThinkPHP/Common/debug.php | PHP | asf20 | 1,986 |
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2010 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
// $Id$
// 检查缓存目录(Runtime) 如果不存在则自动创建
function check_runtime() {
if(!is_writeable(RUNTIME_PATH)) {
header("Content-Type:text/html; charset=utf-8");
exit('<div style=\'font-weight:bold;float:left;width:345px;text-align:center;border:1px solid silver;background:#E8EFFF;padding:8px;color:red;font-size:14px;font-family:Tahoma\'>目录 [ '.RUNTIME_PATH.' ] 不可写!</div>');
}
if(!is_dir(CACHE_PATH)) mkdir(CACHE_PATH); // 模板缓存目录
if(!is_dir(LOG_PATH)) mkdir(LOG_PATH); // 日志目录
if(!is_dir(TEMP_PATH)) mkdir(TEMP_PATH); // 数据缓存目录
if(!is_dir(DATA_PATH)) mkdir(DATA_PATH); // 数据文件目录
return true;
}
// 生成核心编译缓存
function build_runtime() {
// 加载常量定义文件
require THINK_PATH.'/Common/defines.php';
// 加载路径定义文件
require defined('PATH_DEFINE_FILE')?PATH_DEFINE_FILE:THINK_PATH.'/Common/paths.php';
// 读取核心编译文件列表
if(is_file(CONFIG_PATH.'core.php')) {
// 加载项目自定义的核心编译文件列表
$list = include CONFIG_PATH.'core.php';
}elseif(defined('THINK_MODE')) {
// 根据设置的运行模式加载不同的核心编译文件
$list = include THINK_PATH.'/Mode/'.strtolower(THINK_MODE).'.php';
}else{
// 默认核心
$list = include THINK_PATH.'/Common/core.php';
}
// 加载兼容函数
if(version_compare(PHP_VERSION,'5.2.0','<') )
$list[] = THINK_PATH.'/Common/compat.php';
// 加载核心编译文件列表
foreach ($list as $key=>$file){
if(is_file($file)) require $file;
}
// 检查项目目录结构 如果不存在则自动创建
if(!is_dir(RUNTIME_PATH)) {
// 创建项目目录结构
build_app_dir();
}else{
// 检查缓存目录
check_runtime();
}
// 生成核心编译缓存 去掉文件空白以减少大小
if(!defined('NO_CACHE_RUNTIME')) {
$compile = defined('RUNTIME_ALLINONE');
$content = compile(THINK_PATH.'/Common/defines.php',$compile);
$content .= compile(defined('PATH_DEFINE_FILE')? PATH_DEFINE_FILE : THINK_PATH.'/Common/paths.php',$compile);
foreach ($list as $file){
$content .= compile($file,$compile);
}
$runtime = defined('THINK_MODE')?'~'.strtolower(THINK_MODE).'_runtime.php':'~runtime.php';
if(defined('STRIP_RUNTIME_SPACE') && STRIP_RUNTIME_SPACE == false ) {
file_put_contents(RUNTIME_PATH.$runtime,'<?php'.$content);
}else{
file_put_contents(RUNTIME_PATH.$runtime,strip_whitespace('<?php'.$content));
}
unset($content);
}
}
// 批量创建目录
function mkdirs($dirs,$mode=0777) {
foreach ($dirs as $dir){
if(!is_dir($dir)) mkdir($dir,$mode);
}
}
// 默认创建测试Action处理函数
if (!function_exists('build_action'))
{
function build_action()
{
$content = file_get_contents(THINK_PATH.'/Tpl/'.(defined('BUILD_MODE')?BUILD_MODE:'AutoIndex').'.tpl.php');
file_put_contents(LIB_PATH.'Action/IndexAction.class.php',$content);
}
}
// 创建项目目录结构
function build_app_dir() {
// 没有创建项目目录的话自动创建
if(!is_dir(APP_PATH)) mk_dir(APP_PATH,0777);
if(is_writeable(APP_PATH)) {
$dirs = array(
LIB_PATH,
RUNTIME_PATH,
CONFIG_PATH,
COMMON_PATH,
LANG_PATH,
CACHE_PATH,
TMPL_PATH,
TMPL_PATH.'default/',
LOG_PATH,
TEMP_PATH,
DATA_PATH,
LIB_PATH.'Model/',
LIB_PATH.'Action/',
);
mkdirs($dirs);
// 目录安全写入
if(!defined('BUILD_DIR_SECURE')) define('BUILD_DIR_SECURE',false);
if(BUILD_DIR_SECURE) {
if(!defined('DIR_SECURE_FILENAME')) define('DIR_SECURE_FILENAME','index.html');
if(!defined('DIR_SECURE_CONTENT')) define('DIR_SECURE_CONTENT',' ');
// 自动写入目录安全文件
$content = DIR_SECURE_CONTENT;
$a = explode(',', DIR_SECURE_FILENAME);
foreach ($a as $filename){
foreach ($dirs as $dir)
file_put_contents($dir.$filename,$content);
}
}
// 写入配置文件
if(!is_file(CONFIG_PATH.'config.php'))
file_put_contents(CONFIG_PATH.'config.php',"<?php\nreturn array(\n\t//'配置项'=>'配置值'\n);\n?>");
// 写入测试Action
if(!is_file(LIB_PATH.'Action/IndexAction.class.php'))
build_action();
}else{
header("Content-Type:text/html; charset=utf-8");
exit('<div style=\'font-weight:bold;float:left;width:345px;text-align:center;border:1px solid silver;background:#E8EFFF;padding:8px;color:red;font-size:14px;font-family:Tahoma\'>项目目录不可写,目录无法自动生成!<BR>请使用项目生成器或者手动生成项目目录~</div>');
}
}
?> | 0321hy | trunk/Lib/ThinkPHP/Common/runtime.php | PHP | asf20 | 5,818 |
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2010 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
// $Id$
// 系统默认的核心列表文件
return array(
THINK_PATH.'/Common/functions.php', // 系统函数库
THINK_PATH.'/Lib/Think/Core/Think.class.php',
THINK_PATH.'/Lib/Think/Exception/ThinkException.class.php', // 异常处理类
THINK_PATH.'/Lib/Think/Core/Log.class.php', // 日志处理类
THINK_PATH.'/Lib/Think/Core/App.class.php', // 应用程序类
THINK_PATH.'/Lib/Think/Core/Action.class.php', // 控制器类
//THINK_PATH.'/Lib/Think/Core/Model.class.php', // 模型类
THINK_PATH.'/Lib/Think/Core/View.class.php', // 视图类
THINK_PATH.'/Common/alias.php', // 加载别名
);
?> | 0321hy | trunk/Lib/ThinkPHP/Common/core.php | PHP | asf20 | 1,263 |
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2010 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
// $Id$
/**
+------------------------------------------------------------------------------
* 系统定义文件
+------------------------------------------------------------------------------
* @category Think
* @package Common
* @author liu21st <liu21st@gmail.com>
* @version $Id$
+------------------------------------------------------------------------------
*/
//[RUNTIME]
if (!defined('THINK_PATH')) exit();
// 系统信息
if(version_compare(PHP_VERSION,'6.0.0','<') ) {
@set_magic_quotes_runtime (0);
define('MAGIC_QUOTES_GPC',get_magic_quotes_gpc()?True:False);
}
define('MEMORY_LIMIT_ON',function_exists('memory_get_usage'));
define('IS_CGI',substr(PHP_SAPI, 0,3)=='cgi' ? 1 : 0 );
define('IS_WIN',strstr(PHP_OS, 'WIN') ? 1 : 0 );
define('IS_CLI',PHP_SAPI=='cli'? 1 : 0);
if(!IS_CLI) {
// 当前文件名
if(!defined('_PHP_FILE_')) {
if(IS_CGI) {
//CGI/FASTCGI模式下
$_temp = explode('.php',$_SERVER["PHP_SELF"]);
define('_PHP_FILE_', rtrim(str_replace($_SERVER["HTTP_HOST"],'',$_temp[0].'.php'),'/'));
}else {
define('_PHP_FILE_', rtrim($_SERVER["SCRIPT_NAME"],'/'));
}
}
if(!defined('__ROOT__')) {
// 网站URL根目录
if( strtoupper(APP_NAME) == strtoupper(basename(dirname(_PHP_FILE_))) ) {
$_root = dirname(dirname(_PHP_FILE_));
}else {
$_root = dirname(_PHP_FILE_);
}
define('__ROOT__', (($_root=='/' || $_root=='\\')?'':$_root));
}
//支持的URL模式
define('URL_COMMON', 0); //普通模式
define('URL_PATHINFO', 1); //PATHINFO模式
define('URL_REWRITE', 2); //REWRITE模式
define('URL_COMPAT', 3); // 兼容模式
}
// 版本信息
define('THINK_VERSION', '2.1');
//[/RUNTIME]
// 记录内存初始使用
if(MEMORY_LIMIT_ON) {
$GLOBALS['_startUseMems'] = memory_get_usage();
}
?> | 0321hy | trunk/Lib/ThinkPHP/Common/defines.php | PHP | asf20 | 2,612 |
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2008 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
// $Id$
//[RUNTIME]
// 目录设置
define('CACHE_DIR', 'Cache');
define('HTML_DIR', 'Html');
define('CONF_DIR', 'Conf');
define('LIB_DIR', 'Lib');
define('LOG_DIR', 'Logs');
define('LANG_DIR', 'Lang');
define('TEMP_DIR', 'Temp');
define('TMPL_DIR', 'Tpl');
// 路径设置
define('TMPL_PATH','./Tpl/');
define('HTML_PATH','./'.RUNTIME_PATH.'/'.HTML_DIR.'/');
//define('TMPL_PATH',APP_PATH.'/'.TMPL_DIR.'/');
//define('HTML_PATH',APP_PATH.'/'.HTML_DIR.'/'); //
define('COMMON_PATH', APP_PATH.'/Common/'); // 项目公共目录
define('LIB_PATH', APP_PATH.'/'.LIB_DIR.'/'); //
define('CACHE_PATH', RUNTIME_PATH.CACHE_DIR.'/'); //
define('CONFIG_PATH', APP_PATH.'/'.CONF_DIR.'/'); //
define('LOG_PATH', RUNTIME_PATH.LOG_DIR.'/'); //
define('LANG_PATH', APP_PATH.'/'.LANG_DIR.'/'); //
define('TEMP_PATH', RUNTIME_PATH.TEMP_DIR.'/'); //
define('DATA_PATH', RUNTIME_PATH.'Data/'); //
define('VENDOR_PATH',THINK_PATH.'/Vendor/');
//[/RUNTIME]
// 为了方便导入第三方类库 设置Vendor目录到include_path
set_include_path(get_include_path() . PATH_SEPARATOR . VENDOR_PATH);
?> | 0321hy | trunk/Lib/ThinkPHP/Common/paths.php | PHP | asf20 | 1,763 |
using UnityEngine;
using System.Collections;
public class EquipJob : Job {
Tool tool;
public EquipJob(Tool t, int nstartX, int nstartY, int nstartZ):base(nstartX, nstartY, nstartZ, 4){
tool = t;
}
public bool workOn(Robot robot){
robot.tools.Add(tool);
percentageComplete = 200;
if (tool.isConstructionTool){
robot.addConstructionTool((ConstructionTool)(tool));
robot.hasConstructionTool = true;
} else if (tool.isDeconstructionTool){
robot.addDeconstructionTool((DeconstructionTool)(tool));
robot.hasDeconstructionTool = true;
} else if (tool.isMiningTool){
robot.addMiningTool((MiningTool)(tool));
robot.hasMiningTool = true;
}
bool isDone = base.workOn(1, robot);
Controller.removeTool(tool);
return true;
}
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
}
| 100-degrees-celsius | Jobs and Robots/Jobs/EquipJob.cs | C# | gpl3 | 885 |
using UnityEngine;
using System.Collections;
public class HaulingJob : Job {
Item item;
int haulingToX, haulingToY, haulingToZ;
public HaulingJob(Item nitem, int endX, int endY, int endZ):base(nitem.x, nitem.y, nitem.z, 5){
item = nitem;
haulingToX = endX;
haulingToY = endY;
haulingToZ = endZ;
}
public bool workOn(Robot robot){
robot.hauledItem = item;
Job endJob = new Job(haulingToX, haulingToY, haulingToZ, 0);
endJob.percentageComplete = 101;
robot.assignJob(endJob);
return true;
}
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
}
| 100-degrees-celsius | Jobs and Robots/Jobs/HaulingJob.cs | C# | gpl3 | 639 |
using UnityEngine;
using System.Collections;
public class ConstructionJob : Job {
public ConstructionJob(int nstartX, int nstartY, int nstartZ):base(nstartX, nstartY, nstartZ, 2){
}
public bool workOn(double workspeed, Robot robot){
bool isDone = base.workOn(workspeed, robot);
double amount = workspeed * (robot.rateOfConstruction);
percentageComplete += amount;
foreach (Tool t in robot.constructionTools){
t.wearPercent += 0.001/t.material.strengthModifier;
if (t.wearPercent > 100){
robot.tools.Remove(t);
robot.constructionTools.Remove(t);
robot.hasConstructionTool = false;
}
}
return isDone;
}
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
}
| 100-degrees-celsius | Jobs and Robots/Jobs/Construction Jobs/ConstructionJob.cs | C# | gpl3 | 771 |
using UnityEngine;
using System.Collections;
public class TrackConstructionJob : ConstructionJob {
int startX, startY, startZ;
int endX, endY, endZ;
public TrackConstructionJob(int nstartX, int nstartY, int nstartZ, int nendX, int nendY, int nendZ)
:base(nstartX, nstartY, nstartZ)
{
startX = nstartX;
startY = nstartY;
startZ = nstartZ;
endX = nendX;
endY = nendY;
endZ = nendZ;
}
public bool workOn(double workspeed, Robot robot){
bool isDone = base.workOn(workspeed, robot);
if (isDone){
SplineControlPoint[] points = new SplineControlPoint[3];
points[0] = new SplineControlPoint(new Vector3((float) (startX), (float)(startY), (float)(startZ)),
new Vector3(-1,-1,-1), new float[] {50, 50});
points[1] = new SplineControlPoint(new Vector3((float)(endX), (float)(endY), (float)(endZ)),
new Vector3(-1,-1,-1), new float[] {50, 50});
Spline3D path = new Spline3D(points);
path.Subdivide(2);
//Here will be genRail(), once Virex moves it to the right place
}
return isDone;
}
}
| 100-degrees-celsius | Jobs and Robots/Jobs/Construction Jobs/TrackConstructionJob.cs | C# | gpl3 | 1,062 |
using UnityEngine;
using System.Collections;
public class MiningJob : Job {
public MiningJob(int nstartX, int nstartY, int nstartZ):base(nstartX, nstartY, nstartZ, 6){
}
public bool workOn(double workspeed, Robot robot){
bool isDone = base.workOn(workspeed, robot);
double amount = workspeed * (robot.rateOfMining);
percentageComplete += amount;
foreach (Tool t in robot.miningTools){
t.wearPercent += 0.001/t.material.strengthModifier;
if (t.wearPercent > 100){
robot.tools.Remove(t);
robot.miningTools.Remove(t);
robot.hasMiningTool = false;
}
}
return isDone;
}
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
}
| 100-degrees-celsius | Jobs and Robots/Jobs/MiningJob.cs | C# | gpl3 | 738 |
using UnityEngine;
using System.Collections;
public static class Controller{
private static ArrayList unasignedJobs;
private static ArrayList idlingRobots;
private static ArrayList unusedTools;
// Use this for initialization
public static void Start () {
unasignedJobs = null;
idlingRobots = null;
unasignedJobs = new ArrayList();
idlingRobots = new ArrayList();
unusedTools = new ArrayList();
}
// Update is called once per frame
public static void Update () {
if ((int)(idlingRobots.Count) != 0){
if (unasignedJobs.Count != 0){
Robot bestRobot = (Robot)(idlingRobots[0]);
int bestCost = 1000000;
Job jobToBeAssigned = (Job) (unasignedJobs[0]);
foreach(Robot rob in idlingRobots){
if ((getCostOf(rob, jobToBeAssigned)) < bestCost){
bestCost = getCostOf(rob, jobToBeAssigned);
bestRobot = rob;
}
}
Robot robotToBeAssigned = bestRobot;
robotToBeAssigned.assignJob(jobToBeAssigned);
idlingRobots.Remove(robotToBeAssigned);
unasignedJobs.Remove(jobToBeAssigned);
}
}
}
public static void addJob(Job j){
unasignedJobs.Add(j);
}
public static void addRobot(Robot r){
idlingRobots.Add (r);
}
public static void finishedJob(Robot r, Job j){
idlingRobots.Remove(r);
unasignedJobs.Remove(j);
}
public static ArrayList getUnusedTools(){
return unusedTools;
}
public static void addUnusedTool(Tool t){
unusedTools.Add(t);
}
public static void removeTool(Tool t){
unusedTools.Remove(t);
}
public static int getCostOf(Robot robot, Job job){
int cost = 0;
Point robotPoint = robot.getPostion();
cost += Mathf.Abs(robotPoint.x - job.x);
cost += Mathf.Abs(robotPoint.y - job.y);
cost += Mathf.Abs(robotPoint.z - job.z);
if (job.jobType == 2){
cost -= (int)(3 * (robot.rateOfConstruction));
} else if (job.jobType == 3){
cost -= (int)(3 * (robot.rateOfDeconstruction));
} else if (job.jobType == 6){
cost -= (int)(3 * (robot.rateOfMining));
}
return cost;
}
}
| 100-degrees-celsius | Jobs and Robots/Jobs/Controller.cs | C# | gpl3 | 2,031 |
using UnityEngine;
using System.Collections;
public class ReactionJob : BuildingOperationJob {
int reactionType;
public ReactionJob(int nstartX, int nstartY, int nstartZ, int nreactionType):base(nstartX, nstartY, nstartZ){
}
public bool workOn(double workspeed, Robot robot){
bool isDone = base.workOn(workspeed, robot);
if (isDone){
GameObject m = GameObject.CreatePrimitive(PrimitiveType.Cube);
//m.AddComponent(Rigidbody);
m.transform.position = new Vector3(2, 0, 15);
}
return isDone;
}
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
}
| 100-degrees-celsius | Jobs and Robots/Jobs/Building Operation Jobs/Reactions/ReactionJob.cs | C# | gpl3 | 644 |
using UnityEngine;
using System.Collections;
public class BuildingOperationJob : Job {
public BuildingOperationJob(int nstartX, int nstartY, int nstartZ):base(nstartX, nstartY, nstartZ, 1){
isBuildingOperationJob = true;
}
public bool workOn(double workspeed, Robot robot){
bool isDone = base.workOn(workspeed, robot);
double amount = workspeed;
percentageComplete += amount;
return isDone;
}
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
}
| 100-degrees-celsius | Jobs and Robots/Jobs/Building Operation Jobs/BuildingOperationJob.cs | C# | gpl3 | 530 |
using UnityEngine;
using System.Collections;
public class Job{
public double percentageComplete = 0;
public bool isBuildingOperationJob, isConstructionJob, isDeconstructionJob,
isEquipJob, isHaulingJob, isMiningJob;
public int x, y, z;
public int jobType;
public Job(int startX, int startY, int startZ, int njobType){
x = startX;
y = startY;
z = startZ;
percentageComplete = 0;
/*-
isBuildingOperationJob = false;
isConstructionJob = false;
isDeconstructionJob = false;
isEquipJob = false;
isHaulingJob = false;
isMiningJob = false;
-*/
jobType = njobType;
if ((jobType > 6) | (jobType < 0)){
jobType = 0;
}
Controller.addJob(this);
}
public bool workOn(double workspeed, Robot robot){
if (percentageComplete > 100){
return true;
} else {
return false;
}
}
}
| 100-degrees-celsius | Jobs and Robots/Jobs/Job.cs | C# | gpl3 | 846 |
using UnityEngine;
using System.Collections;
public class DeconstructionJob : Job {
public DeconstructionJob(int nstartX, int nstartY, int nstartZ):base(nstartX, nstartY, nstartZ, 3){
}
public bool workOn(double workspeed, Robot robot){
bool isDone = base.workOn(workspeed, robot);
double amount = workspeed * (robot.rateOfDeconstruction);
percentageComplete += amount;
foreach (Tool t in robot.deconstructionTools){
t.wearPercent += 0.001/t.material.strengthModifier;
if (t.wearPercent > 100){
robot.tools.Remove(t);
robot.deconstructionTools.Remove(t);
robot.hasDeconstructionTool = false;
}
}
return isDone;
}
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
}
| 100-degrees-celsius | Jobs and Robots/Jobs/DeconstructionJob.cs | C# | gpl3 | 780 |
using UnityEngine;
using System.Collections;
public class Ore : Item {
public Ore(Material material, int nx, int ny, int nz){
x = nx;
y = ny;
z = nz;
}
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
}
| 100-degrees-celsius | Jobs and Robots/Items/Ores/Ore.cs | C# | gpl3 | 332 |
using UnityEngine;
using System.Collections;
public class DeconstructionTool : Tool {
public DeconstructionTool(Metal nmaterial, int nx, int ny, int nz):base(nx, ny, nz){
material = nmaterial;
speedWithTool = material.workSpeedModifier * 0.5;
}
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
}
| 100-degrees-celsius | Jobs and Robots/Items/Equipment and Tools/DeconstructionTool.cs | C# | gpl3 | 373 |
using UnityEngine;
using System.Collections;
public class ConstructionTool : Tool {
public ConstructionTool(Metal nmaterial, int nx, int ny, int nz):base(nx, ny, nz){
material = nmaterial;
speedWithTool = material.workSpeedModifier * 0.5;
}
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
}
| 100-degrees-celsius | Jobs and Robots/Items/Equipment and Tools/ConstructionTool.cs | C# | gpl3 | 374 |
using UnityEngine;
using System.Collections;
public class MiningTool : Tool {
public MiningTool(Metal nmaterial, int nx, int ny, int nz):base(nx, ny, nz){
material = nmaterial;
isMiningTool = true;
speedWithTool = material.workSpeedModifier * 0.5;
}
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
}
| 100-degrees-celsius | Jobs and Robots/Items/Equipment and Tools/MiningTool.cs | C# | gpl3 | 380 |
using UnityEngine;
using System.Collections;
public class Tool : Item{
public Metal material;
public double speedWithTool;
public double wearPercent;
public bool isMiningTool, isConstructionTool, isDeconstructionTool;
public Tool(int nx, int ny, int nz){
isMiningTool = false;
isConstructionTool = false;
isDeconstructionTool = false;
x = nx;
y = ny;
z = nz;
Controller.addUnusedTool(this);
}
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
}
| 100-degrees-celsius | Jobs and Robots/Items/Equipment and Tools/Tool.cs | C# | gpl3 | 539 |
using UnityEngine;
using System.Collections;
public class Item : MonoBehaviour{
public int x, y, z;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
}
| 100-degrees-celsius | Jobs and Robots/Items/Item.cs | C# | gpl3 | 223 |
using UnityEngine;
using System.Collections;
public class Material : MonoBehaviour {
public bool isCoal;
// Use this for initialization
void Start () {
isCoal = false;
}
// Update is called once per frame
void Update () {
}
}
| 100-degrees-celsius | Jobs and Robots/Items/Materials/Material.cs | C# | gpl3 | 244 |
using UnityEngine;
using System.Collections;
public class Brass : Metal {
public Brass(){
weightModifier = 4;
strengthModifier = 2;
corrosionResistance = 4;
workSpeedModifier = 4;
}
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
}
| 100-degrees-celsius | Jobs and Robots/Items/Materials/Brass.cs | C# | gpl3 | 314 |
using UnityEngine;
using System.Collections;
public class Steel : Metal {
public Steel(){
weightModifier = 2;
strengthModifier = 6;
corrosionResistance = 2;
workSpeedModifier = 9;
}
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
}
| 100-degrees-celsius | Jobs and Robots/Items/Materials/Steel.cs | C# | gpl3 | 314 |
using UnityEngine;
using System.Collections;
public class Metal : Material{
public double strengthModifier;
public double workSpeedModifier;
public double corrosionResistance;
public double weightModifier;
public bool isAluminum, isBrass, isBronze, isCopper, isGalvanizedSteel, isIron, isSteel;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
}
| 100-degrees-celsius | Jobs and Robots/Items/Materials/Metal.cs | C# | gpl3 | 424 |
using UnityEngine;
using System.Collections;
public class GalvanizedSteel : Metal {
public GalvanizedSteel(){
weightModifier = 2;
strengthModifier = 7;
corrosionResistance = 6;
workSpeedModifier = 15;
}
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
}
| 100-degrees-celsius | Jobs and Robots/Items/Materials/GalvanizedSteel.cs | C# | gpl3 | 335 |
using UnityEngine;
using System.Collections;
public class Aluminum : Metal {
public Aluminum(){
weightModifier = 1;
strengthModifier = 4;
corrosionResistance = 5;
workSpeedModifier = 10;
}
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
}
| 100-degrees-celsius | Jobs and Robots/Items/Materials/Aluminum.cs | C# | gpl3 | 321 |
using UnityEngine;
using System.Collections;
public class Iron : Metal {
public Iron(){
weightModifier = 2.5;
strengthModifier = 4;
corrosionResistance = 1;
workSpeedModifier = 6.5;
}
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
}
| 100-degrees-celsius | Jobs and Robots/Items/Materials/Iron.cs | C# | gpl3 | 316 |
using UnityEngine;
using System.Collections;
public class Copper : Metal {
public Copper(){
workSpeedModifier = 2;
strengthModifier = 1;
corrosionResistance = 3;
weightModifier = 6;
}
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
}
| 100-degrees-celsius | Jobs and Robots/Items/Materials/Copper.cs | C# | gpl3 | 316 |
using UnityEngine;
using System.Collections;
public class Bronze : Metal{
public Bronze(){
weightModifier = 5;
strengthModifier = 5;
corrosionResistance = 3.5;
workSpeedModifier = 3;
}
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
}
| 100-degrees-celsius | Jobs and Robots/Items/Materials/Bronze.cs | C# | gpl3 | 317 |
using UnityEngine;
using System.Collections;
public class Coal : Material {
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
}
| 100-degrees-celsius | Jobs and Robots/Items/Materials/Coal.cs | C# | gpl3 | 196 |
using UnityEngine;
using System.Collections;
public class Bar : Item {
Material material;
public Bar(Material nmaterial){
material = nmaterial;
}
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
}
| 100-degrees-celsius | Jobs and Robots/Items/Bars/Bar.cs | C# | gpl3 | 275 |
using UnityEngine;
using System;
using System.Collections;
public class Robot : MonoBehaviour {
Job currentJob;
bool hasAJob;
double pressureInTank;
bool addedStatustoList;
bool atJobSite;
double x, y, z;
int jobX, jobY, jobZ;
private ArrayList path;
private int pathIndex;
Point nextPoint;
double rateOfMovement;
public bool hasMiningTool, hasConstructionTool, hasDeconstructionTool;
public double rateOfConstruction, rateOfDeconstruction, rateOfMining;
public ArrayList tools, miningTools, constructionTools, deconstructionTools;
public Item hauledItem;
// Use this for initialization
void Start () {
hasAJob = false;
currentJob = null;
pressureInTank = 10000;
nextPoint = new Point(0,0,0);
hasMiningTool = false;
hasConstructionTool = false;
hasDeconstructionTool = false;
rateOfConstruction = 1;
rateOfMining = 1;
rateOfDeconstruction = 1;
tools = new ArrayList();
miningTools = new ArrayList();
constructionTools = new ArrayList();
deconstructionTools = new ArrayList();
}
// Update is called once per frame
void Update () {
if (!hasAJob){
if (pressureInTank < 500){
addedStatustoList = true;
//refill with steam
}
if (!hasConstructionTool | !hasDeconstructionTool | !hasMiningTool){
if (!hasConstructionTool){
foreach (Tool t in Controller.getUnusedTools()){
if ((t.isConstructionTool) & (!addedStatustoList)){
addedStatustoList = true;
currentJob = new EquipJob(t, t.x, t.y, t.z);
}
}
} if (!hasDeconstructionTool){
foreach (Tool t in Controller.getUnusedTools()){
if ((t.isDeconstructionTool) & (!addedStatustoList)){
addedStatustoList = true;
currentJob = new EquipJob(t, t.x, t.y, t.z);
}
}
} if (!hasMiningTool){
foreach (Tool t in Controller.getUnusedTools()){
if ((t.isMiningTool) & (!addedStatustoList)){
addedStatustoList = true;
assignJob(new EquipJob(t, t.x, t.y, t.z));
}
}
}
}
if (!addedStatustoList){
addedStatustoList = true;
Controller.addRobot(this);
print ("Data transmitted");
}
} if (atJobSite & hasAJob){
bool done = false;
if (currentJob.jobType == 1){
done = ((BuildingOperationJob)(currentJob)).workOn(1, this);
} else if (currentJob.jobType == 2){
done = ((ConstructionJob)(currentJob)).workOn(1, this);
} else if (currentJob.jobType == 3){
done = ((DeconstructionJob)(currentJob)).workOn(1, this);
} else if (currentJob.jobType == 4) {
done = ((EquipJob)(currentJob)).workOn(this);
done = true;
} else if (currentJob.jobType == 5){
done = ((HaulingJob)(currentJob)).workOn(1, this);
} else if (currentJob.jobType == 6){
done = ((MiningJob)(currentJob)).workOn(1, this);
} else {
print ("Snork");
}
//print (currentJob.percentageComplete);
if (done){
Controller.finishedJob(this, currentJob);
currentJob = null;
hasAJob = false;
addedStatustoList = false;
Debug.Log("Done with Job");
}
}
if (hasAJob & !atJobSite){
rateOfMovement = 0;
foreach (Tool t in tools){
rateOfMovement += (float)(t.material.weightModifier);
}
rateOfMovement = (0.05 / (rateOfMovement + 1));
//Debug.Log(rateOfMovement);
nextPoint = (Point)(path[pathIndex]);
bool goodToMoveOn = true;
pathTo(nextPoint.x, nextPoint.y, nextPoint.z, rateOfMovement);
if((int)(x) != nextPoint.x){
goodToMoveOn = false;
//Debug.Log (x);
} else if((int)(y) != nextPoint.y){
goodToMoveOn = false;
//Debug.Log(y);
} else if((int)(z)!= nextPoint.z){
goodToMoveOn = false;
//Debug.Log(z);
}
if (goodToMoveOn){
pathIndex += 1;
}
if (((int)x == jobX) & ((int)y == jobY) & ((int)z == jobZ)){
x = (int) x;
y = (int) y;
z = (int) z;
atJobSite = true;
pathIndex = 0;
}
}
}
public void addConstructionTool(ConstructionTool tool){
hasConstructionTool = true;
rateOfConstruction = tool.speedWithTool;
tools.Add (tool);
constructionTools.Add (tool);
}
public void addDeconstructionTool(DeconstructionTool tool){
hasDeconstructionTool = true;
rateOfDeconstruction = tool.speedWithTool;
tools.Add(tool);
deconstructionTools.Add (tool);
}
public void addMiningTool(MiningTool tool){
hasMiningTool = true;
rateOfMining = tool.speedWithTool;
tools.Add (tool);
miningTools.Add (tool);
}
public void assignJob(Job j){
print ("Job Assigned");
currentJob = j;
hasAJob = true;
atJobSite = false;
jobX = j.x;
jobY = j.y;
jobZ = j.z;
z = jobZ;
path = generatePath(new Point((int)(x), (int)(y), (int)(z)), new Point((int)(jobX), (int)(jobY), (int)(jobZ)));
}
ArrayList generatePath(Point startLoc, Point goalLoc){
ArrayList open = new ArrayList();
ArrayList attemptingPath = new ArrayList();
ArrayList triedPoints = new ArrayList();
open.Add(startLoc);
attemptingPath.Add(startLoc);
Point pointToTry = startLoc;
Point bestSoFar = startLoc;
while (!pointToTry.isEqualTo(goalLoc)){
// Generates points next to current one
Point[] adjacentpoints = pointToTry.getAdjacentPoints();
// Finds one with lowest cost, and goes from there
for (int i = 0; i < 7; i++){
if (adjacentpoints[i].getFCost(goalLoc) < bestSoFar.getFCost(goalLoc) + 1){
if ((!adjacentpoints[i].occupied)&(!triedPoints.Contains(adjacentpoints[i]))){
bestSoFar = adjacentpoints[i];
}
}
}
if (pointToTry.isEqualTo(startLoc)){
attemptingPath = null;
attemptingPath = new ArrayList();
} else {
triedPoints.Add(bestSoFar);
}
pointToTry = bestSoFar;
attemptingPath.Add(pointToTry);
}
return attemptingPath;
}
void pathTo(int pathX, int pathY, int pathZ, double travelSpeed){
if (!(x == pathX & y == pathY & z == pathZ)) {
if (x < pathX){
x += travelSpeed;
} else if (x > pathX){
x -= travelSpeed;
}
if (y < pathY){
y += travelSpeed;
} else if (y > pathY){
y -= travelSpeed;
}
if (z < pathZ){
z += travelSpeed;
} else if (z > pathZ){
z -= travelSpeed;
}
}
transform.position = new Vector3((float)x, (float)y, (float)z);
}
public Point getPostion(){
Point p = new Point((int)(x), (int)(y), (int)(z));
return p;
}
}
| 100-degrees-celsius | Jobs and Robots/Robots/Robot.cs | C# | gpl3 | 6,356 |
using UnityEngine;
using System.Collections;
public class Point {
public int x, y, z;
public Point parent;
public bool occupied;
public Point(int nx, int ny, int nz){
x = nx;
y = ny;
z = nz;
parent = null;
}
public Point(int nx, int ny, int nz, Point nparent){
x = nx;
y = ny;
z = nz;
parent = nparent;
}
public int getFCost(Point endPoint){
int fCost = 0;
fCost = getMovementCost() + getHeuristicCost(endPoint);
return fCost;
}
public int getMovementCost(){
int cost = 0;
if (parent == null){
return cost;
} else{
if (parent.x != x & parent.y != y){
cost = 14 + parent.getMovementCost();
} else {
cost = 10 + parent.getMovementCost();
}
}
return cost;
}
public int getHeuristicCost(Point endPoint){
int cost = 0;
int distanceX = Mathf.Abs(endPoint.x - this.x);
int distanceY = Mathf.Abs(endPoint.y - this.y);
cost = (distanceX + distanceY) * 10;
return cost;
}
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
public bool isEqualTo(Point point){
if ((this.x == point.x) & (this.y == point.y) & (this.z == point.z)){
return true;
} else {
return false;
}
}
public Point[] getAdjacentPoints(){
Point[] adjacentPoints = {new Point(x+1, y, z, this), new Point(x+1, y+1, z, this),
new Point(x+1, y-1, z, this), new Point(x-1, y, z, this), new Point(x-1, y+1, z, this),
new Point(x-1, y-1, z, this), new Point(x, y-1, z, this), new Point(x, y+1, z, this)
};
return adjacentPoints;
}
}
| 100-degrees-celsius | Jobs and Robots/Robots/Point.cs | C# | gpl3 | 1,591 |
using UnityEngine;
using System.Collections;
public class Follower : MonoBehaviour {
private float x, y, z;
public float rotationX, rotationY, rotationZ;
bool madeTool = false;
// Use this for initialization
void Start () {
Controller.Start();
}
// Update is called once per frame
void Update () {
Controller.Update();
ConstructionController.Update();
if (Input.GetKey(KeyCode.UpArrow)){
y += 1;
} else if (Input.GetKey(KeyCode.DownArrow)){
y -= 1;
} else if (Input.GetKey(KeyCode.RightArrow)){
x += 1;
} else if (Input.GetKey(KeyCode.LeftArrow)){
x -= 1;
} else if (Input.GetKey(KeyCode.A)){
rotationY += 1;
} else if (Input.GetKey(KeyCode.D)){
rotationY -= 1;
} else if (Input.GetKey(KeyCode.W)){
rotationX += 1;
} else if (Input.GetKey(KeyCode.S)){
rotationX -= 1;
} else if (Input.GetKey(KeyCode.Z)){
rotationZ += 1;
} else if (Input.GetKey(KeyCode.X)){
rotationZ -= 1;
} else if (Input.GetKey(KeyCode.Space)){
if (!madeTool){
EquipJob j = new EquipJob(new MiningTool(new GalvanizedSteel(), 5, 0, 15), 5, 0, 15);
Controller.addJob(j);
madeTool = true;
}
}
z += ((Input.GetAxis("Mouse ScrollWheel")));
transform.position = getVector();
transform.Rotate(rotationX, rotationY, rotationZ);
rotationX = 0;
rotationY = 0;
rotationZ = 0;
}
public Vector3 getVector(){
Vector3 vector = new Vector3(x, y, z);
return vector;
}
}
| 100-degrees-celsius | Jobs and Robots/Camera Stuff/Follower.cs | C# | gpl3 | 1,459 |
using UnityEngine;
using System.Collections;
public class WorkshopManager : MonoBehaviour {
bool clicked;
// Use this for initialization
void Start () {
clicked = false;
}
// Update is called once per frame
void Update () {
}
void OnMouseUp(){
Debug.Log("Job Created");
//ReactionJob job = new ReactionJob((int) transform.position.x, (int) transform.position.y,
//(int) transform.position.z, 0);
//new TrackConstructionJob(-3, 0, 15, 3, 0, 15);
clicked = true;
}
}
| 100-degrees-celsius | Jobs and Robots/Infrastructure/Buildings/Workshops/WorkshopManager.cs | C# | gpl3 | 502 |
using UnityEngine;
using System.Collections;
public static class ConstructionController {
static int startX, startY, startZ;
static int endX, endY, endZ;
static bool firstCoordsAssigned;
public static void Update(){
if (Input.GetMouseButtonDown(0)){
if (!firstCoordsAssigned){
startX = (int)(Input.mousePosition.x);
startY = (int)(Input.mousePosition.y);
startZ = (int)(Input.mousePosition.z);
firstCoordsAssigned = true;
} else {
endX = (int)(Input.mousePosition.x);
endY = (int)(Input.mousePosition.y);
endZ = (int)(Input.mousePosition.z);
firstCoordsAssigned = false;
new TrackConstructionJob(startX, startY, startZ, endX, endY, endZ);
Debug.Log("sX: " +startX + " sY: " + startY + " sZ: " + startZ +
" eX: " +endX + " eY: " + endY + " eZ: " + endZ);
}
}
}
}
| 100-degrees-celsius | Jobs and Robots/Infrastructure/ConstructionController.cs | C# | gpl3 | 856 |
using UnityEngine;
using System.Collections;
public class Cart : MonoBehaviour {
public Terminal startTerminal {get; set;}
//This doesn't work. It is supposed to check if the cart is colliding with the target terminal (or any terminal right now) and slow it down if so,
// but the collision isn't being passed up from the wheels to the top-level of the cart.
void OnTriggerStay(Collider other) {
Terminal terminal = (other.gameObject.transform.parent.GetComponentInChildren<Terminal>() as Terminal);
if (terminal != null)
{
rigidbody.velocity = Vector3.Lerp (rigidbody.velocity, Vector3.zero, 0.1f/Vector3.Distance(transform.position, terminal.coord));
if(rigidbody.velocity.magnitude < 1 && Vector3.Distance(transform.position, terminal.coord) < 5)
{
rigidbody.constraints = RigidbodyConstraints.FreezeAll;
}
}
}
}
| 100-degrees-celsius | Mine Carts test/Mine Carts test/Assets/Mine Carts/Cart.cs | C# | gpl3 | 856 |
using UnityEngine;
using System.Collections;
public class EquipJob : Job {
Tool tool;
public EquipJob(Tool t, int nstartX, int nstartY, int nstartZ):base(nstartX, nstartY, nstartZ, 4){
tool = t;
}
public bool workOn(Robot robot){
robot.tools.Add(tool);
percentageComplete = 200;
if (tool.isConstructionTool){
robot.addConstructionTool((ConstructionTool)(tool));
robot.hasConstructionTool = true;
} else if (tool.isDeconstructionTool){
robot.addDeconstructionTool((DeconstructionTool)(tool));
robot.hasDeconstructionTool = true;
} else if (tool.isMiningTool){
robot.addMiningTool((MiningTool)(tool));
robot.hasMiningTool = true;
}
bool isDone = base.workOn(1, robot);
Controller.removeTool(tool);
return true;
}
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
}
| 100-degrees-celsius | Mine Carts test/Mine Carts test/Assets/Jobs/EquipJob.cs | C# | gpl3 | 885 |
using UnityEngine;
using System.Collections;
public class HaulingJob : Job {
GameObject item;
Item realItem;
int haulingToX, haulingToY, haulingToZ;
public PlacingJob j;
Job jobAtEnd;
public HaulingJob(Item nitem, int endX, int endY, int endZ):base((int)nitem.transform.position.x, (int)nitem.transform.position.y, (int)nitem.transform.position.z, 5){
item = nitem.item;
realItem = nitem;
haulingToX = endX;
haulingToY = endY;
haulingToZ = endZ;
}
public HaulingJob(Item nitem, int endX, int endY, int endZ, Job nendJob):base((int)nitem.transform.position.x, (int)nitem.transform.position.y, (int)nitem.transform.position.z, 5){
Controller.removeJob(this);
item = nitem.item;
realItem = nitem;
haulingToX = endX;
haulingToY = endY;
haulingToZ = endZ;
jobAtEnd = nendJob;
}
public bool workOn(Robot robot){
//Debug.Log ("At site");
robot.hauledItem = realItem;
PlacingJob endJob;
try {
endJob = new PlacingJob(haulingToX, haulingToY, haulingToZ, jobAtEnd);
} catch {
endJob = new PlacingJob(haulingToX, haulingToY, haulingToZ);
}
endJob.percentageComplete = 101;
robot.assignJob(endJob, true);
robot.hauling = true;
j = endJob;
return false;
}
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
}
| 100-degrees-celsius | Mine Carts test/Mine Carts test/Assets/Jobs/HaulingJob.cs | C# | gpl3 | 1,337 |
using UnityEngine;
using System.Collections;
public class ConstructionJob : Job {
public ConstructionJob(int nstartX, int nstartY, int nstartZ):base(nstartX, nstartY, nstartZ, 2){
}
public bool workOn(double workspeed, Robot robot){
bool isDone = base.workOn(workspeed, robot);
double amount = workspeed * (robot.rateOfConstruction);
percentageComplete += amount;
robot.constructionTool.wearPercent += 0.001/robot.constructionTool.material.strengthModifier;
if (robot.constructionTool.wearPercent > 100){
robot.tools.Remove(robot.constructionTool);
GameObject.Destroy(robot.constructionTool.item);
robot.constructionTool = null;
robot.hasConstructionTool = false;
}
return isDone;
}
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
}
| 100-degrees-celsius | Mine Carts test/Mine Carts test/Assets/Jobs/Construction Jobs/ConstructionJob.cs | C# | gpl3 | 851 |
using UnityEngine;
using System.Collections;
public class TrackConstructionJob : ConstructionJob {
int startX, startY, startZ;
int endX, endY, endZ;
public TrackConstructionJob(int nstartX, int nstartY, int nstartZ, int nendX, int nendY, int nendZ)
:base(nstartX, nstartY, nstartZ)
{
startX = nstartX;
startY = nstartY;
startZ = nstartZ;
endX = nendX;
endY = nendY;
endZ = nendZ;
}
public bool workOn(double workspeed, Robot robot){
bool isDone = base.workOn(workspeed, robot);
if (isDone){
SplineControlPoint[] points = new SplineControlPoint[3];
points[0] = new SplineControlPoint(new Vector3((float) (startX), (float)(startY), (float)(startZ)),
new Vector3(-1,-1,-1), new float[] {50, 50});
points[1] = new SplineControlPoint(new Vector3((float)(endX), (float)(endY), (float)(endZ)),
new Vector3(-1,-1,-1), new float[] {50, 50});
Spline3D[] trackSections = TrackFactory.genTrack(points, TrackFactory.rail);
}
return isDone;
}
}
| 100-degrees-celsius | Mine Carts test/Mine Carts test/Assets/Jobs/Construction Jobs/TrackConstructionJob.cs | C# | gpl3 | 1,006 |
using UnityEngine;
using System.Collections;
public class MiningJob : Job {
public MiningJob(int nstartX, int nstartY, int nstartZ):base(nstartX, nstartY, nstartZ, 6){
}
public bool workOn(double workspeed, Robot robot){
bool isDone = base.workOn(workspeed, robot);
double amount = workspeed * (robot.rateOfMining);
percentageComplete += amount;
try {
robot.miningTool.wearPercent += 0.001/robot.miningTool.material.strengthModifier;
if (robot.miningTool.wearPercent > 100){
robot.tools.Remove(robot.miningTool);
GameObject.Destroy(robot.miningTool.item);
robot.miningTool = null;
robot.hasMiningTool = false;
}
} catch {
}
if (isDone){
GameObject obj = (GameObject) GameObject.Instantiate(UnityEngine.Resources.Load("OrePrefab"));
obj.transform.position = new Vector3(x, y + 3, z + 3);
//ItemList.ores.Add(obj);
Ore r = (Ore)obj.GetComponent("Ore");
r.item = obj;
int randNum = Random.Range(0, 5);
Material mat;
if (randNum == 0){
mat = new Iron();
} else if (randNum == 1){
mat = new Tin();
} else if (randNum == 2){
mat = new Copper();
} else if (randNum == 3){
mat = new Zinc();
} else if (randNum == 4){
mat = new Aluminum();
} else {
mat = new Iron();
Debug.Log (randNum);
}
r.starterate(mat);
Debug.Log (mat.GetType().ToString());
}
return isDone;
}
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
}
| 100-degrees-celsius | Mine Carts test/Mine Carts test/Assets/Jobs/MiningJob.cs | C# | gpl3 | 1,523 |
using UnityEngine;
using System.Collections;
public static class Controller{
private static ArrayList unassignedJobs;
private static ArrayList idlingRobots;
private static ArrayList unusedTools;
// Use this for initialization
public static void Start () {
unassignedJobs = null;
idlingRobots = null;
unassignedJobs = new ArrayList();
idlingRobots = new ArrayList();
unusedTools = new ArrayList();
}
// Update is called once per frame
public static void Update () {
if ((int)(idlingRobots.Count) != 0){
if (unassignedJobs.Count != 0){
Robot bestRobot = (Robot)(idlingRobots[0]);
Job jobToBeAssigned = (Job) (unassignedJobs[0]);
int bestCost = getCostOf(bestRobot, jobToBeAssigned);;
foreach(Robot rob in idlingRobots){
if ((getCostOf(rob, jobToBeAssigned)) < bestCost){
bestCost = getCostOf(rob, jobToBeAssigned);
bestRobot = rob;
}
}
bestRobot.assignJob(jobToBeAssigned);
unassignedJobs.Remove(jobToBeAssigned);
idlingRobots.Remove(bestRobot);
}
}
}
public static void addJob(Job j){
unassignedJobs.Add(j);
}
public static void addRobot(Robot r){
idlingRobots.Add (r);
}
public static void finishedJob(Robot r, Job j){
try {
idlingRobots.Add(r);
} catch {
}
}
public static void removeRobot(Robot robot){
idlingRobots.Remove(robot);
}
public static ArrayList getUnusedTools(){
return unusedTools;
}
public static void addUnusedTool(Tool t){
unusedTools.Add(t);
}
public static void removeTool(Tool t){
unusedTools.Remove(t);
}
public static int getCostOf(Robot robot, Job job){
int cost = 0;
Point robotPoint = robot.getPostion();
cost += Mathf.Abs(robotPoint.x - job.x);
cost += Mathf.Abs(robotPoint.y - job.y);
cost += Mathf.Abs(robotPoint.z - job.z);
if (job.jobType == 2){
cost -= (int)(3 * (robot.rateOfConstruction));
} else if (job.jobType == 3){
cost -= (int)(3 * (robot.rateOfDeconstruction));
} else if (job.jobType == 6){
cost -= (int)(3 * (robot.rateOfMining));
}
return cost;
}
public static void removeJob(Job j){
unassignedJobs.Remove(j);
}
}
| 100-degrees-celsius | Mine Carts test/Mine Carts test/Assets/Jobs/Controller.cs | C# | gpl3 | 2,158 |
using UnityEngine;
using System.Collections;
public class SmeltOre : SmeltingJob {
Ore ore;
bool hauled;
bool haulingStarted;
HaulingJob h;
public SmeltOre(int nx, int ny, int nz, Ore nore):base(nx, ny, nz){
ore = nore;
jobType = 8;
hauled = false;
haulingStarted = false;
h = new HaulingJob(ore, x, y, z, this);
Material material = ore.material;
if ((material.GetType()).ToString() == "Aluminum"){
ItemList.aluminumOre.Remove(ore);
jobLabel = "Smelt Aluminum Ore";
} else if ((material.GetType()).ToString() == "Copper"){
ItemList.copperOre.Remove(ore);
jobLabel = "Smelt Copper Ore";
} else if ((material.GetType()).ToString() == "Iron"){
ItemList.ironOre.Remove(ore);
jobLabel = "Smelt Iron Ore";
} else if ((material.GetType()).ToString() == "Tin"){
ItemList.tinOre.Remove(ore);
jobLabel = "Smelt Tin Ore";
} else if ((material.GetType()).ToString() == "Zinc"){
ItemList.zincOre.Remove(ore);
jobLabel = "Smelt Zinc Ore";
} else {
Debug.LogError (material.GetType());
}
}
public bool workOn(double workspeed, Robot robot){
bool isDone = false;
try {
hauled = h.j.complete;
} catch {
hauled = false;
}
if (hauled){
isDone = base.workOn(workspeed, robot);
} else {
if (!haulingStarted){
robot.assignJob(h, true);
haulingStarted = true;
}
}
if (isDone){
GameObject.Destroy(ore.item);
GameObject obj = (GameObject)GameObject.Instantiate(UnityEngine.Resources.Load("BarPrefab"));
obj.transform.position = new Vector3(0f, 0f, 20f);
Bar b = (Bar)obj.GetComponent("Bar");
b.item = obj;
b.starterate(ore.material);
}
return isDone;
}
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
}
| 100-degrees-celsius | Mine Carts test/Mine Carts test/Assets/Jobs/Building Operation Jobs/Smelting/SmeltOre.cs | C# | gpl3 | 1,818 |
using UnityEngine;
using System.Collections;
public class SmeltBronze : SmeltAlloy {
Bar copperBar;
Bar tinBar;
bool hauled;
bool haulingStarted;
HaulingJob copperHauling;
HaulingJob tinHauling;
public SmeltBronze(int nx, int ny, int nz, Bar ntinBar, Bar ncopperBar):base(nx, ny, nz){
jobType = 10;
copperBar = ncopperBar;
tinBar = ntinBar;
hauled = false;
haulingStarted = false;
copperHauling = new HaulingJob(copperBar, x, y, z, this);
tinHauling = new HaulingJob(tinBar, x, y, z, copperHauling);
ItemList.copperBars.Remove(copperBar);
ItemList.tinBars.Remove(tinBar);
jobLabel = "Smelt Bronze";
}
public bool workOn(double workspeed, Robot robot){
bool isDone = false;
try {
hauled = copperHauling.j.complete;
} catch {
hauled = false;
}
if (hauled){
isDone = base.workOn(workspeed, robot);
} else {
if (!haulingStarted){
robot.assignJob(tinHauling, true);
haulingStarted = true;
Debug.Log ("Sure thing");
}
}
if (isDone){
GameObject.Destroy(copperBar.item);
GameObject.Destroy(tinBar.item);
GameObject obj = (GameObject)GameObject.Instantiate(UnityEngine.Resources.Load("BarPrefab"));
obj.transform.position = new Vector3(0f, 0f, 20f);
Bar b = (Bar)obj.GetComponent("Bar");
b.item = obj;
b.starterate(new Bronze());
}
return isDone;
}
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
}
| 100-degrees-celsius | Mine Carts test/Mine Carts test/Assets/Jobs/Building Operation Jobs/Smelting/SmeltBronze.cs | C# | gpl3 | 1,494 |
using UnityEngine;
using System.Collections;
public class SmeltSteel : SmeltAlloy {
public SmeltSteel(int nx, int ny, int nz):base(nx,ny,nz){
}
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
}
| 100-degrees-celsius | Mine Carts test/Mine Carts test/Assets/Jobs/Building Operation Jobs/Smelting/SmeltSteel.cs | C# | gpl3 | 267 |
using UnityEngine;
using System.Collections;
public class SmeltAlloy : SmeltingJob {
public SmeltAlloy(int nx, int ny, int nz):base(nx, ny, nz){
}
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
}
| 100-degrees-celsius | Mine Carts test/Mine Carts test/Assets/Jobs/Building Operation Jobs/Smelting/SmeltAlloy.cs | C# | gpl3 | 274 |
using UnityEngine;
using System.Collections;
public class SmeltBrass : SmeltAlloy {
Bar copperBar;
Bar zincBar;
bool hauled;
bool haulingStarted;
HaulingJob copperHauling;
HaulingJob zincHauling;
public SmeltBrass(int nx, int ny, int nz, Bar nzincBar, Bar ncopperBar):base(nx, ny, nz){
jobType = 11;
copperBar = ncopperBar;
zincBar = nzincBar;
hauled = false;
haulingStarted = false;
copperHauling = new HaulingJob(copperBar, x, y, z, this);
zincHauling = new HaulingJob(zincBar, x, y, z, copperHauling);
ItemList.copperBars.Remove(copperBar);
ItemList.zincBars.Remove(zincBar);
jobLabel = "Smelt Brass";
}
public bool workOn(double workspeed, Robot robot){
bool isDone = false;
try {
hauled = copperHauling.j.complete;
} catch {
hauled = false;
}
if (hauled){
isDone = base.workOn(workspeed, robot);
} else {
if (!haulingStarted){
robot.assignJob(zincHauling, true);
haulingStarted = true;
Debug.Log ("Sure thing");
}
}
if (isDone){
GameObject.Destroy(zincBar.item);
GameObject.Destroy(copperBar.item);
GameObject obj = (GameObject)GameObject.Instantiate(UnityEngine.Resources.Load("BarPrefab"));
obj.transform.position = new Vector3(0f, 0f, 20f);
Bar b = (Bar)obj.GetComponent("Bar");
b.item = obj;
b.starterate(new Brass());
}
return isDone;
}
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
}
| 100-degrees-celsius | Mine Carts test/Mine Carts test/Assets/Jobs/Building Operation Jobs/Smelting/SmeltBrass.cs | C# | gpl3 | 1,501 |
using UnityEngine;
using System.Collections;
public class SmeltGalvanizedSteel : SmeltAlloy {
Bar steelBar;
Bar zincBar;
bool hauled;
bool haulingStarted;
HaulingJob steelHauling;
HaulingJob zincHauling;
public SmeltGalvanizedSteel(int nx, int ny, int nz, Bar nzincBar, Bar nsteelBar):base(nx, ny, nz){
jobType = 12;
steelBar = nsteelBar;
zincBar = nzincBar;
hauled = false;
haulingStarted = false;
steelHauling = new HaulingJob(steelBar, x, y, z, this);
zincHauling = new HaulingJob(zincBar, x, y, z, steelHauling);
ItemList.steelBars.Remove(steelBar);
ItemList.zincBars.Remove(zincBar);
jobLabel = "Smelt Galvanized Steel";
}
public bool workOn(double workspeed, Robot robot){
bool isDone = false;
try {
hauled = steelHauling.j.complete;
} catch {
hauled = false;
}
if (hauled){
isDone = base.workOn(workspeed, robot);
} else {
if (!haulingStarted){
robot.assignJob(zincHauling, true);
haulingStarted = true;
Debug.Log ("Sure thing");
}
}
if (isDone){
GameObject.Destroy(zincBar.item);
GameObject.Destroy(steelBar.item);
GameObject obj = (GameObject)GameObject.Instantiate(UnityEngine.Resources.Load("BarPrefab"));
obj.transform.position = new Vector3(0f, 0f, 20f);
Bar b = (Bar)obj.GetComponent("Bar");
b.item = obj;
b.starterate(new Brass());
}
return isDone;
}
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
}
| 100-degrees-celsius | Mine Carts test/Mine Carts test/Assets/Jobs/Building Operation Jobs/Smelting/SmeltGalvanizedSteel.cs | C# | gpl3 | 1,520 |
using UnityEngine;
using System.Collections;
public class SmeltingJob : BuildingOperationJob {
public SmeltingJob(int nx, int ny, int nz):base(nx, ny, nz){
}
public bool workOn(double workspeed, Robot robot){
bool isDone = base.workOn(workspeed, robot);
return isDone;
}
}
| 100-degrees-celsius | Mine Carts test/Mine Carts test/Assets/Jobs/Building Operation Jobs/Smelting/SmeltingJob.cs | C# | gpl3 | 289 |
using UnityEngine;
using System.Collections;
public class RechargingJob : BuildingOperationJob {
public RechargingJob(BoilerManager nBoiler):base((int) nBoiler.transform.position.x, (int) nBoiler.transform.position.y, (int) nBoiler.transform.position.z){
this.jobType = 7;
}
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
public bool workOn(Robot robot){
bool isDone = base.workOn(1, robot);
if (isDone){
Debug.Log("Yup");
robot.pressureInTank = robot.tank.maxPressure;
}
return isDone;
}
}
| 100-degrees-celsius | Mine Carts test/Mine Carts test/Assets/Jobs/Building Operation Jobs/RechargingJob.cs | C# | gpl3 | 589 |
using UnityEngine;
using System.Collections;
public class AssembleRobot : BuildingOperationJob {
RobotComponent arms, legs, head, torso, tank;
HaulingJob[] jobs;
bool hauled;
bool haulingStarted;
public AssembleRobot(int nx, int ny, int nz, Arms narms, Legs nlegs, Head nhead, Torso ntorso, Tank ntank):base(nx, ny, nz){
arms = narms;
legs = nlegs;
torso = ntorso;
head = nhead;
tank = ntank;
hauled = false;
haulingStarted = false;
jobs = new HaulingJob[5];
jobs[0] = new HaulingJob(arms, x, y, z, this);
jobs[1] = new HaulingJob(legs, x, y, z, jobs[0]);
jobs[2] = new HaulingJob(torso, x, y, z, jobs[1]);
jobs[3] = new HaulingJob(head, x, y, z,jobs[2]);
jobs[4] = new HaulingJob(tank, x, y, z, jobs[3]);
ItemList.heads.Remove(head);
ItemList.arms.Remove(arms);
ItemList.legs.Remove(legs);
ItemList.torsos.Remove(torso);
ItemList.tanks.Remove(tank);
jobLabel = "Assemble Robot";
}
public bool workOn(double workspeed, Robot robot){
bool isDone = false;
try {
hauled = jobs[0].j.complete;
} catch {
hauled = false;
}
if (hauled){
isDone = base.workOn(workspeed, robot);
} else {
if (!haulingStarted){
haulingStarted = true;
robot.assignJob(jobs[4], true);
}
}
if (isDone){
GameObject.DestroyObject(arms.item);
GameObject.DestroyObject(legs.item);
GameObject.DestroyObject(head.item);
GameObject.DestroyObject(torso.item);
GameObject.DestroyObject(tank.item);
GameObject obj = (GameObject)GameObject.Instantiate(UnityEngine.Resources.Load("RobotPrefab"));
obj.transform.position = new Vector3(x, y, z);
Robot r = (Robot)obj.GetComponent("Robot");
r.starterate((Arms)arms, (Legs)legs, (Head)head, (Torso)torso, (Tank)tank);
}
return isDone;
}
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
}
| 100-degrees-celsius | Mine Carts test/Mine Carts test/Assets/Jobs/Building Operation Jobs/Assembly jobs/AssembleRobot.cs | C# | gpl3 | 1,922 |
using UnityEngine;
using System.Collections;
public class ForgeRobotComponents : BuildingOperationJob {
Bar bar;
Metal material;
int ftype; //0 = head, 1 = arms, 2 = legs, 3 = torso, 4 = tank, 5 = mining tool, 6 = construction tool, 7 = deconstruction tool
bool hauled;
bool haulingStarted;
HaulingJob h;
public ForgeRobotComponents(Bar nbar, int nx, int ny, int nz, int nftype):base(nx, ny, nz){
bar = nbar;
material = (Metal)bar.getMaterial();
ftype = nftype;
if (ftype < 0 | ftype > 7){
ftype = 0;
}
jobType = 14;
hauled = false;
haulingStarted = false;
h = new HaulingJob(bar, x, y, z, this);
if ((material.GetType()).ToString() == "Aluminum"){
ItemList.aluminumBars.Remove(bar);
} else if ((material.GetType()).ToString() == "Copper"){
ItemList.copperBars.Remove(bar);
} else if ((material.GetType()).ToString() == "Iron"){
ItemList.ironBars.Remove(bar);
} else if ((material.GetType()).ToString() == "Steel"){
ItemList.steelBars.Remove(bar);
} else if ((material.GetType()).ToString() == "GalvanizedSteel"){
ItemList.galvanizedSteelBars.Remove(bar);
} else if ((material.GetType()).ToString() == "Brass"){
ItemList.brassBars.Remove(bar);
} else if ((material.GetType()).ToString() == "Bronze"){
ItemList.bronzeBars.Remove(bar);
} else {
Debug.LogError (material.GetType());
}
if (ftype == 0){
jobLabel = "Forge Head";
} else if (ftype == 1){
jobLabel = "Forge Arms";
} else if (ftype == 2){
jobLabel = "Forge Legs";
} else if (ftype == 3){
jobLabel = "Forge Torso";
} else if (ftype == 4){
jobLabel = "Forge Tank";
} else if (ftype == 5){
jobLabel = "Forge Mining Tool";
} else if (ftype == 6){
jobLabel = "Forge Construction Tool";
} else if (ftype == 7){
jobLabel = "Forge Deconstruction Tool";
}
}
public bool workOn(double workspeed, Robot robot){
bool isDone = false;
try {
hauled = h.j.complete;
} catch {
hauled = false;
}
if (hauled){
isDone = base.workOn(workspeed, robot);
} else {
if (!haulingStarted){
robot.assignJob(h, true);
haulingStarted = true;
Debug.Log ("Sure thing");
}
}
if (isDone){
GameObject.Destroy(bar.item);
if (ftype == 0){
Head item;
GameObject obj = (GameObject)GameObject.Instantiate(UnityEngine.Resources.Load("HeadPrefab"));
item = (Head)obj.GetComponent("Head");
item.item = obj;
item.starterate(material);
obj.transform.position = new Vector3(x, y + 5, z + 5);
} else if (ftype == 1){
Arms item;
GameObject obj = (GameObject)GameObject.Instantiate(UnityEngine.Resources.Load("ArmsPrefab"));
item = ((Arms)obj.GetComponent("Arms"));
item.item = obj;
item.starterate(material);
obj.transform.position = new Vector3(x, y + 5, z + 5);
} else if (ftype == 2){
Legs item;
GameObject obj = (GameObject)GameObject.Instantiate(UnityEngine.Resources.Load("LegsPrefab"));
item = ((Legs)obj.GetComponent("Legs"));
item.item = obj;
item.starterate(material);
obj.transform.position = new Vector3(x, y + 5, z + 5);
} else if (ftype == 3){
Torso item;
GameObject obj = (GameObject)GameObject.Instantiate(UnityEngine.Resources.Load("TorsoPrefab"));
item = ((Torso)obj.GetComponent("Torso"));
item.item = obj;
item.starterate(material);
obj.transform.position = new Vector3(x, y + 5, z + 5);
} else if (ftype == 4){
Tank item;
GameObject obj = (GameObject)GameObject.Instantiate(UnityEngine.Resources.Load("TankPrefab"));
item = ((Tank)obj.GetComponent("Tank"));
item.item = obj;
item.starterate(material);
obj.transform.position = new Vector3(x + 5, y + 5, z);
} else if (ftype == 5){
MiningTool item;
GameObject obj = (GameObject)GameObject.Instantiate(UnityEngine.Resources.Load("MiningToolPrefab"));
item = ((MiningTool)obj.GetComponent("MiningTool"));
item.item = obj;
item.starterate(material);
obj.transform.position = new Vector3(x + 10, y + 5, z);
} else if (ftype == 6){
ConstructionTool item;
GameObject obj = (GameObject)GameObject.Instantiate(UnityEngine.Resources.Load("ConstructionToolPrefab"));
item = ((ConstructionTool)obj.GetComponent("ConstructionTool"));
item.item = obj;
item.starterate(material);
obj.transform.position = new Vector3(x, y + 5, z + 5);
} else if (ftype == 7){
DeconstructionTool item;
GameObject obj = (GameObject)GameObject.Instantiate(UnityEngine.Resources.Load("DeconstructionToolPrefab"));
item = ((DeconstructionTool)obj.GetComponent("DeconstructionTool"));
item.item = obj;
item.starterate(material);
obj.transform.position = new Vector3(x, y + 5, z + 5);
}
}
return isDone;
}
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
}
| 100-degrees-celsius | Mine Carts test/Mine Carts test/Assets/Jobs/Building Operation Jobs/Forging/ForgeRobotComponents.cs | C# | gpl3 | 4,911 |
using UnityEngine;
using System.Collections;
public class ReactionJob : BuildingOperationJob {
int reactionType;
public ReactionJob(int nstartX, int nstartY, int nstartZ, int nreactionType):base(nstartX, nstartY, nstartZ){
}
public bool workOn(double workspeed, Robot robot){
bool isDone = base.workOn(workspeed, robot);
if (isDone){
GameObject m = GameObject.CreatePrimitive(PrimitiveType.Cube);
//m.AddComponent(Rigidbody);
m.transform.position = new Vector3(2, 0, 15);
}
return isDone;
}
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
}
| 100-degrees-celsius | Mine Carts test/Mine Carts test/Assets/Jobs/Building Operation Jobs/Reactions/ReactionJob.cs | C# | gpl3 | 644 |
using UnityEngine;
using System.Collections;
public class BuildingOperationJob : Job {
public BuildingOperationJob(int nstartX, int nstartY, int nstartZ):base(nstartX, nstartY, nstartZ, 1){
isBuildingOperationJob = true;
}
public bool workOn(double workspeed, Robot robot){
bool isDone = base.workOn(workspeed, robot);
double amount = workspeed;
percentageComplete += amount;
return isDone;
}
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
}
| 100-degrees-celsius | Mine Carts test/Mine Carts test/Assets/Jobs/Building Operation Jobs/BuildingOperationJob.cs | C# | gpl3 | 530 |
using UnityEngine;
using System.Collections;
public class Job{
public double percentageComplete = 0;
public bool isBuildingOperationJob, isConstructionJob, isDeconstructionJob,
isEquipJob, isHaulingJob, isMiningJob;
public int x, y, z;
public int jobType;
public string jobLabel;
public Job(int startX, int startY, int startZ, int njobType){
x = startX;
y = startY;
z = startZ;
percentageComplete = 0;
/*-
isBuildingOperationJob = false;
isConstructionJob = false;
isDeconstructionJob = false;
isEquipJob = false;
isHaulingJob = false;
isMiningJob = false;
-*/
jobType = njobType;
if ((jobType > 15) | (jobType < 0)){
jobType = 0;
}
Controller.addJob(this);
}
public Point getPosition(){
Point here = new Point(x, y, z);
return here;
}
public bool workOn(double workspeed, Robot robot){
if (percentageComplete > 100){
return true;
} else {
return false;
}
}
}
| 100-degrees-celsius | Mine Carts test/Mine Carts test/Assets/Jobs/Job.cs | C# | gpl3 | 958 |
using UnityEngine;
using System.Collections;
public class DeconstructionJob : Job {
public DeconstructionJob(int nstartX, int nstartY, int nstartZ):base(nstartX, nstartY, nstartZ, 3){
}
public bool workOn(double workspeed, Robot robot){
bool isDone = base.workOn(workspeed, robot);
double amount = workspeed * (robot.rateOfDeconstruction);
percentageComplete += amount;
robot.deconstructionTool.wearPercent += 0.001/robot.deconstructionTool.material.strengthModifier;
if (robot.deconstructionTool.wearPercent > 100){
robot.tools.Remove(robot.deconstructionTool);
GameObject.Destroy(robot.deconstructionTool.item);
robot.deconstructionTool = null;
robot.hasDeconstructionTool = false;
}
return isDone;
}
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
}
| 100-degrees-celsius | Mine Carts test/Mine Carts test/Assets/Jobs/DeconstructionJob.cs | C# | gpl3 | 866 |
using UnityEngine;
using System.Collections;
public class PlacingJob : Job {
public bool complete;
Job jobAtEnd;
public PlacingJob(int nx, int ny, int nz):base(nx, ny, nz, 9){
Controller.removeJob(this);
complete = false;
}
public PlacingJob(int nx, int ny, int nz, Job endJob):base(nx, ny, nz, 9){
Controller.removeJob(this);
complete = false;
jobAtEnd = endJob;
}
public bool workOn(Robot r){
bool done = base.workOn(1000, r);
r.hauling = false;
//Debug.Log("No prob bob");
complete = true;
try {
r.assignJob(jobAtEnd, true);
return false;
} catch {
return true;
}
}
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
}
| 100-degrees-celsius | Mine Carts test/Mine Carts test/Assets/Jobs/PlacingJob.cs | C# | gpl3 | 743 |
using UnityEngine;
using System.Collections;
public class Ore : Boulder {
public Ore():base(){
}
public void starterate(Material mat){
material = mat;
if ((material.GetType()).ToString() == "Aluminum"){
ItemList.aluminumOre.Add(this);
item.renderer.material = (UnityEngine.Material)UnityEngine.Resources.Load("Materials/Aluminum");
} else if ((material.GetType()).ToString() == "Copper"){
ItemList.copperOre.Add(this);
item.renderer.material = (UnityEngine.Material)UnityEngine.Resources.Load("Materials/Copper");
} else if ((material.GetType()).ToString() == "Iron"){
ItemList.ironOre.Add(this);
item.renderer.material = (UnityEngine.Material)UnityEngine.Resources.Load("Materials/Iron");
} else if ((material.GetType()).ToString() == "Tin"){
ItemList.tinOre.Add(this);
item.renderer.material = (UnityEngine.Material)UnityEngine.Resources.Load("Materials/Tin");
} else if ((material.GetType()).ToString() == "Zinc"){
ItemList.zincOre.Add(this);
item.renderer.material = (UnityEngine.Material)UnityEngine.Resources.Load("Materials/Zinc");
} else {
Debug.Log (material.GetType());
}
}
// Use this for initialization
void Start () {
description = "This is a chunk of " + material.GetType().ToString() + " ore";
}
// Update is called once per frame
void Update () {
}
}
| 100-degrees-celsius | Mine Carts test/Mine Carts test/Assets/Items/Boulder/Ore.cs | C# | gpl3 | 1,360 |
using UnityEngine;
using System.Collections;
public class Boulder : Item {
public Material material;
public Boulder():base(){
}
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
}
| 100-degrees-celsius | Mine Carts test/Mine Carts test/Assets/Items/Boulder/Boulder.cs | C# | gpl3 | 258 |
using UnityEngine;
using System.Collections;
public class DeconstructionTool : Tool {
public DeconstructionTool():base(){
}
public void starterate(Metal nmaterial){
material = nmaterial;
speedWithTool = material.workSpeedModifier * 0.5;
Controller.addUnusedTool(this);
isDeconstructionTool = true;
}
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
}
| 100-degrees-celsius | Mine Carts test/Mine Carts test/Assets/Items/Equipment and Tools/Tools/DeconstructionTool.cs | C# | gpl3 | 437 |
using UnityEngine;
using System.Collections;
public class ConstructionTool : Tool {
public ConstructionTool():base(){
}
public void starterate(Metal nmaterial){
material = nmaterial;
speedWithTool = material.workSpeedModifier * 0.5;
Controller.addUnusedTool(this);
isConstructionTool = true;
}
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
}
| 100-degrees-celsius | Mine Carts test/Mine Carts test/Assets/Items/Equipment and Tools/Tools/ConstructionTool.cs | C# | gpl3 | 438 |
using UnityEngine;
using System.Collections;
public class MiningTool : Tool {
public MiningTool():base(){
}
public void starterate(Metal nmaterial){
material = nmaterial;
speedWithTool = material.workSpeedModifier * 0.5;
Controller.addUnusedTool(this);
isMiningTool = true;
}
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
}
| 100-degrees-celsius | Mine Carts test/Mine Carts test/Assets/Items/Equipment and Tools/Tools/MiningTool.cs | C# | gpl3 | 415 |
using UnityEngine;
using System.Collections;
public class Tool : Item{
public Metal material;
public double speedWithTool;
public double wearPercent;
public bool isMiningTool, isConstructionTool, isDeconstructionTool;
public Tool():base(){
isMiningTool = false;
isConstructionTool = false;
isDeconstructionTool = false;
Controller.addUnusedTool(this);
}
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
}
| 100-degrees-celsius | Mine Carts test/Mine Carts test/Assets/Items/Equipment and Tools/Tools/Tool.cs | C# | gpl3 | 494 |
using UnityEngine;
using System.Collections;
public class Legs : RobotComponent {
public Legs():base(){
}
public void starterate(Metal nmaterial){
material = nmaterial;
ItemList.legs.Add(this);
}
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
}
| 100-degrees-celsius | Mine Carts test/Mine Carts test/Assets/Items/Equipment and Tools/Robot components/Legs.cs | C# | gpl3 | 331 |
using UnityEngine;
using System.Collections;
public class Tank : RobotComponent {
public int maxPressure;
public Tank():base(){
}
public void starterate(Metal nmaterial){
material = nmaterial;
ItemList.tanks.Add(this);
maxPressure = (int)(1000 * material.corrosionResistance * material.strengthModifier);
}
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
}
| 100-degrees-celsius | Mine Carts test/Mine Carts test/Assets/Items/Equipment and Tools/Robot components/Tank.cs | C# | gpl3 | 447 |
using UnityEngine;
using System.Collections;
public class Arms : RobotComponent {
public Arms():base(){
}
public void starterate(Metal nmaterial){
material = nmaterial;
ItemList.arms.Add(this);
}
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
}
| 100-degrees-celsius | Mine Carts test/Mine Carts test/Assets/Items/Equipment and Tools/Robot components/Arms.cs | C# | gpl3 | 331 |
using UnityEngine;
using System.Collections;
public class RobotComponent : Item {
public Metal material;
int damage; // How much damage the piece has taken, starts at 0, goes to 100
public RobotComponent():base(){
}
public void Degrade(){
if (Random.Range(0, 1000000) == 1){
damage += 1;
}
}
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
}
| 100-degrees-celsius | Mine Carts test/Mine Carts test/Assets/Items/Equipment and Tools/Robot components/RobotComponent.cs | C# | gpl3 | 432 |
using UnityEngine;
using System.Collections;
public class Head : RobotComponent {
public Head():base(){
}
public void starterate(Metal nmaterial){
material = nmaterial;
ItemList.heads.Add(this);
}
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
}
| 100-degrees-celsius | Mine Carts test/Mine Carts test/Assets/Items/Equipment and Tools/Robot components/Head.cs | C# | gpl3 | 332 |
using UnityEngine;
using System.Collections;
public class Torso : RobotComponent {
public Torso():base(){
}
public void starterate(Metal nmaterial){
material = nmaterial;
ItemList.torsos.Add(this);
}
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
}
| 100-degrees-celsius | Mine Carts test/Mine Carts test/Assets/Items/Equipment and Tools/Robot components/Torso.cs | C# | gpl3 | 335 |
using UnityEngine;
using System.Collections;
public class Item : MonoBehaviour{
public int x, y, z;
public GameObject item;
public string description;
bool clicked;
public Item(){
}
public bool isAt(Point point){
bool isAt = false;
if ((x == point.x) & (y == point.y) & (z == point.z)){
isAt = true;
}
return isAt;
}
// Use this for initialization
void Start () {
item = this.gameObject;
x = (int)transform.position.x;
y = (int)transform.position.y;
z = (int)transform.position.z;
}
public void updatePosition(){
x = (int)transform.position.x;
y = (int)transform.position.y;
z = (int)transform.position.z;
}
// Update is called once per frame
void Update () {
}
public void setPosition(Vector3 v){
item.transform.position = v;
}
void examine(){
clicked = true;
Debug.Log("Yep");
}
void OnGUI(){
if (clicked){
if (GUI.Button(new Rect(10, 10, 10 + (7 * description.Length), 25), description)){
clicked = false;
}
}
}
void OnMouseOver(){
Debug.Log("Clicked");
if (Input.GetMouseButton(1)){
examine();
}
}
}
| 100-degrees-celsius | Mine Carts test/Mine Carts test/Assets/Items/Item.cs | C# | gpl3 | 1,119 |
using UnityEngine;
using System.Collections;
public class Material{
public bool isCoal, isMetal, isWood, isStone;
// Use this for initialization
void Start () {
isCoal = false;
isMetal = false;
isStone = false;
isWood = false;
}
// Update is called once per frame
void Update () {
}
}
| 100-degrees-celsius | Mine Carts test/Mine Carts test/Assets/Items/Materials/Material.cs | C# | gpl3 | 309 |
using UnityEngine;
using System.Collections;
public class Brass : Metal {
public Brass(){
weightModifier = 4;
strengthModifier = 2;
corrosionResistance = 4;
workSpeedModifier = 4;
}
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
}
| 100-degrees-celsius | Mine Carts test/Mine Carts test/Assets/Items/Materials/Brass.cs | C# | gpl3 | 314 |
using UnityEngine;
using System.Collections;
public class Steel : Metal {
public Steel(){
weightModifier = 2;
strengthModifier = 6;
corrosionResistance = 2;
workSpeedModifier = 9;
}
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
}
| 100-degrees-celsius | Mine Carts test/Mine Carts test/Assets/Items/Materials/Steel.cs | C# | gpl3 | 314 |
using UnityEngine;
using System.Collections;
public class Metal : Material{
public double strengthModifier;
public double workSpeedModifier;
public double corrosionResistance;
public double weightModifier;
public bool isAluminum, isBrass, isBronze, isCopper, isGalvanizedSteel, isIron, isSteel, isTin, isZinc;
public Metal(){
isMetal = true;
}
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
}
| 100-degrees-celsius | Mine Carts test/Mine Carts test/Assets/Items/Materials/Metal.cs | C# | gpl3 | 477 |
using UnityEngine;
using System.Collections;
public class GalvanizedSteel : Metal {
public GalvanizedSteel(){
weightModifier = 2;
strengthModifier = 7;
corrosionResistance = 6;
workSpeedModifier = 15;
}
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
}
| 100-degrees-celsius | Mine Carts test/Mine Carts test/Assets/Items/Materials/GalvanizedSteel.cs | C# | gpl3 | 335 |
using UnityEngine;
using System.Collections;
public class Aluminum : Metal {
public Aluminum(){
weightModifier = 1;
strengthModifier = 4;
corrosionResistance = 5;
workSpeedModifier = 10;
}
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
}
| 100-degrees-celsius | Mine Carts test/Mine Carts test/Assets/Items/Materials/Aluminum.cs | C# | gpl3 | 321 |
using UnityEngine;
using System.Collections;
public class Tin : Metal {
public Tin(){
isTin = true;
}
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
}
| 100-degrees-celsius | Mine Carts test/Mine Carts test/Assets/Items/Materials/Tin.cs | C# | gpl3 | 227 |
using UnityEngine;
using System.Collections;
public class Iron : Metal {
public Iron(){
weightModifier = 2.5;
strengthModifier = 4;
corrosionResistance = 1;
workSpeedModifier = 6.5;
}
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
}
| 100-degrees-celsius | Mine Carts test/Mine Carts test/Assets/Items/Materials/Iron.cs | C# | gpl3 | 316 |
using UnityEngine;
using System.Collections;
public class Copper : Metal {
public Copper(){
workSpeedModifier = 2;
strengthModifier = 1;
corrosionResistance = 3;
weightModifier = 6;
}
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
}
| 100-degrees-celsius | Mine Carts test/Mine Carts test/Assets/Items/Materials/Copper.cs | C# | gpl3 | 316 |
using UnityEngine;
using System.Collections;
public class Zinc : Metal {
public Zinc(){
isZinc = true;
}
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
}
| 100-degrees-celsius | Mine Carts test/Mine Carts test/Assets/Items/Materials/Zinc.cs | C# | gpl3 | 230 |
using UnityEngine;
using System.Collections;
public class Stone : Material {
// Use this for initialization
void Start () {
isStone = true;
}
// Update is called once per frame
void Update () {
}
}
| 100-degrees-celsius | Mine Carts test/Mine Carts test/Assets/Items/Materials/Stone.cs | C# | gpl3 | 212 |
using UnityEngine;
using System.Collections;
public class Wood : Material {
// Use this for initialization
void Start () {
isWood = true;
}
// Update is called once per frame
void Update () {
}
}
| 100-degrees-celsius | Mine Carts test/Mine Carts test/Assets/Items/Materials/Wood.cs | C# | gpl3 | 210 |
using UnityEngine;
using System.Collections;
public class Bronze : Metal{
public Bronze(){
weightModifier = 5;
strengthModifier = 5;
corrosionResistance = 3.5;
workSpeedModifier = 3;
}
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
}
| 100-degrees-celsius | Mine Carts test/Mine Carts test/Assets/Items/Materials/Bronze.cs | C# | gpl3 | 317 |
using UnityEngine;
using System.Collections;
public class Coal : Material {
// Use this for initialization
void Start () {
isCoal = true;
}
// Update is called once per frame
void Update () {
}
}
| 100-degrees-celsius | Mine Carts test/Mine Carts test/Assets/Items/Materials/Coal.cs | C# | gpl3 | 211 |
using UnityEngine;
using System.Collections;
public static class ItemList {
//These are the lists of items that can be turned into something else. Some things are finished products,
//like tools, and hence not on here
public static ArrayList allItems = new ArrayList();
//ores
public static ArrayList ironOre = new ArrayList();
public static ArrayList tinOre = new ArrayList();
public static ArrayList aluminumOre = new ArrayList();
public static ArrayList copperOre = new ArrayList();
public static ArrayList zincOre = new ArrayList();
//bars
public static ArrayList ironBars = new ArrayList();
public static ArrayList tinBars = new ArrayList();
public static ArrayList aluminumBars = new ArrayList();
public static ArrayList copperBars = new ArrayList();
public static ArrayList zincBars = new ArrayList();
public static ArrayList brassBars = new ArrayList();
public static ArrayList bronzeBars = new ArrayList();
public static ArrayList coalBars = new ArrayList();
public static ArrayList galvanizedSteelBars = new ArrayList();
public static ArrayList steelBars = new ArrayList();
//robotstuff
public static ArrayList arms = new ArrayList();
public static ArrayList heads = new ArrayList();
public static ArrayList legs = new ArrayList();
public static ArrayList tanks = new ArrayList();
public static ArrayList torsos = new ArrayList();
}
| 100-degrees-celsius | Mine Carts test/Mine Carts test/Assets/Items/ItemList.cs | C# | gpl3 | 1,381 |
using UnityEngine;
using System.Collections;
public class Bar : Item {
public Material material;
public Bar():base(){
}
public void starterate(Material mat){
material = mat;
if ((material.GetType()).ToString() == "Aluminum"){
ItemList.aluminumBars.Add(this);
item.renderer.material = (UnityEngine.Material)UnityEngine.Resources.Load("Materials/Aluminum");
} else if ((material.GetType()).ToString() == "Copper"){
ItemList.copperBars.Add(this);
item.renderer.material = (UnityEngine.Material)UnityEngine.Resources.Load("Materials/Copper");
} else if ((material.GetType()).ToString() == "Iron"){
ItemList.ironBars.Add(this);
item.renderer.material = (UnityEngine.Material)UnityEngine.Resources.Load("Materials/Iron");
} else if ((material.GetType()).ToString() == "Tin"){
ItemList.tinBars.Add(this);
item.renderer.material = (UnityEngine.Material)UnityEngine.Resources.Load("Materials/Tin");
} else if ((material.GetType()).ToString() == "Zinc"){
ItemList.zincBars.Add(this);
item.renderer.material = (UnityEngine.Material)UnityEngine.Resources.Load("Materials/Zinc");
} else if ((material.GetType()).ToString() == "Brass"){
ItemList.brassBars.Add(this);
item.renderer.material = (UnityEngine.Material)UnityEngine.Resources.Load("Materials/Brass");
} else if ((material.GetType()).ToString() == "Bronze"){
ItemList.bronzeBars.Add(this);
item.renderer.material = (UnityEngine.Material)UnityEngine.Resources.Load("Materials/Bronze");
} else if ((material.GetType()).ToString() == "Steel"){
ItemList.steelBars.Add(this);
item.renderer.material = (UnityEngine.Material)UnityEngine.Resources.Load("Materials/Steel");
} else if ((material.GetType()).ToString() == "GalvanizedSteel"){
ItemList.galvanizedSteelBars.Add(this);
item.renderer.material = (UnityEngine.Material)UnityEngine.Resources.Load("Materials/GalvanizedSteel");
} else {
Debug.LogError (material.GetType());
}
ItemList.ironBars.Add(this);
}
// Use this for initialization
void Start () {
description = "This is a " + material.GetType().ToString() + " bar";
}
// Update is called once per frame
void Update () {
}
public Material getMaterial(){
return material;
}
}
| 100-degrees-celsius | Mine Carts test/Mine Carts test/Assets/Items/Bars/Bar.cs | C# | gpl3 | 2,241 |
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class CubicSpline {
#region properties
//point[0] is the start point of the spline, point[1] the first control point,
// point[2] the second control point and point[3] the end point
private Vector3[] _points = new Vector3[4];
//Only the nodes on the track are of interest to the rasterizer,
//so we don't return the control points
public Vector3[] points
{
get
{
return new Vector3[] {_points[0], _points[3]};
}
}
#endregion
#region constructors
//The public constructor, which makes a CubicSpline section out of two SplineControlPoints
public CubicSpline(SplineControlPoint start, SplineControlPoint end)
{
_points[0] = start.location;
_points[1] = start.location+start.direction*start.weights[1];
_points[2] = end.location-end.direction*end.weights[0];
_points[3] = end.location;
}
//This constructor is used internally by the subdivide function
private CubicSpline(Vector3[] points)
{
_points = points;
}
#endregion
#region subdivision functions
//Recursively subdivides the track until the length is smaller than the specified length
//See also http://www.ams.org/samplings/feature-column/fcarc-bezier#2
public List<CubicSpline> subdivide(int lmax)
{
//Subdivide the lines between the 4 points that make up the spline
Vector3 p01 = Vector3.Lerp(_points[0], _points[1], 0.5f);
Vector3 p12 = Vector3.Lerp(_points[1], _points[2], 0.5f);
Vector3 p23 = Vector3.Lerp(_points[2], _points[3], 0.5f);
//Subdivide the lines between the points found that way
Vector3 p012 = Vector3.Lerp(p01, p12, 0.5f);
Vector3 p123 = Vector3.Lerp(p12, p23, 0.5f);
//Finaly, the midpoint of our spline is halfway between the two points obtained that way.
Vector3 p0123 = Vector3.Lerp(p012, p123, 0.5f);
float length = Vector3.Distance(_points[0], p0123);
//We split the spline in two
CubicSpline frontSpline = new CubicSpline(new Vector3[] {_points[0], p01, p012, p0123});
CubicSpline backSpline = new CubicSpline(new Vector3[] {p0123, p123, p23, _points[3]});
List<CubicSpline> newSplines = new List<CubicSpline>();
//Return the two splines if the section is short enough
if (length < lmax)
{
newSplines.Add(frontSpline);
newSplines.Add(backSpline);
}
//Or recur on those splines if it's not.
else
{
newSplines.AddRange(frontSpline.subdivide(lmax));
newSplines.AddRange(backSpline.subdivide(lmax));
}
return newSplines;
}
#endregion
} | 100-degrees-celsius | Mine Carts test/Mine Carts test/Assets/Splines/CubicSpline.cs | C# | gpl3 | 2,537 |
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class Spline3D : IEnumerable<Vector3[]> {
#region Properties
//The path that the track follows
private CubicSpline[] _SplineSections;
//Information for the outside world.
public Vector3 startPoint
{
get
{
return _SplineSections[0].points[0];
}
}
public Vector3 endPoint
{
get
{
return _SplineSections[_SplineSections.Length-1].points[1];
}
}
public Vector3 center
{
get
{
return (startPoint + endPoint)/2;
}
}
public Vector3 direction
{
get
{
return endPoint - startPoint;
}
}
public SplineControlPoint startSplineControlPoint
{
get
{
return new SplineControlPoint(startPoint, startPoint-_SplineSections[0].points[1], new float[] {1, 1});
}
}
public SplineControlPoint endSplineControlPoint
{
get
{
return new SplineControlPoint(endPoint, endPoint-_SplineSections[_SplineSections.Length-1].points[0], new float[] {1, 1});
}
}
public Transform type {get; set;}
public int layer {get; set;}
#endregion
#region Constructors
//Public constructor
public Spline3D(SplineControlPoint[] cp)
{
_SplineSections = new CubicSpline[cp.Length-1];
//Starting at points 0 and 1, generate a CubicSpline from point 0 to 1,
// then from 1 to 2 et cetera.
for (int i = 1; i < cp.Length; i++)
{
_SplineSections[i-1] = new CubicSpline(cp[i-1], cp[i]);
}
layer = LayerMask.NameToLayer("Track");
}
//Private constructor used in the Rasterize method
private Spline3D(CubicSpline ss)
{
_SplineSections = new CubicSpline[] {ss};
}
#endregion
#region Subdivision functions
//Subdivides the spline into smaller splines
private CubicSpline[] Subdivide(int lmax)
{
List<CubicSpline> accu = new List<CubicSpline>();
foreach(CubicSpline spline in _SplineSections)
{
accu.AddRange(spline.subdivide(lmax));
}
return accu.ToArray();
}
//Subdivides the spline into smaller splines and returns them as an array of Spline3Ds
public Spline3D[] Rasterize(int lmax)
{
CubicSpline[] SubdividedSplines = Subdivide(lmax);
Spline3D[] RasterizedSpline3Ds = new Spline3D[SubdividedSplines.Length];
for(int i = 0; i < RasterizedSpline3Ds.Length; i++)
{
RasterizedSpline3Ds[i] = new Spline3D(SubdividedSplines[i]);
}
return RasterizedSpline3Ds;
}
//Smooths the spline by subdividing it's internal spline sections
//untill they're shorter than the specified length
public void Smooth(int lmax)
{
_SplineSections = Subdivide(lmax);
}
#endregion
#region Enumerator functions
//Implements an enumeable interface for ease of access.
public IEnumerator<Vector3[]> GetEnumerator()
{
return new Spline3DEnumerator(_SplineSections);
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
#endregion
}
class Spline3DEnumerator : IEnumerator<Vector3[]> {
private CubicSpline[] _splines;
private int _index;
public Spline3DEnumerator(CubicSpline[] s)
{
_splines = s;
_index = -1;
}
public void Reset()
{
_index = -1;
}
public object Current
{
get
{
return _splines[_index].points;
}
}
Vector3[] IEnumerator<Vector3[]>.Current
{
get
{
return _splines[_index].points;
}
}
public bool MoveNext()
{
_index++;
if (_index >= _splines.Length)
return false;
else
return true;
}
public void Dispose()
{
}
} | 100-degrees-celsius | Mine Carts test/Mine Carts test/Assets/Splines/Spline3D.cs | C# | gpl3 | 3,577 |
using UnityEngine;
using System.Collections;
public struct SplineControlPoint {
public Vector3 location;
public Vector3 direction;
public float[] weights;
public SplineControlPoint(Vector3 l, Vector3 d, float[] w)
{
this.location = l;
this.direction = d.normalized;
this.weights = w;
}
}
| 100-degrees-celsius | Mine Carts test/Mine Carts test/Assets/Splines/SplineControlPoint.cs | C# | gpl3 | 307 |