code
stringlengths
1
2.01M
language
stringclasses
1 value
<?php class format { /** * 日期格式化 * * @param $timestamp * @param $showtime */ public static function date($timestamp, $showtime = 0) { if (empty($timestamp)) return false; $times = intval($timestamp); if(!$times) return true; $lang = pc_base::load_config('system','lang'); if($lang == 'zh-cn') { $str = $showtime ? date('Y-m-d H:i:s', $times) : date('Y-m-d', $times); } else { $str = $showtime ? date('m/d/Y H:i:s', $times) : date('m/d/Y', $times); } return $str; } /** * 获取当前星期 * * @param $timestamp */ public static function week($timestamp) { $times = intval($timestamp); if(!$times) return true; $weekarray = array(L('Sunday'),L('Monday'),L('Tuesday'),L('Wednesday'),L('Thursday'),L('Friday'),L('Saturday')); return $weekarray[date("w",$timestamp)]; } } ?>
PHP
<?php /** * session mysql 数据库存储类 * * @copyright (C) 2005-2010 PHPCMS * @license http://www.phpcms.cn/license/ * @lastmodify 2010-6-8 */ class session_mysql { var $lifetime = 1800; var $db; var $table; /** * 构造函数 * */ public function __construct() { $this->db = pc_base::load_model('session_model'); $this->lifetime = pc_base::load_config('system','session_ttl'); session_set_save_handler(array(&$this,'open'), array(&$this,'close'), array(&$this,'read'), array(&$this,'write'), array(&$this,'destroy'), array(&$this,'gc')); session_start(); } /** * session_set_save_handler open方法 * @param $save_path * @param $session_name * @return true */ public function open($save_path, $session_name) { return true; } /** * session_set_save_handler close方法 * @return bool */ public function close() { return $this->gc($this->lifetime); } /** * 读取session_id * session_set_save_handler read方法 * @return string 读取session_id */ public function read($id) { $r = $this->db->get_one(array('sessionid'=>$id), 'data'); return $r ? $r['data'] : ''; } /** * 写入session_id 的值 * * @param $id session * @param $data 值 * @return mixed query 执行结果 */ public function write($id, $data) { $uid = isset($_SESSION['userid']) ? $_SESSION['userid'] : 0; $roleid = isset($_SESSION['roleid']) ? $_SESSION['roleid'] : 0; $groupid = isset($_SESSION['groupid']) ? $_SESSION['groupid'] : 0; $m = defined('ROUTE_M') ? ROUTE_M : ''; $c = defined('ROUTE_C') ? ROUTE_C : ''; $a = defined('ROUTE_A') ? ROUTE_A : ''; if(strlen($data) > 255) $data = ''; $ip = ip(); $sessiondata = array( 'sessionid'=>$id, 'userid'=>uid, 'ip'=>ip, 'lastvisit'=>SYS_TIME, 'roleid'=>$roleid, 'groupid'=>$groupid, 'm'=>$m, 'c'=>$c, 'a'=>a, 'data'=>$data, ); return $this->db->insert($sessiondata, 1, 1); } /** * 删除指定的session_id * * @param $id session * @return bool */ public function destroy($id) { return $this->db->delete(array('sessionid'=>$id)); } /** * 删除过期的 session * * @param $maxlifetime 存活期时间 * @return bool */ public function gc($maxlifetime) { $expiretime = SYS_TIME - $maxlifetime; return $this->db->delete("`lastvisit`<$expiretime"); } } ?>
PHP
<?php class http { var $method; var $cookie; var $post; var $header; var $ContentType; var $errno; var $errstr; function __construct() { $this->method = 'GET'; $this->cookie = ''; $this->post = ''; $this->header = ''; $this->errno = 0; $this->errstr = ''; } function post($url, $data = array(), $referer = '', $limit = 0, $timeout = 30, $block = TRUE) { $this->method = 'POST'; $this->ContentType = "Content-Type: application/x-www-form-urlencoded\r\n"; if($data) { $post = ''; foreach($data as $k=>$v) { $post .= $k.'='.rawurlencode($v).'&'; } $this->post .= substr($post, 0, -1); } return $this->request($url, $referer, $limit, $timeout, $block); } function get($url, $referer = '', $limit = 0, $timeout = 30, $block = TRUE) { $this->method = 'GET'; return $this->request($url, $referer, $limit, $timeout, $block); } function upload($url, $data = array(), $files = array(), $referer = '', $limit = 0, $timeout = 30, $block = TRUE) { $this->method = 'POST'; $boundary = "AaB03x"; $this->ContentType = "Content-Type: multipart/form-data; boundary=$boundary\r\n"; if($data) { foreach($data as $k => $v) { $this->post .= "--$boundary\r\n"; $this->post .= "Content-Disposition: form-data; name=\"".$k."\"\r\n"; $this->post .= "\r\n".$v."\r\n"; $this->post .= "--$boundary\r\n"; } } foreach($files as $k=>$v) { $this->post .= "--$boundary\r\n"; $this->post .= "Content-Disposition: file; name=\"$k\"; filename=\"".basename($v)."\"\r\n"; $this->post .= "Content-Type: ".$this->get_mime($v)."\r\n"; $this->post .= "\r\n".file_get_contents($v)."\r\n"; $this->post .= "--$boundary\r\n"; } $this->post .= "--$boundary--\r\n"; return $this->request($url, $referer, $limit, $timeout, $block); } function request($url, $referer = '', $limit = 0, $timeout = 30, $block = TRUE) { $matches = parse_url($url); $host = $matches['host']; $path = $matches['path'] ? $matches['path'].($matches['query'] ? '?'.$matches['query'] : '') : '/'; $port = $matches['port'] ? $matches['port'] : 80; if($referer == '') $referer = URL; $out = "$this->method $path HTTP/1.1\r\n"; $out .= "Accept: */*\r\n"; $out .= "Referer: $referer\r\n"; $out .= "Accept-Language: zh-cn\r\n"; $out .= "User-Agent: ".$_SERVER['HTTP_USER_AGENT']."\r\n"; $out .= "Host: $host\r\n"; if($this->cookie) $out .= "Cookie: $this->cookie\r\n"; if($this->method == 'POST') { $out .= $this->ContentType; $out .= "Content-Length: ".strlen($this->post)."\r\n"; $out .= "Cache-Control: no-cache\r\n"; $out .= "Connection: Close\r\n\r\n"; $out .= $this->post; } else { $out .= "Connection: Close\r\n\r\n"; } if($timeout > ini_get('max_execution_time')) @set_time_limit($timeout); $fp = @fsockopen($host, $port, $errno, $errstr, $timeout); if(!$fp) { $this->errno = $errno; $this->errstr = $errstr; return false; } else { stream_set_blocking($fp, $block); stream_set_timeout($fp, $timeout); fwrite($fp, $out); $this->data = ''; $status = stream_get_meta_data($fp); if(!$status['timed_out']) { $maxsize = min($limit, 1024000); if($maxsize == 0) $maxsize = 1024000; $start = false; while(!feof($fp)) { if($start) { $line = fread($fp, $maxsize); if(strlen($this->data) > $maxsize) break; $this->data .= $line; } else { $line = fgets($fp); $this->header .= $line; if($line == "\r\n" || $line == "\n") $start = true; } } } fclose($fp); return $this->is_ok(); } } function save($file) { dir_create(dirname($file)); return file_put_contents($file, $this->data); } function set_cookie($name, $value) { $this->cookie .= "$name=$value;"; } function get_cookie() { $cookies = array(); if(preg_match_all("|Set-Cookie: ([^;]*);|", $this->header, $m)) { foreach($m[1] as $c) { list($k, $v) = explode('=', $c); $cookies[$k] = $v; } } return $cookies; } function get_data() { if (strpos($this->header,'chunk')) { $data = explode(chr(13), $this->data); return $data[1]; } else { return $this->data; } } function get_header() { return $this->header; } function get_status() { preg_match("|^HTTP/1.1 ([0-9]{3}) (.*)|", $this->header, $m); return array($m[1], $m[2]); } function get_mime($file) { $ext = strtolower(trim(substr(strrchr($file, '.'), 1, 10))); if($ext == '') return ''; $mime_types = array ( 'acx' => 'application/internet-property-stream', 'ai' => 'application/postscript', 'aif' => 'audio/x-aiff', 'aifc' => 'audio/x-aiff', 'aiff' => 'audio/x-aiff', 'asp' => 'text/plain', 'aspx' => 'text/plain', 'asf' => 'video/x-ms-asf', 'asr' => 'video/x-ms-asf', 'asx' => 'video/x-ms-asf', 'au' => 'audio/basic', 'avi' => 'video/x-msvideo', 'axs' => 'application/olescript', 'bas' => 'text/plain', 'bcpio' => 'application/x-bcpio', 'bin' => 'application/octet-stream', 'bmp' => 'image/bmp', 'c' => 'text/plain', 'cat' => 'application/vnd.ms-pkiseccat', 'cdf' => 'application/x-cdf', 'cer' => 'application/x-x509-ca-cert', 'class' => 'application/octet-stream', 'clp' => 'application/x-msclip', 'cmx' => 'image/x-cmx', 'cod' => 'image/cis-cod', 'cpio' => 'application/x-cpio', 'crd' => 'application/x-mscardfile', 'crl' => 'application/pkix-crl', 'crt' => 'application/x-x509-ca-cert', 'csh' => 'application/x-csh', 'css' => 'text/css', 'dcr' => 'application/x-director', 'der' => 'application/x-x509-ca-cert', 'dir' => 'application/x-director', 'dll' => 'application/x-msdownload', 'dms' => 'application/octet-stream', 'doc' => 'application/msword', 'dot' => 'application/msword', 'dvi' => 'application/x-dvi', 'dxr' => 'application/x-director', 'eps' => 'application/postscript', 'etx' => 'text/x-setext', 'evy' => 'application/envoy', 'exe' => 'application/octet-stream', 'fif' => 'application/fractals', 'flr' => 'x-world/x-vrml', 'flv' => 'video/x-flv', 'gif' => 'image/gif', 'gtar' => 'application/x-gtar', 'gz' => 'application/x-gzip', 'h' => 'text/plain', 'hdf' => 'application/x-hdf', 'hlp' => 'application/winhlp', 'hqx' => 'application/mac-binhex40', 'hta' => 'application/hta', 'htc' => 'text/x-component', 'htm' => 'text/html', 'html' => 'text/html', 'htt' => 'text/webviewhtml', 'ico' => 'image/x-icon', 'ief' => 'image/ief', 'iii' => 'application/x-iphone', 'ins' => 'application/x-internet-signup', 'isp' => 'application/x-internet-signup', 'jfif' => 'image/pipeg', 'jpe' => 'image/jpeg', 'jpeg' => 'image/jpeg', 'jpg' => 'image/jpeg', 'js' => 'application/x-javascript', 'latex' => 'application/x-latex', 'lha' => 'application/octet-stream', 'lsf' => 'video/x-la-asf', 'lsx' => 'video/x-la-asf', 'lzh' => 'application/octet-stream', 'm13' => 'application/x-msmediaview', 'm14' => 'application/x-msmediaview', 'm3u' => 'audio/x-mpegurl', 'man' => 'application/x-troff-man', 'mdb' => 'application/x-msaccess', 'me' => 'application/x-troff-me', 'mht' => 'message/rfc822', 'mhtml' => 'message/rfc822', 'mid' => 'audio/mid', 'mny' => 'application/x-msmoney', 'mov' => 'video/quicktime', 'movie' => 'video/x-sgi-movie', 'mp2' => 'video/mpeg', 'mp3' => 'audio/mpeg', 'mpa' => 'video/mpeg', 'mpe' => 'video/mpeg', 'mpeg' => 'video/mpeg', 'mpg' => 'video/mpeg', 'mpp' => 'application/vnd.ms-project', 'mpv2' => 'video/mpeg', 'ms' => 'application/x-troff-ms', 'mvb' => 'application/x-msmediaview', 'nws' => 'message/rfc822', 'oda' => 'application/oda', 'p10' => 'application/pkcs10', 'p12' => 'application/x-pkcs12', 'p7b' => 'application/x-pkcs7-certificates', 'p7c' => 'application/x-pkcs7-mime', 'p7m' => 'application/x-pkcs7-mime', 'p7r' => 'application/x-pkcs7-certreqresp', 'p7s' => 'application/x-pkcs7-signature', 'pbm' => 'image/x-portable-bitmap', 'pdf' => 'application/pdf', 'pfx' => 'application/x-pkcs12', 'pgm' => 'image/x-portable-graymap', 'php' => 'text/plain', 'pko' => 'application/ynd.ms-pkipko', 'pma' => 'application/x-perfmon', 'pmc' => 'application/x-perfmon', 'pml' => 'application/x-perfmon', 'pmr' => 'application/x-perfmon', 'pmw' => 'application/x-perfmon', 'png' => 'image/png', 'pnm' => 'image/x-portable-anymap', 'pot,' => 'application/vnd.ms-powerpoint', 'ppm' => 'image/x-portable-pixmap', 'pps' => 'application/vnd.ms-powerpoint', 'ppt' => 'application/vnd.ms-powerpoint', 'prf' => 'application/pics-rules', 'ps' => 'application/postscript', 'pub' => 'application/x-mspublisher', 'qt' => 'video/quicktime', 'ra' => 'audio/x-pn-realaudio', 'ram' => 'audio/x-pn-realaudio', 'ras' => 'image/x-cmu-raster', 'rgb' => 'image/x-rgb', 'rmi' => 'audio/mid', 'roff' => 'application/x-troff', 'rtf' => 'application/rtf', 'rtx' => 'text/richtext', 'scd' => 'application/x-msschedule', 'sct' => 'text/scriptlet', 'setpay' => 'application/set-payment-initiation', 'setreg' => 'application/set-registration-initiation', 'sh' => 'application/x-sh', 'shar' => 'application/x-shar', 'sit' => 'application/x-stuffit', 'snd' => 'audio/basic', 'spc' => 'application/x-pkcs7-certificates', 'spl' => 'application/futuresplash', 'src' => 'application/x-wais-source', 'sst' => 'application/vnd.ms-pkicertstore', 'stl' => 'application/vnd.ms-pkistl', 'stm' => 'text/html', 'svg' => 'image/svg+xml', 'sv4cpio' => 'application/x-sv4cpio', 'sv4crc' => 'application/x-sv4crc', 'swf' => 'application/x-shockwave-flash', 't' => 'application/x-troff', 'tar' => 'application/x-tar', 'tcl' => 'application/x-tcl', 'tex' => 'application/x-tex', 'texi' => 'application/x-texinfo', 'texinfo' => 'application/x-texinfo', 'tgz' => 'application/x-compressed', 'tif' => 'image/tiff', 'tiff' => 'image/tiff', 'tr' => 'application/x-troff', 'trm' => 'application/x-msterminal', 'tsv' => 'text/tab-separated-values', 'txt' => 'text/plain', 'uls' => 'text/iuls', 'ustar' => 'application/x-ustar', 'vcf' => 'text/x-vcard', 'vrml' => 'x-world/x-vrml', 'wav' => 'audio/x-wav', 'wcm' => 'application/vnd.ms-works', 'wdb' => 'application/vnd.ms-works', 'wks' => 'application/vnd.ms-works', 'wmf' => 'application/x-msmetafile', 'wmv' => 'video/x-ms-wmv', 'wps' => 'application/vnd.ms-works', 'wri' => 'application/x-mswrite', 'wrl' => 'x-world/x-vrml', 'wrz' => 'x-world/x-vrml', 'xaf' => 'x-world/x-vrml', 'xbm' => 'image/x-xbitmap', 'xla' => 'application/vnd.ms-excel', 'xlc' => 'application/vnd.ms-excel', 'xlm' => 'application/vnd.ms-excel', 'xls' => 'application/vnd.ms-excel', 'xlt' => 'application/vnd.ms-excel', 'xlw' => 'application/vnd.ms-excel', 'xof' => 'x-world/x-vrml', 'xpm' => 'image/x-xpixmap', 'xwd' => 'image/x-xwindowdump', 'z' => 'application/x-compress', 'zip' => 'application/zip', ); return isset($mime_types[$ext]) ? $mime_types[$ext] : ''; } function is_ok() { $status = $this->get_status(); if(intval($status[0]) != 200) { $this->errno = $status[0]; $this->errstr = $status[1]; return false; } return true; } function errno() { return $this->errno; } function errmsg() { return $this->errstr; } } ?>
PHP
<?php /** * model.class.php 数据模型基类 * * @copyright (C) 2005-2010 PHPCMS * @license http://www.phpcms.cn/license/ * @lastmodify 2010-6-7 */ pc_base::load_sys_class('db_factory', '', 0); class model { //数据库配置 protected $db_config = ''; //数据库连接 protected $db = ''; //调用数据库的配置项 protected $db_setting = 'default'; //数据表名 protected $table_name = ''; //表前缀 public $db_tablepre = ''; public function __construct() { if (!isset($this->db_config[$this->db_setting])) { $this->db_setting = 'default'; } $this->table_name = $this->db_config[$this->db_setting]['tablepre'].$this->table_name; $this->db_tablepre = $this->db_config[$this->db_setting]['tablepre']; $this->db = db_factory::get_instance($this->db_config)->get_database($this->db_setting); } /** * 执行sql查询 * @param $where 查询条件[例`name`='$name'] * @param $data 需要查询的字段值[例`name`,`gender`,`birthday`] * @param $limit 返回结果范围[例:10或10,10 默认为空] * @param $order 排序方式 [默认按数据库默认方式排序] * @param $group 分组方式 [默认为空] * @return array 查询结果集数组 */ final public function select($where = '', $data = '*', $limit = '', $order = '', $group = '', $key='') { if (is_array($where)) $where = $this->sqls($where); return $this->db->select($data, $this->table_name, $where, $limit, $order, $group, $key); } /** * 查询多条数据并分页 * @param $where * @param $order * @param $page * @param $pagesize * @return unknown_type */ final public function listinfo($where = '', $order = '', $page = 1, $pagesize = 20, $key='', $setpages = 10,$urlrule = '',$array = array()) { $where = to_sqls($where); $this->number = $this->count($where); $page = max(intval($page), 1); $offset = $pagesize*($page-1); $this->pages = pages($this->number, $page, $pagesize, $urlrule, $array, $setpages); $array = array(); return $this->select($where, '*', "$offset, $pagesize", $order, '', $key); } /** * 获取单条记录查询 * @param $where 查询条件 * @param $data 需要查询的字段值[例`name`,`gender`,`birthday`] * @param $order 排序方式 [默认按数据库默认方式排序] * @param $group 分组方式 [默认为空] * @return array/null 数据查询结果集,如果不存在,则返回空 */ final public function get_one($where = '', $data = '*', $order = '', $group = '') { if (is_array($where)) $where = $this->sqls($where); return $this->db->get_one($data, $this->table_name, $where, $order, $group); } /** * 直接执行sql查询 * @param $sql 查询sql语句 * @return boolean/query resource 如果为查询语句,返回资源句柄,否则返回true/false */ final public function query($sql) { return $this->db->query($sql); } /** * 执行添加记录操作 * @param $data 要增加的数据,参数为数组。数组key为字段值,数组值为数据取值 * @param $return_insert_id 是否返回新建ID号 * @param $replace 是否采用 replace into的方式添加数据 * @return boolean */ final public function insert($data, $return_insert_id = false, $replace = false) { return $this->db->insert($data, $this->table_name, $return_insert_id, $replace); } /** * 获取最后一次添加记录的主键号 * @return int */ final public function insert_id() { return $this->db->insert_id(); } /** * 执行更新记录操作 * @param $data 要更新的数据内容,参数可以为数组也可以为字符串,建议数组。 * 为数组时数组key为字段值,数组值为数据取值 * 为字符串时[例:`name`='phpcms',`hits`=`hits`+1]。 * 为数组时[例: array('name'=>'phpcms','password'=>'123456')] * 数组的另一种使用array('name'=>'+=1', 'base'=>'-=1');程序会自动解析为`name` = `name` + 1, `base` = `base` - 1 * @param $where 更新数据时的条件,可为数组或字符串 * @return boolean */ final public function update($data, $where = '') { if (is_array($where)) $where = $this->sqls($where); return $this->db->update($data, $this->table_name, $where); } /** * 执行删除记录操作 * @param $where 删除数据条件,不充许为空。 * @return boolean */ final public function delete($where) { if (is_array($where)) $where = $this->sqls($where); return $this->db->delete($this->table_name, $where); } /** * 计算记录数 * @param string/array $where 查询条件 */ final public function count($where = '') { $r = $this->get_one($where, "COUNT(*) AS num"); return $r['num']; } /** * 将数组转换为SQL语句 * @param array $where 要生成的数组 * @param string $font 连接串。 */ final public function sqls($where, $font = ' AND ') { if (is_array($where)) { $sql = ''; foreach ($where as $key=>$val) { $sql .= $sql ? " $font `$key` = '$val' " : " `$key` = '$val'"; } return $sql; } else { return $where; } } /** * 获取最后数据库操作影响到的条数 * @return int */ final public function affected_rows() { return $this->db->affected_rows(); } /** * 获取数据表主键 * @return array */ final public function get_primary() { return $this->db->get_primary($this->table_name); } /** * 获取表字段 * @return array */ final public function get_fields() { return $this->db->get_fields($this->table_name); } /** * 检查表是否存在 * @param $table 表名 * @return boolean */ final public function table_exists($table){ return $this->db->table_exists($this->db_tablepre.$table); } final public function list_tables() { return $this->db->list_tables(); } /** * 返回数据结果集 * @param $query (mysql_query返回值) * @return array */ final public function fetch_array() { $data = array(); while($r = $this->db->fetch_next()) { $data[] = $r; } return $data; } /** * 返回数据库版本号 */ final public function version() { return $this->db->version(); } }
PHP
<?php /** * @author wangtiecheng(jim_@live.cn) * @link http://www.phpcms.cn http://www.ku6.cn * @copyright 2005-2009 PHPCMS/KU6 Software LLCS * @license http://www.phpcms.cn/license/ * @datetime Wed Aug 05 18:37:10 CST 2009 * @lastmodify Wed Aug 05 18:37:10 CST 2009 * ------------------------------------------------------------ * $xml = new xml(); * $res = $xml->xml_unserialize($data); */ class xml { var $parser; var $document; var $parent; var $stack; var $last_opened_tag; public function xml() { $this->parser = xml_parser_create(); xml_parser_set_option(&$this->parser, XML_OPTION_CASE_FOLDING, false); xml_set_object(&$this->parser, &$this); xml_set_element_handler(&$this->parser, 'open','close'); xml_set_character_data_handler(&$this->parser, 'data'); } public function destruct() { xml_parser_free(&$this->parser); } /** * unserialize * @param xml字符串 * @return array */ public function xml_unserialize($xml) { $data = $this->parse($xml); $this->destruct(); return $data; } /** * serialize * @param $data 数组 * @return string */ public function xml_serialize(&$data, $level = 0, $prior_key = NULL) { if($level == 0) { ob_start(); echo "<?xml version=\"1.0\" ?>\n<root>","\n"; } while(list($key, $value) = each($data)) { if(!strpos($key, ' attr')) { if(is_array($value) and array_key_exists(0, $value)) { $this->xml_serialize($value, $level, $key); } else { $tag = $prior_key ? $prior_key : $key; echo str_repeat("\t", $level),'<',$tag; if(array_key_exists("$key attr", $data)) { while(list($attr_name, $attr_value) = each($data["$key attr"])) { echo ' ',$attr_name,'="',htmlspecialchars($attr_value),'"'; } reset($data["$key attr"]); } if(is_null($value)) { echo " />\n"; } elseif(!is_array($value)) { echo '>',htmlspecialchars($value),"</$tag>\n"; } else { echo ">\n",$this->xml_serialize($value, $level+1),str_repeat("\t", $level),"</$tag>\n"; } } } } reset($data); if($level == 0) { $str = &ob_get_contents(); ob_end_clean(); return $str.'</root>'; } } public function parse(&$data){ $this->document = array(); $this->stack = array(); $this->parent = &$this->document; return xml_parse(&$this->parser, &$data, true) ? $this->document : NULL; } public function open(&$parser, $tag, $attributes){ $this->data = ''; $this->last_opened_tag = $tag; if(is_array($this->parent) && array_key_exists($tag, $this->parent)) { if(is_array($this->parent[$tag]) && array_key_exists(0,$this->parent[$tag])) { $key = $this->count_numeric_items($this->parent[$tag]); } else { if(array_key_exists("$tag attr", $this->parent)) { $arr = array('0 attr'=>&$this->parent["$tag attr"], &$this->parent[$tag]); unset($this->parent["$tag attr"]); } else { $arr = array(&$this->parent[$tag]); } $this->parent[$tag] = &$arr; $key = 1; } $this->parent = &$this->parent[$tag]; } else { $key = $tag; } if($attributes) { $this->parent["$key attr"] = $attributes; } $this->parent = &$this->parent[$key]; $this->stack[] = &$this->parent; } public function data(&$parser, $data) { if($this->last_opened_tag != NULL) { $this->data .= $data; } } public function close(&$parser, $tag) { if($this->last_opened_tag == $tag) { $this->parent = $this->data; $this->last_opened_tag = NULL; } array_pop($this->stack); if($this->stack) { $this->parent = &$this->stack[count($this->stack)-1]; } } public function count_numeric_items(&$array) { return is_array($array) ? count(array_filter(array_keys($array), 'is_numeric')) : 0; } } ?>
PHP
<?php /** * 生成验证码 * @author chenzhouyu * 类用法 * $checkcode = new checkcode(); * $checkcode->doimage(); * //取得验证 * $_SESSION['code']=$checkcode->get_code(); */ class checkcode { //验证码的宽度 public $width=130; //验证码的高 public $height=50; //设置字体的地址 public $font; //设置字体色 public $font_color; //设置随机生成因子 public $charset = 'abcdefghkmnprstuvwyzABCDEFGHKLMNPRSTUVWYZ23456789'; //设置背景色 public $background = '#EDF7FF'; //生成验证码字符数 public $code_len = 4; //字体大小 public $font_size = 20; //验证码 private $code; //图片内存 private $img; //文字X轴开始的地方 private $x_start; function __construct() { $this->font = PC_PATH.'libs'.DIRECTORY_SEPARATOR.'data'.DIRECTORY_SEPARATOR.'font'.DIRECTORY_SEPARATOR.'elephant.ttf'; } /** * 生成随机验证码。 */ protected function creat_code() { $code = ''; $charset_len = strlen($this->charset)-1; for ($i=0; $i<$this->code_len; $i++) { $code .= $this->charset[rand(1, $charset_len)]; } $this->code = $code; } /** * 获取验证码 */ public function get_code() { return strtolower($this->code); } /** * 生成图片 */ public function doimage() { $this->creat_code(); $this->img = imagecreatetruecolor($this->width, $this->height); if (!$this->font_color) { $this->font_color = imagecolorallocate($this->img, rand(0,156), rand(0,156), rand(0,156)); } else { $this->font_color = imagecolorallocate($this->img, hexdec(substr($this->font_color, 1,2)), hexdec(substr($this->font_color, 3,2)), hexdec(substr($this->font_color, 5,2))); } //设置背景色 $background = imagecolorallocate($this->img,hexdec(substr($this->background, 1,2)),hexdec(substr($this->background, 3,2)),hexdec(substr($this->background, 5,2))); //画一个柜形,设置背景颜色。 imagefilledrectangle($this->img,0, $this->height, $this->width, 0, $background); $this->creat_font(); $this->creat_line(); $this->output(); } /** * 生成文字 */ private function creat_font() { $x = $this->width/$this->code_len; for ($i=0; $i<$this->code_len; $i++) { imagettftext($this->img, $this->font_size, rand(-30,30), $x*$i+rand(0,5), $this->height/1.4, $this->font_color, $this->font, $this->code[$i]); if($i==0)$this->x_start=$x*$i+5; } } /** * 画线 */ private function creat_line() { imagesetthickness($this->img, 3); $xpos = ($this->font_size * 2) + rand(-5, 5); $width = $this->width / 2.66 + rand(3, 10); $height = $this->font_size * 2.14; if ( rand(0,100) % 2 == 0 ) { $start = rand(0,66); $ypos = $this->height / 2 - rand(10, 30); $xpos += rand(5, 15); } else { $start = rand(180, 246); $ypos = $this->height / 2 + rand(10, 30); } $end = $start + rand(75, 110); imagearc($this->img, $xpos, $ypos, $width, $height, $start, $end, $this->font_color); $color = $colors[rand(0, sizeof($colors) - 1)]; if ( rand(1,75) % 2 == 0 ) { $start = rand(45, 111); $ypos = $this->height / 2 - rand(10, 30); $xpos += rand(5, 15); } else { $start = rand(200, 250); $ypos = $this->height / 2 + rand(10, 30); } $end = $start + rand(75, 100); imagearc($this->img, $this->width * .75, $ypos, $width, $height, $start, $end, $this->font_color); } //输出图片 private function output() { header("content-type:image/png\r\n"); imagepng($this->img); imagedestroy($this->img); } }
PHP
<?php define('CODETABLEDIR', dirname(__FILE__).DIRECTORY_SEPARATOR.'encoding'.DIRECTORY_SEPARATOR); function utf8_to_gbk($utfstr) { global $UC2GBTABLE; $okstr = ''; if(empty($UC2GBTABLE)) { $filename = CODETABLEDIR.'gb-unicode.table'; $fp = fopen($filename, 'rb'); while($l = fgets($fp,15)) { $UC2GBTABLE[hexdec(substr($l, 7, 6))] = hexdec(substr($l, 0, 6)); } fclose($fp); } $okstr = ''; $ulen = strlen($utfstr); for($i=0; $i<$ulen; $i++) { $c = $utfstr[$i]; $cb = decbin(ord($utfstr[$i])); if(strlen($cb)==8) { $csize = strpos(decbin(ord($cb)),'0'); for($j = 0; $j < $csize; $j++) { $i++; $c .= $utfstr[$i]; } $c = utf8_to_unicode($c); if(isset($UC2GBTABLE[$c])) { $c = dechex($UC2GBTABLE[$c]+0x8080); $okstr .= chr(hexdec($c[0].$c[1])).chr(hexdec($c[2].$c[3])); } else { $okstr .= '&#'.$c.';'; } } else { $okstr .= $c; } } $okstr = trim($okstr); return $okstr; } function gbk_to_utf8($gbstr) { global $CODETABLE; if(empty($CODETABLE)) { $filename = CODETABLEDIR.'gb-unicode.table'; $fp = fopen($filename, 'rb'); while($l = fgets($fp,15)) { $CODETABLE[hexdec(substr($l, 0, 6))] = substr($l, 7, 6); } fclose($fp); } $ret = ''; $utf8 = ''; while($gbstr) { if(ord(substr($gbstr, 0, 1)) > 0x80) { $thisW = substr($gbstr, 0, 2); $gbstr = substr($gbstr, 2, strlen($gbstr)); $utf8 = ''; @$utf8 = unicode_to_utf8(hexdec($CODETABLE[hexdec(bin2hex($thisW)) - 0x8080])); if($utf8 != '') { for($i = 0; $i < strlen($utf8); $i += 3) $ret .= chr(substr($utf8, $i, 3)); } } else { $ret .= substr($gbstr, 0, 1); $gbstr = substr($gbstr, 1, strlen($gbstr)); } } return $ret; } function big5_to_gbk($Text) { global $BIG5_DATA; if(empty($BIG5_DATA)) { $filename = CODETABLEDIR.'big5-gb.table'; $fp = fopen($filename, 'rb'); $BIG5_DATA = fread($fp, filesize($filename)); fclose($fp); } $max = strlen($Text)-1; for($i = 0; $i < $max; $i++) { $h = ord($Text[$i]); if($h >= 0x80) { $l = ord($Text[$i+1]); if($h==161 && $l==64) { $gbstr = ' '; } else { $p = ($h-160)*510+($l-1)*2; $gbstr = $BIG5_DATA[$p].$BIG5_DATA[$p+1]; } $Text[$i] = $gbstr[0]; $Text[$i+1] = $gbstr[1]; $i++; } } return $Text; } function gbk_to_big5($Text) { global $GB_DATA; if(empty($GB_DATA)) { $filename = CODETABLEDIR.'gb-big5.table'; $fp = fopen($filename, 'rb'); $gb = fread($fp, filesize($filename)); fclose($fp); } $max = strlen($Text)-1; for($i = 0; $i < $max; $i++) { $h = ord($Text[$i]); if($h >= 0x80) { $l = ord($Text[$i+1]); if($h==161 && $l==64) { $big = ' '; } else { $p = ($h-160)*510+($l-1)*2; $big = $GB_DATA[$p].$GB_DATA[$p+1]; } $Text[$i] = $big[0]; $Text[$i+1] = $big[1]; $i++; } } return $Text; } function unicode_to_utf8($c) { $str = ''; if($c < 0x80) { $str .= $c; } elseif($c < 0x800) { $str .= (0xC0 | $c >> 6); $str .= (0x80 | $c & 0x3F); } elseif($c < 0x10000) { $str .= (0xE0 | $c >> 12); $str .= (0x80 | $c >> 6 & 0x3F); $str .= (0x80 | $c & 0x3F); } elseif($c < 0x200000) { $str .= (0xF0 | $c >> 18); $str .= (0x80 | $c >> 12 & 0x3F); $str .= (0x80 | $c >> 6 & 0x3F); $str .= (0x80 | $c & 0x3F); } return $str; } function utf8_to_unicode($c) { switch(strlen($c)) { case 1: return ord($c); case 2: $n = (ord($c[0]) & 0x3f) << 6; $n += ord($c[1]) & 0x3f; return $n; case 3: $n = (ord($c[0]) & 0x1f) << 12; $n += (ord($c[1]) & 0x3f) << 6; $n += ord($c[2]) & 0x3f; return $n; case 4: $n = (ord($c[0]) & 0x0f) << 18; $n += (ord($c[1]) & 0x3f) << 12; $n += (ord($c[2]) & 0x3f) << 6; $n += ord($c[3]) & 0x3f; return $n; } } function asc_to_pinyin($asc,&$pyarr) { if($asc < 128)return chr($asc); elseif(isset($pyarr[$asc]))return $pyarr[$asc]; else { foreach($pyarr as $id => $p) { if($id >= $asc)return $p; } } } function gbk_to_pinyin($txt) { $l = strlen($txt); $i = 0; $pyarr = array(); $py = array(); $filename = CODETABLEDIR.'gb-pinyin.table'; $fp = fopen($filename,'r'); while(!feof($fp)) { $p = explode("-",fgets($fp,32)); $pyarr[intval($p[1])] = trim($p[0]); } fclose($fp); ksort($pyarr); while($i<$l) { $tmp = ord($txt[$i]); if($tmp>=128) { $asc = abs($tmp*256+ord($txt[$i+1])-65536); $i = $i+1; }else $asc = $tmp; $py[] = asc_to_pinyin($asc,$pyarr); $i++; } return $py; } ?>
PHP
<?php /** * global.func.php 公共函数库 * * @copyright (C) 2005-2010 PHPCMS * @license http://www.phpcms.cn/license/ * @lastmodify 2010-6-1 */ /** * 返回经addslashes处理过的字符串或数组 * @param $string 需要处理的字符串或数组 * @return mixed */ function new_addslashes($string) { if(!is_array($string)) return addslashes($string); foreach($string as $key => $val) $string[$key] = new_addslashes($val); return $string; } /** * 返回经stripslashes处理过的字符串或数组 * @param $string 需要处理的字符串或数组 * @return mixed */ function new_stripslashes($string) { if(!is_array($string)) return stripslashes($string); foreach($string as $key => $val) $string[$key] = new_stripslashes($val); return $string; } /** * 返回经addslashe处理过的字符串或数组 * @param $obj 需要处理的字符串或数组 * @return mixed */ function new_html_special_chars($string) { if(!is_array($string)) return htmlspecialchars($string); foreach($string as $key => $val) $string[$key] = new_html_special_chars($val); return $string; } /** * 安全过滤函数 * * @param $string * @return string */ function safe_replace($string) { $string = str_replace('%20','',$string); $string = str_replace('%27','',$string); $string = str_replace('%2527','',$string); $string = str_replace('*','',$string); $string = str_replace('"','&quot;',$string); $string = str_replace("'",'',$string); $string = str_replace('"','',$string); $string = str_replace(';','',$string); $string = str_replace('<','&lt;',$string); $string = str_replace('>','&gt;',$string); $string = str_replace("{",'',$string); $string = str_replace('}','',$string); return $string; } /** * 过滤ASCII码从0-28的控制字符 * @return String */ function trim_unsafe_control_chars($str) { $rule = '/[' . chr ( 1 ) . '-' . chr ( 8 ) . chr ( 11 ) . '-' . chr ( 12 ) . chr ( 14 ) . '-' . chr ( 31 ) . ']*/'; return str_replace ( chr ( 0 ), '', preg_replace ( $rule, '', $str ) ); } /** * 格式化文本域内容 * * @param $string 文本域内容 * @return string */ function trim_textarea($string) { $string = nl2br ( str_replace ( ' ', '&nbsp;', $string ) ); return $string; } /** * 将文本格式成适合js输出的字符串 * @param string $string 需要处理的字符串 * @param intval $isjs 是否执行字符串格式化,默认为执行 * @return string 处理后的字符串 */ function format_js($string, $isjs = 1) { $string = addslashes(str_replace(array("\r", "\n"), array('', ''), $string)); return $isjs ? 'document.write("'.$string.'");' : $string; } /** * 转义 javascript 代码标记 * * @param $str * @return mixed */ function trim_script($str) { $str = preg_replace ( '/\<([\/]?)script([^\>]*?)\>/si', '&lt;\\1script\\2&gt;', $str ); $str = preg_replace ( '/\<([\/]?)iframe([^\>]*?)\>/si', '&lt;\\1iframe\\2&gt;', $str ); $str = preg_replace ( '/\<([\/]?)frame([^\>]*?)\>/si', '&lt;\\1frame\\2&gt;', $str ); $str = preg_replace ( '/]]\>/si', ']] >', $str ); return $str; } /** * 获取当前页面完整URL地址 */ function get_url() { $sys_protocal = isset($_SERVER['SERVER_PORT']) && $_SERVER['SERVER_PORT'] == '443' ? 'https://' : 'http://'; $php_self = $_SERVER['PHP_SELF'] ? safe_replace($_SERVER['PHP_SELF']) : safe_replace($_SERVER['SCRIPT_NAME']); $path_info = isset($_SERVER['PATH_INFO']) ? safe_replace($_SERVER['PATH_INFO']) : ''; $relate_url = isset($_SERVER['REQUEST_URI']) ? safe_replace($_SERVER['REQUEST_URI']) : $php_self.(isset($_SERVER['QUERY_STRING']) ? '?'.safe_replace($_SERVER['QUERY_STRING']) : $path_info); return $sys_protocal.(isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : '').$relate_url; } /** * 字符截取 支持UTF8/GBK * @param $string * @param $length * @param $dot */ function str_cut($string, $length, $dot = '...') { $strlen = strlen($string); if($strlen <= $length) return $string; $string = str_replace(array('&nbsp;', '&amp;', '&quot;', '&#039;', '&ldquo;', '&rdquo;', '&mdash;', '&lt;', '&gt;', '&middot;', '&hellip;'), array(' ', '&', '"', "'", '“', '”', '—', '<', '>', '·', '…'), $string); $strcut = ''; if(strtolower(CHARSET) == 'utf-8') { $n = $tn = $noc = 0; while($n < $strlen) { $t = ord($string[$n]); if($t == 9 || $t == 10 || (32 <= $t && $t <= 126)) { $tn = 1; $n++; $noc++; } elseif(194 <= $t && $t <= 223) { $tn = 2; $n += 2; $noc += 2; } elseif(224 <= $t && $t < 239) { $tn = 3; $n += 3; $noc += 2; } elseif(240 <= $t && $t <= 247) { $tn = 4; $n += 4; $noc += 2; } elseif(248 <= $t && $t <= 251) { $tn = 5; $n += 5; $noc += 2; } elseif($t == 252 || $t == 253) { $tn = 6; $n += 6; $noc += 2; } else { $n++; } if($noc >= $length) break; } if($noc > $length) $n -= $tn; $strcut = substr($string, 0, $n); } else { $dotlen = strlen($dot); $maxi = $length - $dotlen - 1; for($i = 0; $i < $maxi; $i++) { $strcut .= ord($string[$i]) > 127 ? $string[$i].$string[++$i] : $string[$i]; } } $strcut = str_replace(array('&', '"', "'", '<', '>'), array('&amp;', '&quot;', '&#039;', '&lt;', '&gt;'), $strcut); return $strcut.$dot; } /** * 获取请求ip * * @return ip地址 */ function ip() { if(getenv('HTTP_CLIENT_IP') && strcasecmp(getenv('HTTP_CLIENT_IP'), 'unknown')) { $ip = getenv('HTTP_CLIENT_IP'); } elseif(getenv('HTTP_X_FORWARDED_FOR') && strcasecmp(getenv('HTTP_X_FORWARDED_FOR'), 'unknown')) { $ip = getenv('HTTP_X_FORWARDED_FOR'); } elseif(getenv('REMOTE_ADDR') && strcasecmp(getenv('REMOTE_ADDR'), 'unknown')) { $ip = getenv('REMOTE_ADDR'); } elseif(isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], 'unknown')) { $ip = $_SERVER['REMOTE_ADDR']; } return preg_match ( '/[\d\.]{7,15}/', $ip, $matches ) ? $matches [0] : ''; } function get_cost_time() { $microtime = microtime(TRUE); return $microtime - SYS_START_TIME; } /** * 程序执行时间 * * @return int 单位ms */ function execute_time() { $stime = explode ( ' ', SYS_START_TIME ); $etime = explode ( ' ', microtime () ); return number_format ( ($etime [1] + $etime [0] - $stime [1] - $stime [0]), 6 ); } /** * 产生随机字符串 * * @param int $length 输出长度 * @param string $chars 可选的 ,默认为 0123456789 * @return string 字符串 */ function random($length, $chars = '0123456789') { $hash = ''; $max = strlen($chars) - 1; for($i = 0; $i < $length; $i++) { $hash .= $chars[mt_rand(0, $max)]; } return $hash; } /** * 将字符串转换为数组 * * @param string $data 字符串 * @return array 返回数组格式,如果,data为空,则返回空数组 */ function string2array($data) { if($data == '') return array(); eval("\$array = $data;"); return $array; } /** * 将数组转换为字符串 * * @param array $data 数组 * @param bool $isformdata 如果为0,则不使用new_stripslashes处理,可选参数,默认为1 * @return string 返回字符串,如果,data为空,则返回空 */ function array2string($data, $isformdata = 1) { if($data == '') return ''; if($isformdata) $data = new_stripslashes($data); return addslashes(var_export($data, TRUE)); } /** * 转换字节数为其他单位 * * * @param string $filesize 字节大小 * @return string 返回大小 */ function sizecount($filesize) { if ($filesize >= 1073741824) { $filesize = round($filesize / 1073741824 * 100) / 100 .' GB'; } elseif ($filesize >= 1048576) { $filesize = round($filesize / 1048576 * 100) / 100 .' MB'; } elseif($filesize >= 1024) { $filesize = round($filesize / 1024 * 100) / 100 . ' KB'; } else { $filesize = $filesize.' Bytes'; } return $filesize; } /** * 字符串加密、解密函数 * * * @param string $txt 字符串 * @param string $operation ENCODE为加密,DECODE为解密,可选参数,默认为ENCODE, * @param string $key 密钥:数字、字母、下划线 * @return string */ function sys_auth($txt, $operation = 'ENCODE', $key = '') { $key = $key ? $key : pc_base::load_config('system', 'auth_key'); $txt = $operation == 'ENCODE' ? (string)$txt : base64_decode($txt); $len = strlen($key); $code = ''; for($i=0; $i<strlen($txt); $i++){ $k = $i % $len; $code .= $txt[$i] ^ $key[$k]; } $code = $operation == 'DECODE' ? $code : base64_encode($code); return $code; } /** * 语言文件处理 * * @param string $language 标示符 * @param array $pars 转义的数组,二维数组 ,'key1'=>'value1','key2'=>'value2', * @param string $modules 多个模块之间用半角逗号隔开,如:member,guestbook * @return string 语言字符 */ function L($language = 'no_language',$pars = array(), $modules = '') { static $LANG = array(); if(!$LANG) { $lang = pc_base::load_config('system','lang'); require_once PC_PATH.'languages'.DIRECTORY_SEPARATOR.$lang.DIRECTORY_SEPARATOR.'system.lang.php'; if(defined('IN_ADMIN')) require_once PC_PATH.'languages'.DIRECTORY_SEPARATOR.$lang.DIRECTORY_SEPARATOR.'system_menu.lang.php'; if(file_exists(PC_PATH.'languages'.DIRECTORY_SEPARATOR.$lang.DIRECTORY_SEPARATOR.ROUTE_M.'.lang.php')) require PC_PATH.'languages'.DIRECTORY_SEPARATOR.$lang.DIRECTORY_SEPARATOR.ROUTE_M.'.lang.php'; if(!empty($modules)) { $modules = explode(',',$modules); foreach($modules AS $m) { require PC_PATH.'languages'.DIRECTORY_SEPARATOR.$lang.DIRECTORY_SEPARATOR.$m.'.lang.php'; } } } if(!array_key_exists($language,$LANG)) { return $LANG['no_language'].'['.$language.']'; } else { $language = $LANG[$language]; if($pars) { foreach($pars AS $_k=>$_v) { $language = str_replace('{'.$_k.'}',$_v,$language); } } return $language; } } /** * 模板调用 * * @param $module * @param $template * @param $istag * @return unknown_type */ function template($module = 'content', $template = 'index', $style = 'default') { $template_cache = pc_base::load_sys_class('template_cache'); $compiledtplfile = PHPCMS_PATH.'caches'.DIRECTORY_SEPARATOR.'caches_template'.DIRECTORY_SEPARATOR.$style.DIRECTORY_SEPARATOR.$module.DIRECTORY_SEPARATOR.$template.'.php'; if(file_exists(PC_PATH.'templates'.DIRECTORY_SEPARATOR.$style.DIRECTORY_SEPARATOR.$module.DIRECTORY_SEPARATOR.$template.'.html')) { if(!file_exists($compiledtplfile) || (@filemtime(PC_PATH.'templates'.DIRECTORY_SEPARATOR.$style.DIRECTORY_SEPARATOR.$module.DIRECTORY_SEPARATOR.$template.'.html') > @filemtime($compiledtplfile))) { $template_cache->template_compile($module, $template, $style); } } else { $compiledtplfile = PHPCMS_PATH.'caches'.DIRECTORY_SEPARATOR.'caches_template'.DIRECTORY_SEPARATOR.$module.DIRECTORY_SEPARATOR.$template.'.default.php'; if(file_exists(PC_PATH.'templates'.DIRECTORY_SEPARATOR.'default'.DIRECTORY_SEPARATOR.$module.DIRECTORY_SEPARATOR.$template.'.html') && filemtime(PC_PATH.'templates'.DIRECTORY_SEPARATOR.'default'.DIRECTORY_SEPARATOR.$module.DIRECTORY_SEPARATOR.$template.'.html') > filemtime($compiledtplfile)) { $template_cache->template_compile($module, $template, 'default'); } else { showmessage('Template does not exist.'.DIRECTORY_SEPARATOR.$style.DIRECTORY_SEPARATOR.$module.DIRECTORY_SEPARATOR.$template.'.html'); } } return $compiledtplfile; } /** * 输出自定义错误 * * @param $errno 错误号 * @param $errstr 错误描述 * @param $errfile 报错文件地址 * @param $errline 错误行号 * @return string 错误提示 */ function my_error_handler($errno, $errstr, $errfile, $errline) { if($errno==8) return ''; $errfile = str_replace(PHPCMS_PATH,'',$errfile); if(pc_base::load_config('system','errorlog')) { error_log(date('m-d H:i:s',SYS_TIME).' | '.$errno.' | '.str_pad($errstr,30).' | '.$errfile.' | '.$errline."\r\n", 3, CACHE_PATH.'error_log.php'); } else { $str = '<div style="font-size:12px;text-align:left; border-bottom:1px solid #9cc9e0; border-right:1px solid #9cc9e0;padding:1px 4px;color:#000000;font-family:Arial, Helvetica,sans-serif;"><span>errorno:' . $errno . ',str:' . $errstr . ',file:<font color="blue">' . $errfile . '</font>,line' . $errline .'<br /><a href="http://faq.phpcms.cn/?type=file&errno='.$errno.'&errstr='.urlencode($errstr).'&errfile='.urlencode($errfile).'&errline='.$errline.'" target="_blank" style="color:red">Need Help?</a></span></div>'; echo $str; } } /** * 提示信息页面跳转,跳转地址如果传入数组,页面会提示多个地址供用户选择,默认跳转地址为数组的第一个值,时间为5秒。 * showmessage('登录成功', array('默认跳转地址'=>'http://www.phpcms.cn')); * @param string $msg 提示信息 * @param mixed(string/array) $url_forward 跳转地址 * @param int $ms 跳转等待时间 */ function showmessage($msg, $url_forward = 'goback', $ms = 1250, $dialog = '') { if(defined('IN_ADMIN')) { include(admin::admin_tpl('showmessage', 'admin')); } else { include(template('content', 'message')); } exit; } /** * 查询字符是否存在于某字符串 * * @param $haystack 字符串 * @param $needle 要查找的字符 * @return bool */ function str_exists($haystack, $needle) { return !(strpos($haystack, $needle) === FALSE); } /** * 取得文件扩展 * * @param $filename 文件名 * @return 扩展名 */ function fileext($filename) { return strtolower(trim(substr(strrchr($filename, '.'), 1, 10))); } /** * 加载模板标签缓存 * @param string $name 缓存名 * @param integer $times 缓存时间 */ function tpl_cache($name,$times = 0) { $filepath = 'tpl_data'; $info = getcacheinfo($name, $filepath); if (SYS_TIME - $info['filemtime'] >= $times) { return false; } else { return getcache($name,$filepath); } } /** * 写入缓存,默认为文件缓存,不加载缓存配置。 * @param $name 缓存名称 * @param $data 缓存数据 * @param $filepath 数据路径(模块名称) caches/cache_$filepath/ * @param $type 缓存类型[file,memcache,apc] * @param $config 配置名称 * @param $timeout 过期时间 */ function setcache($name, $data, $filepath='', $type='file', $config='', $timeout='') { pc_base::load_sys_class('cache_factory','',0); if($config) { $cacheconfig = pc_base::load_config('cache'); $cache = cache_factory::get_instance($cacheconfig)->get_cache($config); } else { $cache = cache_factory::get_instance()->get_cache($type); } return $cache->set($name, $data, $timeout, '', $filepath); } /** * 读取缓存,默认为文件缓存,不加载缓存配置。 * @param string $name 缓存名称 * @param $filepath 数据路径(模块名称) caches/cache_$filepath/ * @param string $config 配置名称 */ function getcache($name, $filepath='', $type='file', $config='') { pc_base::load_sys_class('cache_factory','',0); if($config) { $cacheconfig = pc_base::load_config('cache'); $cache = cache_factory::get_instance($cacheconfig)->get_cache($config); } else { $cache = cache_factory::get_instance()->get_cache($type); } return $cache->get($name, '', '', $filepath); } /** * 删除缓存,默认为文件缓存,不加载缓存配置。 * @param $name 缓存名称 * @param $filepath 数据路径(模块名称) caches/cache_$filepath/ * @param $type 缓存类型[file,memcache,apc] * @param $config 配置名称 */ function delcache($name, $filepath='', $type='file', $config='') { pc_base::load_sys_class('cache_factory','',0); if($config) { $cacheconfig = pc_base::load_config('cache'); $cache = cache_factory::get_instance($cacheconfig)->get_cache($config); } else { $cache = cache_factory::get_instance()->get_cache($type); } return $cache->delete($name, '', '', $filepath); } /** * 读取缓存,默认为文件缓存,不加载缓存配置。 * @param string $name 缓存名称 * @param $filepath 数据路径(模块名称) caches/cache_$filepath/ * @param string $config 配置名称 */ function getcacheinfo($name, $filepath='', $type='file', $config='') { pc_base::load_sys_class('cache_factory'); if($config) { $cacheconfig = pc_base::load_config('cache'); $cache = cache_factory::get_instance($cacheconfig)->get_cache($config); } else { $cache = cache_factory::get_instance()->get_cache($type); } return $cache->cacheinfo($name, '', '', $filepath); } function url($url, $isabs = 0) { if(strpos($url, '://') !== FALSE || $url[0] == '?') return $url; $siteurl = get_url(); if($isabs || defined('SHOWJS')) { $url = strpos($url, WEB_PATH) === 0 ? $siteurl.substr($url, strlen(WEB_PATH)) : $siteurl.$url; } else { $url = strpos($url, WEB_PATH) === 0 ? $url : WEB_PATH.$url; } return $url; } /** * 生成sql语句,如果传入$in_cloumn 生成格式为 IN('a', 'b', 'c') * @param $data 条件数组或者字符串 * @param $front 连接符 * @param $in_column 字段名称 * @return string */ function to_sqls($data, $front = ' AND ', $in_column = false) { if($in_column && is_array($data)) { $ids = '\''.implode('\',\'', $data).'\''; $sql = "$in_column IN ($ids)"; return $sql; } else { if ($front == '') { $front = ' AND '; } if(is_array($data) && count($data) > 0) { $sql = ''; foreach ($data as $key => $val) { $sql .= $sql ? " $front `$key` = '$val' " : " `$key` = '$val' "; } return $sql; } else { return $data; } } } /** * 分页函数 * * @param $num 信息总数 * @param $curr_page 当前分页 * @param $perpage 每页显示数 * @param $urlrule URL规则 * @param $array 需要传递的数组,用于增加额外的方法 * @return 分页 */ function pages($num, $curr_page, $perpage = 20, $urlrule = '', $array = array()) { if($urlrule == '') $urlrule = url_par('page={$page}'); $multipage = ''; if($num > $perpage) { $page = 11; $offset = 4; $pages = ceil($num / $perpage); $from = $curr_page - $offset; $to = $curr_page + $offset; $more = 0; if($page >= $pages) { $from = 2; $to = $pages-1; } else { if($from <= 1) { $to = $page-1; $from = 2; } elseif($to >= $pages) { $from = $pages-($page-2); $to = $pages-1; } $more = 1; } $multipage .= L('total').'<b>'.$num.'</b>&nbsp;&nbsp;'; if($curr_page>0) { $multipage .= ' <a href="'.pageurl($urlrule, $curr_page-1, $array).'" class="a1">'.L('previous').'</a>'; if($curr_page==1) { $multipage .= ' <span>1</span>'; } elseif($curr_page>6 && $more) { $multipage .= ' <a href="'.pageurl($urlrule, 1, $array).'">1</a>..'; } else { $multipage .= ' <a href="'.pageurl($urlrule, 1, $array).'">1</a>'; } } for($i = $from; $i <= $to; $i++) { if($i != $curr_page) { $multipage .= ' <a href="'.pageurl($urlrule, $i, $array).'">'.$i.'</a>'; } else { $multipage .= ' <span>'.$i.'</span>'; } } if($curr_page<$pages) { if($curr_page<$pages-5 && $more) { $multipage .= ' ..<a href="'.pageurl($urlrule, $pages, $array).'">'.$pages.'</a> <a href="'.pageurl($urlrule, $curr_page+1, $array).'" class="a1">'.L('next').'</a>'; } else { $multipage .= ' <a href="'.pageurl($urlrule, $pages, $array).'">'.$pages.'</a> <a href="'.pageurl($urlrule, $curr_page+1, $array).'" class="a1">'.L('next').'</a>'; } } elseif($curr_page==$pages) { $multipage .= ' <span>'.$pages.'</span> <a href="'.pageurl($urlrule, $curr_page, $array).'" class="a1">'.L('next').'</a>'; } else { $multipage .= ' <a href="'.pageurl($urlrule, $pages, $array).'">'.$pages.'</a> <a href="'.pageurl($urlrule, $curr_page+1, $array).'" class="a1">'.L('next').'</a>'; } } return $multipage; } /** * 返回分页路径 * * @param $urlrule 分页规则 * @param $page 当前页 * @param $array 需要传递的数组,用于增加额外的方法 * @return 完整的URL路径 */ function pageurl($urlrule, $page, $array = array()) { if(strpos($urlrule, '#')) { $urlrules = explode('#', $urlrule); $urlrule = $page < 2 ? $urlrules[0] : $urlrules[1]; } $findme = array('{$page}'); $replaceme = array($page); if (is_array($array)) foreach ($array as $k=>$v) { $findme[] = '{$'.$k.'}'; $replaceme[] = $v; } $url = str_replace($findme, $replaceme, $urlrule); return $url; } /** * URL路径解析,pages 函数的辅助函数 * * @param $par 传入需要解析的变量 默认为,page={$page} * @param $url URL地址 * @return URL */ function url_par($par, $url = '') { if($url == '') $url = get_url(); $pos = strpos($url, '?'); if($pos === false) { $url .= '?'.$par; } else { $querystring = substr(strstr($url, '?'), 1); parse_str($querystring, $pars); $query_array = array(); foreach($pars as $k=>$v) { $query_array[$k] = $v; } $querystring = http_build_query($query_array).'&'.$par; $url = substr($url, 0, $pos).'?'.$querystring; } return $url; } /** * 判断email格式是否正确 * @param $email */ function is_email($email) { return strlen($email) > 6 && preg_match("/^[\w\-\.]+@[\w\-\.]+(\.\w+)+$/", $email); } /** * iconv 编辑转换 */ if (!function_exists('iconv')) { function iconv($in_charset, $out_charset, $str) { $in_charset = strtoupper($in_charset); $out_charset = strtoupper($out_charset); if (function_exists('mb_convert_encoding')) { return mb_convert_encoding($str, $out_charset, $in_charset); } else { pc_base::load_sys_func('iconv'); $in_charset = strtoupper($in_charset); $out_charset = strtoupper($out_charset); if($in_charset == 'UTF-8' && ($out_charset == 'GBK' || $out_charset == 'GB2312')) { return utf8_to_gbk($str); } if(($in_charset == 'GBK' || $in_charset == 'GB2312') && $out_charset == 'UTF-8') { return gbk_to_utf8($str); } return $str; } } } /** * 代码广告展示函数 * @param intval $siteid 所属站点 * @param intval $id 广告ID * @return 返回广告代码 */ function show_ad($siteid, $id) { $siteid = intval($siteid); $id = intval($id); if(!$id || !$siteid) return false; $p = pc_base::load_model('poster_model'); $r = $p->get_one(array('spaceid'=>$id, 'siteid'=>$siteid), 'setting', '`id` ASC'); if ($r['setting']) { $c = string2array($r['setting']); } else { $r['code'] = ''; } return $c['code']; } /** * 获取当前的站点ID */ function get_siteid() { static $siteid; if (!empty($siteid)) return $siteid; if (defined('IN_ADMIN')) { if ($d = param::get_cookie('siteid')) { $siteid = $d; } else { return ''; } } else { $data = getcache('sitelist', 'commons'); $site_url = SITE_PROTOCOL.SITE_URL; foreach ($data as $v) { if ($v['url'].'/' == $site_url) $siteid = $v['siteid']; } } return $siteid; } /** * 调用关联菜单 * @param $linkageid * @param $id * @param $defaultvalue */ function menu_linkage($linkageid = 0, $id = 'linkid', $defaultvalue = 0) { $linkageid = intval($linkageid); $datas = array(); $datas = getcache($linkageid,'linkage'); $infos = $datas['data']; $title = $defaultvalue ? $infos[$defaultvalue]['name'] : $datas['title']; $colObj = random(3).date('is'); $string = ''; if(!defined('LINKAGE_INIT')) { define('LINKAGE_INIT', 1); $string .= '<script type="text/javascript" src="'.JS_PATH.'linkage/js/mln.colselect.js"></script>'; if(defined('IN_ADMIN')) { $string .= '<link href="'.JS_PATH.'linkage/style/admin.css" rel="stylesheet" type="text/css">'; } else { $string .= '<link href="'.JS_PATH.'linkage/style/css.css" rel="stylesheet" type="text/css">'; } } $string .= '<input type="hidden" name="info['.$id.']" value="1"><div id="'.$id.'"></div>'; $string .= '<script type="text/javascript">'; $string .= 'var colObj'.$colObj.' = {"Items":['; foreach($infos AS $k=>$v) { $s .= '{"name":"'.$v['name'].'","topid":"'.$v['parentid'].'","colid":"'.$k.'","value":"'.$k.'","fun":function(){}},'; } $string .= substr($s, 0, -1); $string .= ']};'; $string .= '$("#'.$id.'").mlnColsel(colObj'.$colObj.',{'; $string .= 'title:"'.$title.'",'; $string .= 'value:"'.$defaultvalue.'",'; $string .= 'width:100'; $string .= '});'; $string .= '</script>'; return $string; } /** * 判断字符串是否为utf8编码,英文和半角字符返回ture * @param $string * @return bool */ function is_utf8($string) { return preg_match('%^(?: [\x09\x0A\x0D\x20-\x7E] # ASCII | [\xC2-\xDF][\x80-\xBF] # non-overlong 2-byte | \xE0[\xA0-\xBF][\x80-\xBF] # excluding overlongs | [\xE1-\xEC\xEE\xEF][\x80-\xBF]{2} # straight 3-byte | \xED[\x80-\x9F][\x80-\xBF] # excluding surrogates | \xF0[\x90-\xBF][\x80-\xBF]{2} # planes 1-3 | [\xF1-\xF3][\x80-\xBF]{3} # planes 4-15 | \xF4[\x80-\x8F][\x80-\xBF]{2} # plane 16 )*$%xs', $string); } /** * 获取UCenter数据库配置 */ function get_uc_database() { $config = pc_base::load_config('system'); return array ( 'hostname' => $config['uc_dbhost'], 'database' => $config['uc_dbname'], 'username' => $config['uc_dbuser'], 'password' => $config['uc_dbpw'], 'tablepre' => $config['uc_dbtablepre'], 'charset' => $config['uc_dbcharset'], 'type' => 'mysql', 'debug' => true, 'pconnect' => 0, 'autoconnect' => 0 ); } ?>
PHP
<?php defined('IN_PHPCMS') or exit('No permission resources.'); pc_base::load_sys_class('model', '', 0); class messagequeue_model extends model { public function __construct() { $this->db_config = pc_base::load_config('database'); $this->db_setting = 'default'; $this->table_name = 'messagequeue'; parent::__construct(); } } ?>
PHP
<?php defined('IN_PHPCMS') or exit('No permission resources.'); pc_base::load_sys_class('model', '', 0); class credit_model extends model { public function __construct() { $this->db_config = pc_base::load_config('database'); $this->db_setting = 'default'; $this->table_name = 'members'; parent::__construct(); } } ?>
PHP
<?php defined('IN_PHPCMS') or exit('No permission resources.'); pc_base::load_sys_class('model', '', 0); class admin_model extends model { public function __construct() { $this->db_config = pc_base::load_config('database'); $this->db_setting = 'default'; $this->table_name = 'admin'; parent::__construct(); } } ?>
PHP
<?php defined('IN_PHPCMS') or exit('No permission resources.'); pc_base::load_sys_class('model', '', 0); class session_model extends model { public function __construct() { $this->db_config = pc_base::load_config('database'); $this->db_setting = 'default'; $this->table_name = 'session'; parent::__construct(); } } ?>
PHP
<?php defined('IN_PHPCMS') or exit('No permission resources.'); pc_base::load_sys_class('model', '', 0); class uc_model extends model { public function __construct($db_config) { $this->db_config = array('ucenter'=>$db_config); $this->db_setting = 'ucenter'; $this->table_name = 'members'; parent::__construct(); } } ?>
PHP
<?php defined('IN_PHPCMS') or exit('No permission resources.'); pc_base::load_sys_class('model', '', 0); class member_model extends model { public function __construct() { $this->db_config = pc_base::load_config('database'); $this->db_setting = 'default'; $this->table_name = 'members'; parent::__construct(); } public function get_version() { return $this->db->version(); } public function get_table_status() { $this->db->query("SHOW TABLE STATUS LIKE '$this->db_tablepre%'"); $datalist = array(); while(($rs = $this->db->fetch_next()) != false) { $datalist[] = $rs; } $this->db->free_result(); return $datalist; } } ?>
PHP
<?php defined('IN_PHPCMS') or exit('No permission resources.'); pc_base::load_sys_class('model', '', 0); class member_model extends model { public function __construct() { $this->db_config = pc_base::load_config('database'); $this->db_setting = 'default'; $this->table_name = 'members'; parent::__construct(); } } ?>
PHP
<?php defined('IN_PHPCMS') or exit('No permission resources.'); pc_base::load_sys_class('model', '', 0); class settings_model extends model { public function __construct() { $this->db_config = pc_base::load_config('database'); $this->db_setting = 'default'; $this->table_name = 'settings'; parent::__construct(); } } ?>
PHP
<?php defined('IN_PHPCMS') or exit('No permission resources.'); pc_base::load_sys_class('model', '', 0); class applications_model extends model { public function __construct() { $this->db_config = pc_base::load_config('database'); $this->db_setting = 'default'; $this->table_name = 'applications'; parent::__construct(); } } ?>
PHP
<?php ?>
PHP
<?php $LANG['nameerror'] = '用户名不能为空。'; $LANG['checkcode'] = '验证码'; $LANG['click_change_validate'] = '单击更换验证码'; $LANG['code_error'] = '验证码错误'; $LANG['input_code'] = '请输入验证码'; $LANG['jump_message'] = '如果您的浏览器没有自动跳转,请点击这里'; $LANG['alert_message'] = '提示信息'; $LANG['go_history'] = '[点这里返回上一页]'; $LANG['register_setting'] = '注册配置'; $LANG['uc_setting'] = 'UCenter配置'; $LANG['sp4_password_compatible'] = 'php2008 sp4密码兼容'; $LANG['denyed_username'] = '禁止注册的用户名:'; $LANG['denyed_username_setting'] = '可以设置通配符,每个关键字一行,可使用通配符 * 如 陈*桥'; $LANG['denyed_email'] = '禁止注册的email:'; $LANG['denyed_email_setting'] = '可以设置通配符,每个email一行,可使用通配符 * 如 *@snda.com'; $LANG['uc_notice'] = '如果开启UCenter接口,以下所有项均为必填项。'; $LANG['enable'] = '是否启用:'; $LANG['uc_api_host'] = 'Ucenter api 地址:'; $LANG['uc_host_notice'] = '如 http://www.domain.com/ucenter 最后不要带斜线'; $LANG['uc_ip_notice'] = '一般不用填写,遇到无法同步时,请填写ucenter主机的IP地址'; $LANG['uc_db_host'] = 'Ucenter 数据库主机名:'; $LANG['uc_db_username'] = 'Ucenter 数据库用户名:'; $LANG['uc_db_password'] = 'Ucenter 数据库密码:'; $LANG['uc_dbname'] = 'Ucenter 数据库名:'; $LANG['uc_db_pre'] = 'Ucenter 数据库表前缀:'; $LANG['uc_db_charset'] = 'Ucenter 数据库字符集:'; $LANG['please_select'] = '请选择'; $LANG['uc_test_database'] = '测试数据连连接'; $LANG['uc_appid'] = '应用id(APP ID):'; $LANG['uc_key'] = 'Ucenter 通信密钥:'; $LANG['sp4_password_key'] = 'php2008 SP4 config.inc中 define(\'PASSWORD_KEY\', \'\'); 中的值(可以为空)'; $LANG['between_6_to_20'] = '应该为6-20位之间'; $LANG['password_can_not_be_empty'] = '密码不能为空。'; $LANG['means_code'] = '请输入重复密码。'; $LANG['login_succeeded'] = '登陆成功!'; $LANG['logout_succeeded'] = '退出成功'; $LANG['add_admin'] = '添加管理员'; $LANG['listadmins'] = '管理员列表'; $LANG['lastlogintime'] = '最后登陆'; $LANG['landing_ip'] = '登陆IP'; $LANG['subminiature_tube'] = '超级管理员'; $LANG['administrator'] = '管理员'; $LANG['least_there_is_a_super_administrator'] = '最少有一个超级管理员。'; $LANG['input'] = '请输入'; $LANG['connecting_please_wait'] = '请稍候...'; $LANG['charset'] = '字符集'; $LANG['synlogin'] = '同步登陆'; $LANG['apifilename'] = '通信文件'; $LANG['the_password_cannot_be_empty'] = '原密码不能为空。'; $LANG['new_password_cannot_be_empty'] = '新密码不能为空。'; $LANG['the_two_passwords_are_not_the_same_admin_zh'] = '两次密码不同。'; $LANG['old_password_incorrect'] = '原密码错误。'; $LANG['email_format_incorrect'] = '电子邮箱格式错误'; $LANG['format_incorrect'] = '格式错误'; $LANG['notice_format'] = '请注意格式'; $LANG['right'] = '正确'; $LANG['old_password_incorrect'] = '原密码错误。'; $LANG['not_change_the_password_please_leave_a_blank'] = '不修改密码请留空。'; $LANG['change_password'] = '修改密码'; $LANG['current_password'] = '原密码'; $LANG['new_password'] = '新密码'; $LANG['re_password'] = '重复密码'; $LANG['inputpassword'] = '请输入密码'; $LANG['bootos_x'] = '再次输入'; $LANG['modification_succeed'] = '修改管理员信息'; $LANG['application_list'] = '应用列表'; $LANG['application_add'] = '添加应用'; $LANG['application_edit'] = '编辑应用'; $LANG['application_name'] = '应用名'; $LANG['application_url'] = '应用地址'; $LANG['application_url_msg'] = '应用的访问地址,请以"/"结尾。如:http://www.phpcms.cn/'; $LANG['application_ip'] = '应用ip'; $LANG['application_ip_msg'] = '当应用URL无法访问时,使用IP进行访问。'; $LANG['application_status'] = '应用状态'; $LANG['application_apifilename'] = '通信文件'; $LANG['application_charset'] = '字符集'; $LANG['application_synlogin'] = '同步登陆'; $LANG['communications_status'] = '通信状态'; $LANG['authkey'] = '通信密钥'; $LANG['automatic_generation'] = '自动生成'; $LANG['regip'] = '注册ip'; $LANG['can_not_be_empty'] = '不能为空'; $LANG['exist'] = '已存在'; $LANG['application_not_exist'] = '应用不存在'; $LANG['can_not_be_empty'] = '不能为空'; $LANG['is_succeed'] = '是否成功'; $LANG['notice_num'] = '通信次数'; $LANG['notice_dateline'] = '通信时间'; $LANG['notice_status'] = '通信状态'; $LANG['table_size'] = '表大小'; $LANG['index_size'] = '索引大小'; $LANG['notice_data'] = '通信数据'; $LANG['notice_id'] = '消息ID'; $LANG['notice_success'] = '通信成功'; $LANG['notice_fail'] = '通信失败'; $LANG['notice_data'] = '通信数据'; $LANG['cache_size'] = '缓存大小'; $LANG['last_modify_time'] = '最后修改时间'; $LANG['clean_applist_cache'] = '更新应用列表缓存'; $LANG['credit_add'] = '添加积分规则'; $LANG['credit_manage'] = '管理积分规则'; $LANG['pleace_select'] = '请选择'; $LANG['change_credit'] = '积分兑换'; $LANG['change_position'] = '兑换方向'; $LANG['change_rate'] = '兑换比率'; $LANG['testing_communication'] = '通信测试中...'; $LANG['communication_success'] = '通信成功'; $LANG['communication_failure'] = '通信失败'; $LANG['view'] = '查看'; $LANG['change_pos'] = '兑换方向'; $LANG['change_rate'] = '兑换比例'; $LANG['id'] = 'ID'; $LANG['credit_update'] = '更新积分规则'; $LANG['avatar'] = '头像'; $LANG['version_info'] = '版本信息'; $LANG['application_info'] = '应用信息'; $LANG['member_info'] = '用户信息'; $LANG['member_total'] = '用户总计'; $LANG['member_today'] = '今日新增:'; $LANG['queue_info'] = '消息队列'; $LANG['system_info'] = '系统信息'; $LANG['server_info'] = '服务器环境'; $LANG['host_info'] = '主机名'; $LANG['php_info'] = 'PHP信息'; $LANG['mysql_info'] = 'Mysql信息'; $LANG['mysql_version'] = 'Mysql版本'; $LANG['service_info'] = '开发团队'; $LANG['development_team'] = '技术团队'; $LANG['design_team'] = '美工团队'; $LANG['phpcms_chenzhouyu'] = '陈周瑜'; $LANG['phpcms_wangtiecheng'] = '王铁成'; $LANG['phpcms_dongfeilong'] = '董飞龙'; $LANG['connect_success'] = '连接成功!'; $LANG['connect_failed'] = '连接失败!';
PHP
<?php $LANG['illegal_operation'] = '非法操作!'; $LANG['illegal_action'] = '非法动作参数!请返回'; $LANG['illegal_parameters'] = '非法参数!'; $LANG['operation_success'] = '操作成功!'; $LANG['operation_failure'] = '操作失败!'; $LANG['total'] = '总数:'; $LANG['first'] = '首页'; $LANG['success'] = '成功'; $LANG['previous'] = '上一页'; $LANG['next'] = '下一页'; $LANG['last'] = '尾页'; $LANG['page'] = '页次:'; $LANG['serial'] = '第'; $LANG['page'] = '页:'; $LANG['User_name_could_not_find'] = '用户名没有找到。'; $LANG['user_not_exist'] = '用户不存在'; $LANG['incorrect_password'] = '密码错误。'; $LANG['unknown_error'] = '未知错误。'; $LANG['user_already_exist'] = '用户已存在。'; $LANG['password_len_error'] = '密码必须为6-20位之间'; $LANG['database_error'] = '数据库错误'; $LANG['relogin'] = '您还没有登陆或登陆已经过期,请重新登陆。'; $LANG['eaccess'] = '权限不足。'; $LANG['select_all'] = '全选'; $LANG['username'] = '用户名'; $LANG['password'] = '密&nbsp;&nbsp;&nbsp;码'; $LANG['email'] = '电子邮箱'; $LANG['email_already_exist'] = '电子邮箱已经存在'; $LANG['application'] = '应用'; $LANG['regtime'] = '注册时间'; $LANG['regip'] = '注册ip'; $LANG['lastlogintime'] = '最后登录'; $LANG['operation'] = '操作'; $LANG['edit'] = '编辑'; $LANG['delete'] = '删除'; $LANG['commend'] = '推荐'; $LANG['search'] = '搜索'; $LANG['type'] = '类型'; $LANG['submit'] = '提交'; $LANG['cancel'] = '取消'; $LANG['loging'] = '登&nbsp;录'; $LANG['yes'] = '是'; $LANG['no'] = '否'; $LANG['phpsso'] = 'PHP用户管理中心'; $LANG['manage_center'] = '管理中心'; $LANG['loading'] = '加载中'; $LANG['hellow'] = '您好!'; $LANG['logout'] = '退出'; $LANG['site_index'] = '站点首页'; $LANG['index'] = '首页'; $LANG['member_search'] = '会员搜索'; $LANG['first_page'] = '首页'; $LANG['account_setting'] = '账号设置'; $LANG['member_manage'] = '用户管理'; $LANG['member_add'] = '添加用户'; $LANG['member_edit'] = '修改用户'; $LANG['member_delete'] = '删除用户'; $LANG['uid'] = '用户ID'; $LANG['application_manage'] = '应用管理'; $LANG['communicate_info'] = '通信信息'; $LANG['admin_manage'] = '管理员管理'; $LANG['credit_change'] = '积分兑换'; $LANG['system_setting'] = '系统设置'; $LANG['clean_cache'] = '更新缓存'; $LANG['admin_manage'] = '管理员管理'; $LANG['sure_delete'] = '您确定要删除吗?'; $LANG['expand'] = '展开'; $LANG['spread_or_closed'] = '展开与关闭'; $LANG['local'] = '当前位置: 首页 > '; $LANG['no_language'] = '没有语言包'; $LANG['other'] = '其他'; $LANG['ucenter_error_code'] = 'ucenter返回错误,错误代码:{code}。'; ?>
PHP
<?php param::set_cookie('username', ''); param::set_cookie('userid', '');
PHP
<?php $username = isset($_GET['username']) && trim($_GET['username']) ? trim($_GET['username']) : exit('-1'); $password = isset($_GET['password']) && trim($_GET['password']) ? trim($_GET['password']) : exit('-1'); $url = isset($_GET['url']) && trim($_GET['url']) ? trim(urldecode($_GET['url'])) : exit('-1'); $name = isset($_GET['name']) && trim($_GET['name']) ? trim($_GET['name']) : exit('-1'); $authkey = isset($_GET['authkey']) && trim($_GET['authkey']) ? trim($_GET['authkey']) : exit('-1'); $apifilename = isset($_GET['apifilename']) && trim($_GET['apifilename']) ? trim($_GET['apifilename']) : exit('-1'); $charset = isset($_GET['charset']) && trim($_GET['charset']) ? trim($_GET['charset']) : exit('-1'); $type = isset($_GET['type']) && trim($_GET['type']) ? trim($_GET['type']) : 'other'; $synlogin = isset($_GET['synlogin']) && trim($_GET['synlogin']) ? trim($_GET['synlogin']) : '1'; $db = pc_base::load_model('admin_model'); $memberinfo = $db->get_one(array('username'=>$username)); if(!empty($memberinfo)) { if(md5(md5($password).$memberinfo['encrypt']) == $memberinfo['password']) { $appdb = pc_base::load_model('applications_model'); $appdata['authkey'] = $authkey; $appdata['apifilename'] = $apifilename; $appdata['charset'] = $charset; $appdata['type'] = $type; $appdata['synlogin'] = $synlogin; $appdata['url'] = $url; $appdata['name'] = $name; $appid = $appdb->insert($appdata, 1); if($appid > 0) { $applist = $appdb->listinfo('', '', 1, 100, 'appid'); setcache('applist', $applist, 'admin'); echo $appid;exit; } else { exit('-3'); } } else { exit('-2'); } } else { exit('-2'); } ?>
PHP
<?php error_reporting(0); define('PHPCMS_PATH', dirname(__FILE__).'/../'); include PHPCMS_PATH.'/phpcms/base.php'; define('UC_KEY', pc_base::load_config('system', 'uc_key')); define('API_RETURN_SUCCEED', '1'); define('API_RETURN_FAILED', '-1'); define('API_RETURN_FORBIDDEN', '-2'); $get = $post = array(); $code = @$_GET['code']; parse_str(authcode($code, 'DECODE', UC_KEY), $get); if(SYS_TIME - $get['time'] > 3600) exit('Authracation has expiried'); if(empty($get)) exit('Invalid Request'); include dirname(__FILE__).'/uc_client/lib/xml.class.php'; $post = xml_unserialize(file_get_contents('php://input')); $action = $get['action']; if(in_array($get['action'], array('test', 'deleteuser', 'renameuser', 'gettag', 'synlogin', 'synlogout', 'updatepw', 'updatebadwords', 'updatehosts', 'updateapps', 'updateclient', 'updatecredit', 'getcreditsettings', 'updatecreditsettings'))) { $uc_note = new uc_note(); header('Content-type: text/html; charset='.pc_base::load_config('system', 'charset')); echo $uc_note->$get['action']($get, $post); exit(); } else { exit(API_RETURN_FAILED); } class uc_note { private $member_db, $uc_db, $applist; function __construct() { $this->member_db = pc_base::load_model('member_model'); pc_base::load_sys_class('uc_model', 'model', 0); $db_config = get_uc_database(); $this->uc_db = new uc_model($db_config); $this->applist = getcache('applist', 'admin'); } //测试通信 public function test() { return API_RETURN_SUCCEED; } //删除用户 public function deleteuser($get,$post) { pc_base::load_app_func('global', 'admin'); pc_base::load_app_class('messagequeue', 'admin' , 0); $ids = new_stripslashes($get['ids']); $s = $this->member_db->select("ucuserid in ($ids)", "uid"); $this->member_db->delete("ucuserid in ($ids)"); $noticedata['uids'] = array(); if ($s) { foreach ($s as $key=>$v) { $noticedata['uids'][$key] = $v['uid']; } } else { return API_RETURN_FAILED; } messagequeue::add('member_delete', $noticedata); return API_RETURN_SUCCEED; } //更改用户密码 public function updatepw($get,$post) { $username = $get['username']; $r = $this->uc_db->get_one(array('username'=>$username)); if ($r) { $this->member_db->update(array('password'=>$r['password'], 'random'=>$r['salt']), array('username'=>$username)); } return API_RETURN_SUCCEED; } //更改一个用户的用户名 public function renameuser($get, $post) { return API_RETURN_SUCCEED; } //同步登录 public function synlogin($get,$post) { header('P3P: CP="CURa ADMa DEVa PSAo PSDo OUR BUS UNI PUR INT DEM STA PRE COM NAV OTC NOI DSP COR"'); $uid = intval($get['uid']); if (empty($uid)) return API_RETURN_FAILED; //获取UC中用户的信息 $r = $this->uc_db->get_one(array('uid'=>$uid)); if ($data = $this->member_db->get_one(array('ucuserid'=>$uid))) {//当用户存在时,获取用户的登陆信息 $this->member_db->update(array('lastip'=>$r['lastloginip'], 'lastdate'=>$r['lastlogindate']), array('uid'=>$data['uid'])); } else { //当用户不存在是注册新用户 $datas = $data = array('username'=>$r['username'], 'password'=>$r['password'], 'random'=>$r['salt'], 'email'=>$r['email'], 'regip'=>$r['regip'], 'regdate'=>$r['regdate'], 'lastdate'=>$r['lastlogindate'], 'appname'=>'ucenter', 'type'=>'app'); $datas['ucuserid'] = $uid; $datas['lastip'] = $r['lastloginip']; if ($s = $this->member_db->get_one(array('username'=>$r['username']))) { $this->member_db->update($datas, array('uid'=>$s['uid'])); $data['uid'] = $s; } else { $data['uid'] = $this->member_db->insert($datas, true); } //向所有的应用中发布新用户注册通知 pc_base::load_app_func('global', 'admin'); pc_base::load_app_class('messagequeue', 'admin' , 0); messagequeue::add('member_add', $data); } //输出应用登陆 $res = ''; foreach($this->applist as $v) { if (!$v['synlogin']) continue; $f = strstr($v['url'].$v['apifilename'], '?') ? '&' : '?'; $res .= '<script type="text/javascript" src="'.$v['url'].$v['apifilename'].$f.'time='.SYS_TIME.'&code='.urlencode(sys_auth('action=synlogin&username=&uid='.$data['uid'].'&password=&time='.SYS_TIME, 'ENCODE', $v['authkey'])).'" reload="1"></script>'; } header("Content-type: text/javascript"); return format_js($res); } //同步退出登录 public function synlogout($get, $post) { $res = ''; foreach($this->applist as $v) { if($v['appid'] != $this->appid) { $f = strstr($v['url'].$v['apifilename'], '?') ? '&' : '?'; $res .= '<script type="text/javascript" src="'.$v['url'].$v['apifilename'].$f.'time='.SYS_TIME.'&code='.urlencode(sys_auth('action=synlogout&time='.SYS_TIME, 'ENCODE', $v['authkey'])).'" reload="1"></script>'; } } header("Content-type: text/javascript"); return format_js($res); } //当 UCenter 的应用程序列表变更时 public function updateapps() { return API_RETURN_SUCCEED; } } function authcode($string, $operation = 'DECODE', $key = '', $expiry = 0) { $ckey_length = 4; $key = md5($key ? $key : UC_KEY); $keya = md5(substr($key, 0, 16)); $keyb = md5(substr($key, 16, 16)); $keyc = $ckey_length ? ($operation == 'DECODE' ? substr($string, 0, $ckey_length): substr(md5(microtime()), -$ckey_length)) : ''; $cryptkey = $keya.md5($keya.$keyc); $key_length = strlen($cryptkey); $string = $operation == 'DECODE' ? base64_decode(substr($string, $ckey_length)) : sprintf('%010d', $expiry ? $expiry + time() : 0).substr(md5($string.$keyb), 0, 16).$string; $string_length = strlen($string); $result = ''; $box = range(0, 255); $rndkey = array(); for($i = 0; $i <= 255; $i++) { $rndkey[$i] = ord($cryptkey[$i % $key_length]); } for($j = $i = 0; $i < 256; $i++) { $j = ($j + $box[$i] + $rndkey[$i]) % 256; $tmp = $box[$i]; $box[$i] = $box[$j]; $box[$j] = $tmp; } for($a = $j = $i = 0; $i < $string_length; $i++) { $a = ($a + 1) % 256; $j = ($j + $box[$a]) % 256; $tmp = $box[$a]; $box[$a] = $box[$j]; $box[$j] = $tmp; $result .= chr(ord($string[$i]) ^ ($box[($box[$a] + $box[$j]) % 256])); } if($operation == 'DECODE') { if((substr($result, 0, 10) == 0 || substr($result, 0, 10) - time() > 0) && substr($result, 10, 16) == substr(md5(substr($result, 26).$keyb), 0, 16)) { return substr($result, 26); } else { return ''; } } else { return $keyc.str_replace('=', '', base64_encode($result)); } } function uc_serialize($arr, $htmlon = 0) { include_once UC_CLIENT_ROOT.'./lib/xml.class.php'; return xml_serialize($arr, $htmlon); } function uc_unserialize($s) { include_once UC_CLIENT_ROOT.'./lib/xml.class.php'; return xml_unserialize($s); }
PHP
<?php $session_storage = 'session_'.pc_base::load_config('system','session_storage'); pc_base::load_sys_class($session_storage); session_start(); $checkcode = pc_base::load_sys_class('checkcode'); if (isset($_GET['code_len']) && intval($_GET['code_len'])) $checkcode->code_len = intval($_GET['code_len']); if (isset($_GET['font_size']) && intval($_GET['font_size'])) $checkcode->font_size = intval($_GET['font_size']); if (isset($_GET['width']) && intval($_GET['width'])) $checkcode->width = intval($_GET['width']); if (isset($_GET['height']) && intval($_GET['height'])) $checkcode->height = intval($_GET['height']); if (isset($_GET['font']) && trim(urldecode($_GET['font']))) $checkcode->font = trim(urldecode($_GET['font'])); if (isset($_GET['font_color']) && trim(urldecode($_GET['font_color']))) $checkcode->font_color = trim(urldecode($_GET['font_color'])); if (isset($_GET['background']) && trim(urldecode($_GET['background']))) $checkcode->background = trim(urldecode($_GET['background'])); $checkcode->doimage(); $_SESSION['code']=$checkcode->get_code(); ?>
PHP
<?php /* [UCenter] (C)2001-2009 Comsenz Inc. This is NOT a freeware, use is subject to license terms $Id: mail.php 753 2008-11-14 06:48:25Z cnteacher $ */ !defined('IN_UC') && exit('Access Denied'); class mailcontrol extends base { function __construct() { $this->mailcontrol(); } function mailcontrol() { parent::__construct(); $this->init_input(); } function onadd() { $this->load('mail'); $mail = array(); $mail['appid'] = UC_APPID; $mail['uids'] = explode(',', $this->input('uids')); $mail['emails'] = explode(',', $this->input('emails')); $mail['subject'] = $this->input('subject'); $mail['message'] = $this->input('message'); $mail['charset'] = $this->input('charset'); $mail['htmlon'] = intval($this->input('htmlon')); $mail['level'] = abs(intval($this->input('level'))); $mail['frommail'] = $this->input('frommail'); $mail['dateline'] = $this->time; return $_ENV['mail']->add($mail); } } ?>
PHP
<?php /* [UCenter] (C)2001-2009 Comsenz Inc. This is NOT a freeware, use is subject to license terms $Id: pm.php 836 2008-12-05 02:25:48Z monkey $ */ !defined('IN_UC') && exit('Access Denied'); define('PMLIMIT1DAY_ERROR', -1); define('PMFLOODCTRL_ERROR', -2); define('PMMSGTONOTFRIEND', -3); define('PMSENDREGDAYS', -4); class pmcontrol extends base { function __construct() { $this->pmcontrol(); } function pmcontrol() { parent::__construct(); $this->load('user'); $this->load('pm'); } function oncheck_newpm() { $this->init_input(); $this->user['uid'] = intval($this->input('uid')); $more = $this->input('more'); $result = $_ENV['pm']->check_newpm($this->user['uid'], $more); if($more == 3) { require_once UC_ROOT.'lib/uccode.class.php'; $this->uccode = new uccode(); $result['lastmsg'] = $this->uccode->complie($result['lastmsg']); } return $result; } function onsendpm() { $this->init_input(); $fromuid = $this->input('fromuid'); $msgto = $this->input('msgto'); $subject = $this->input('subject'); $message = $this->input('message'); $replypmid = $this->input('replypmid'); $isusername = $this->input('isusername'); if($fromuid) { $user = $_ENV['user']->get_user_by_uid($fromuid); $user = daddslashes($user, 1); if(!$user) { return 0; } $this->user['uid'] = $user['uid']; $this->user['username'] = $user['username']; } else { $this->user['uid'] = 0; $this->user['username'] = ''; } if($replypmid) { $isusername = 1; $pms = $_ENV['pm']->get_pm_by_pmid($this->user['uid'], $replypmid); if($pms[0]['msgfromid'] == $this->user['uid']) { $user = $_ENV['user']->get_user_by_uid($pms[0]['msgtoid']); $msgto = $user['username']; } else { $msgto = $pms[0]['msgfrom']; } } $msgto = array_unique(explode(',', $msgto)); $isusername && $msgto = $_ENV['user']->name2id($msgto); $blackls = $_ENV['pm']->get_blackls($this->user['uid'], $msgto); if($fromuid) { if($this->settings['pmsendregdays']) { if($user['regdate'] > $this->time - $this->settings['pmsendregdays'] * 86400) { return PMSENDREGDAYS; } } $this->load('friend'); if(count($msgto) > 1 && !($is_friend = $_ENV['friend']->is_friend($fromuid, $msgto, 3))) { return PMMSGTONOTFRIEND; } $pmlimit1day = $this->settings['pmlimit1day'] && $_ENV['pm']->count_pm_by_fromuid($this->user['uid'], 86400) > $this->settings['pmlimit1day']; if($pmlimit1day || ($this->settings['pmfloodctrl'] && $_ENV['pm']->count_pm_by_fromuid($this->user['uid'], $this->settings['pmfloodctrl']))) { if(!$_ENV['friend']->is_friend($fromuid, $msgto, 3)) { if(!$_ENV['pm']->is_reply_pm($fromuid, $msgto)) { if($pmlimit1day) { return PMLIMIT1DAY_ERROR; } else { return PMFLOODCTRL_ERROR; } } } } } $lastpmid = 0; foreach($msgto as $uid) { if(!$fromuid || !in_array('{ALL}', $blackls[$uid])) { $blackls[$uid] = $_ENV['user']->name2id($blackls[$uid]); if(!$fromuid || isset($blackls[$uid]) && !in_array($this->user['uid'], $blackls[$uid])) { $lastpmid = $_ENV['pm']->sendpm($subject, $message, $this->user, $uid, $replypmid); } } } return $lastpmid; } function ondelete() { $this->init_input(); $this->user['uid'] = intval($this->input('uid')); $id = $_ENV['pm']->deletepm($this->user['uid'], $this->input('pmids')); return $id; } function ondeleteuser() { $this->init_input(); $this->user['uid'] = intval($this->input('uid')); $id = $_ENV['pm']->deleteuidpm($this->user['uid'], $this->input('touids')); return $id; } function onreadstatus() { $this->init_input(); $this->user['uid'] = intval($this->input('uid')); $_ENV['pm']->set_pm_status($this->user['uid'], $this->input('uids'), $this->input('pmids'), $this->input('status')); } function onignore() { $this->init_input(); $this->user['uid'] = intval($this->input('uid')); return $_ENV['pm']->set_ignore($this->user['uid']); } function onls() { $this->init_input(); $pagesize = $this->input('pagesize'); $folder = $this->input('folder'); $filter = $this->input('filter'); $page = $this->input('page'); $folder = in_array($folder, array('newbox', 'inbox', 'outbox', 'searchbox')) ? $folder : 'inbox'; if($folder != 'searchbox') { $filter = $filter ? (in_array($filter, array('newpm', 'privatepm', 'systempm', 'announcepm')) ? $filter : '') : ''; } $msglen = $this->input('msglen'); $this->user['uid'] = intval($this->input('uid')); if($folder != 'searchbox') { $pmnum = $_ENV['pm']->get_num($this->user['uid'], $folder, $filter); $start = $this->page_get_start($page, $pagesize, $pmnum); } else { $pmnum = $pagesize; $start = ($page - 1) * $pagesize; } if($pagesize > 0) { $pms = $_ENV['pm']->get_pm_list($this->user['uid'], $pmnum, $folder, $filter, $start, $pagesize); if(is_array($pms) && !empty($pms)) { foreach($pms as $key => $pm) { if($msglen) { $pms[$key]['message'] = htmlspecialchars($_ENV['pm']->removecode($pms[$key]['message'], $msglen)); } else { unset($pms[$key]['message']); } unset($pms[$key]['folder']); } } $result['data'] = $pms; } $result['count'] = $pmnum; return $result; } function onviewnode() { $this->init_input(); $this->user['uid'] = intval($this->input('uid')); $pmid = $_ENV['pm']->pmintval($this->input('pmid')); $type = $this->input('type'); $pm = $_ENV['pm']->get_pmnode_by_pmid($this->user['uid'], $pmid, $type); if($pm) { require_once UC_ROOT.'lib/uccode.class.php'; $this->uccode = new uccode(); $pm['message'] = $this->uccode->complie($pm['message']); return $pm; } } function onview() { $this->init_input(); $this->user['uid'] = intval($this->input('uid')); $touid = $this->input('touid'); $pmid = $_ENV['pm']->pmintval($this->input('pmid')); $daterange = $this->input('daterange'); if(empty($pmid)) { $daterange = empty($daterange) ? 1 : $daterange; $today = $this->time - ($this->time + $this->settings['timeoffset']) % 86400; if($daterange == 1) { $starttime = $today; } elseif($daterange == 2) { $starttime = $today - 86400; } elseif($daterange == 3) { $starttime = $today - 172800; } elseif($daterange == 4) { $starttime = $today - 604800; } elseif($daterange == 5) { $starttime = 0; } $endtime = $this->time; $pms = $_ENV['pm']->get_pm_by_touid($this->user['uid'], $touid, $starttime, $endtime); } else { $pms = $_ENV['pm']->get_pm_by_pmid($this->user['uid'], $pmid); } require_once UC_ROOT.'lib/uccode.class.php'; $this->uccode = new uccode(); $status = FALSE; foreach($pms as $key => $pm) { $pms[$key]['message'] = $this->uccode->complie($pms[$key]['message']); !$status && $status = $pm['msgtoid'] && $pm['new']; } $status && $_ENV['pm']->set_pm_status($this->user['uid'], $touid, $pmid); return $pms; } function onblackls_get() { $this->init_input(); $this->user['uid'] = intval($this->input('uid')); return $_ENV['pm']->get_blackls($this->user['uid']); } function onblackls_set() { $this->init_input(); $this->user['uid'] = intval($this->input('uid')); $blackls = $this->input('blackls'); return $_ENV['pm']->set_blackls($this->user['uid'], $blackls); } function onblackls_add() { $this->init_input(); $this->user['uid'] = intval($this->input('uid')); $username = $this->input('username'); return $_ENV['pm']->update_blackls($this->user['uid'], $username, 1); } function onblackls_delete($arr) { $this->init_input(); $this->user['uid'] = intval($this->input('uid')); $username = $this->input('username'); return $_ENV['pm']->update_blackls($this->user['uid'], $username, 2); } } ?>
PHP
<?php /* [UCenter] (C)2001-2009 Comsenz Inc. This is NOT a freeware, use is subject to license terms $Id: domain.php 753 2008-11-14 06:48:25Z cnteacher $ */ !defined('IN_UC') && exit('Access Denied'); class domaincontrol extends base { function __construct() { $this->domaincontrol(); } function domaincontrol() { parent::__construct(); $this->init_input(); $this->load('domain'); } function onls() { return $_ENV['domain']->get_list(1, 9999, 9999); } } ?>
PHP
<?php /* [UCenter] (C)2001-2009 Comsenz Inc. This is NOT a freeware, use is subject to license terms $Id: user.php 968 2009-10-29 02:06:45Z zhaoxiongfei $ */ !defined('IN_UC') && exit('Access Denied'); define('UC_USER_CHECK_USERNAME_FAILED', -1); define('UC_USER_USERNAME_BADWORD', -2); define('UC_USER_USERNAME_EXISTS', -3); define('UC_USER_EMAIL_FORMAT_ILLEGAL', -4); define('UC_USER_EMAIL_ACCESS_ILLEGAL', -5); define('UC_USER_EMAIL_EXISTS', -6); class usercontrol extends base { function __construct() { $this->usercontrol(); } function usercontrol() { parent::__construct(); $this->load('user'); $this->app = $this->cache['apps'][UC_APPID]; } // -1 未开启 function onsynlogin() { $this->init_input(); $uid = $this->input('uid'); if($this->app['synlogin']) { if($this->user = $_ENV['user']->get_user_by_uid($uid)) { $synstr = ''; foreach($this->cache['apps'] as $appid => $app) { if($app['synlogin'] && $app['appid'] != $this->app['appid']) { $synstr .= '<script type="text/javascript" src="'.$app['url'].'/api/uc.php?time='.$this->time.'&code='.urlencode($this->authcode('action=synlogin&username='.$this->user['username'].'&uid='.$this->user['uid'].'&password='.$this->user['password']."&time=".$this->time, 'ENCODE', $app['authkey'])).'"></script>'; } } return $synstr; } } return ''; } function onsynlogout() { $this->init_input(); if($this->app['synlogin']) { $synstr = ''; foreach($this->cache['apps'] as $appid => $app) { if($app['synlogin'] && $app['appid'] != $this->app['appid']) { $synstr .= '<script type="text/javascript" src="'.$app['url'].'/api/uc.php?time='.$this->time.'&code='.urlencode($this->authcode('action=synlogout&time='.$this->time, 'ENCODE', $app['authkey'])).'"></script>'; } } return $synstr; } return ''; } function onregister() { $this->init_input(); $username = $this->input('username'); $password = $this->input('password'); $email = $this->input('email'); $questionid = $this->input('questionid'); $answer = $this->input('answer'); $regip = $this->input('regip'); $random = $this->input('random'); if(($status = $this->_check_username($username)) < 0) { return $status; } if(($status = $this->_check_email($email)) < 0) { return $status; } $uid = $_ENV['user']->add_user($username, $password, $email, $random, 0, $questionid, $answer, $regip); return $uid; } function onedit() { $this->init_input(); $username = $this->input('username'); $oldpw = $this->input('oldpw'); $newpw = $this->input('newpw'); $email = $this->input('email'); $ignoreoldpw = $this->input('ignoreoldpw'); $questionid = $this->input('questionid'); $answer = $this->input('answer'); $salt = $this->input('salt'); if($email && ($status = $this->_check_email($email, $username)) < 0) { return $status; } $status = $_ENV['user']->edit_user($username, $oldpw, $newpw, $email, $salt, $ignoreoldpw, $questionid, $answer); if($newpw && $status > 0) { $this->load('note'); $_ENV['note']->add('updatepw', 'username='.urlencode($username).'&password='); $_ENV['note']->send(); } return $status; } function onlogin() { $this->init_input(); $isuid = $this->input('isuid'); $username = $this->input('username'); $password = $this->input('password'); $checkques = $this->input('checkques'); $questionid = $this->input('questionid'); $answer = $this->input('answer'); if($isuid == 1) { $user = $_ENV['user']->get_user_by_uid($username); } elseif($isuid == 2) { $user = $_ENV['user']->get_user_by_email($username); } else { $user = $_ENV['user']->get_user_by_username($username); } $passwordmd5 = preg_match('/^\w{32}$/', $password) ? $password : md5($password); if(empty($user)) { $status = -1; } elseif($user['password'] != md5($passwordmd5.$user['salt'])) { $status = -2; } elseif($checkques && $user['secques'] != '' && $user['secques'] != $_ENV['user']->quescrypt($questionid, $answer)) { $status = -3; } else { $status = $user['uid']; } $merge = $status != -1 && !$isuid && $_ENV['user']->check_mergeuser($username) ? 1 : 0; return array($status, $user['username'], $password, $user['email'], $merge); } function oncheck_email() { $this->init_input(); $email = $this->input('email'); return $this->_check_email($email); } function oncheck_username() { $this->init_input(); $username = $this->input('username'); if(($status = $this->_check_username($username)) < 0) { return $status; } else { return 1; } } function onget_user() { $this->init_input(); $username = $this->input('username'); if(!$this->input('isuid')) { $status = $_ENV['user']->get_user_by_username($username); } else { $status = $_ENV['user']->get_user_by_uid($username); } if($status) { return array($status['uid'],$status['username'],$status['email']); } else { return 0; } } function ongetprotected() { $protectedmembers = $this->db->fetch_all("SELECT uid,username FROM ".UC_DBTABLEPRE."protectedmembers GROUP BY username"); return $protectedmembers; } function ondelete() { $this->init_input(); $uid = $this->input('uid'); return $_ENV['user']->delete_user($uid); } function onaddprotected() { $this->init_input(); $username = $this->input('username'); $admin = $this->input('admin'); $appid = $this->app['appid']; $usernames = (array)$username; foreach($usernames as $username) { $user = $_ENV['user']->get_user_by_username($username); $uid = $user['uid']; $this->db->query("REPLACE INTO ".UC_DBTABLEPRE."protectedmembers SET uid='$uid', username='$username', appid='$appid', dateline='{$this->time}', admin='$admin'", 'SILENT'); } return $this->db->errno() ? -1 : 1; } function ondeleteprotected() { $this->init_input(); $username = $this->input('username'); $appid = $this->app['appid']; $usernames = (array)$username; foreach($usernames as $username) { $this->db->query("DELETE FROM ".UC_DBTABLEPRE."protectedmembers WHERE username='$username' AND appid='$appid'"); } return $this->db->errno() ? -1 : 1; } function onmerge() { $this->init_input(); $oldusername = $this->input('oldusername'); $newusername = $this->input('newusername'); $uid = $this->input('uid'); $password = $this->input('password'); $email = $this->input('email'); if(($status = $this->_check_username($newusername)) < 0) { return $status; } $uid = $_ENV['user']->add_user($newusername, $password, $email, $uid); $this->db->query("UPDATE ".UC_DBTABLEPRE."pms SET msgfrom='$newusername' WHERE msgfromid='$uid' AND msgfrom='$oldusername'"); $this->db->query("DELETE FROM ".UC_DBTABLEPRE."mergemembers WHERE appid='".$this->app['appid']."' AND username='$oldusername'"); return $uid; } function onmerge_remove() { $this->init_input(); $username = $this->input('username'); $this->db->query("DELETE FROM ".UC_DBTABLEPRE."mergemembers WHERE appid='".$this->app['appid']."' AND username='$username'"); return NULL; } function _check_username($username) { $username = addslashes(trim(stripslashes($username))); if(!$_ENV['user']->check_username($username)) { return UC_USER_CHECK_USERNAME_FAILED; } elseif(!$_ENV['user']->check_usernamecensor($username)) { return UC_USER_USERNAME_BADWORD; } elseif($_ENV['user']->check_usernameexists($username)) { return UC_USER_USERNAME_EXISTS; } return 1; } function _check_email($email, $username = '') { if(empty($this->settings)) { $this->settings = $this->cache('settings'); } if(!$_ENV['user']->check_emailformat($email)) { return UC_USER_EMAIL_FORMAT_ILLEGAL; } elseif(!$_ENV['user']->check_emailaccess($email)) { return UC_USER_EMAIL_ACCESS_ILLEGAL; } elseif(!$this->settings['doublee'] && $_ENV['user']->check_emailexists($email, $username)) { return UC_USER_EMAIL_EXISTS; } else { return 1; } } function onuploadavatar() { } function onrectavatar() { } function flashdata_decode($s) { } } ?>
PHP
<?php /* [UCenter] (C)2001-2009 Comsenz Inc. This is NOT a freeware, use is subject to license terms $Id: friend.php 753 2008-11-14 06:48:25Z cnteacher $ */ !defined('IN_UC') && exit('Access Denied'); class friendcontrol extends base { function __construct() { $this->friendcontrol(); } function friendcontrol() { parent::__construct(); $this->init_input(); $this->load('friend'); } function ondelete() { $uid = intval($this->input('uid')); $friendids = $this->input('friendids'); $id = $_ENV['friend']->delete($uid, $friendids); return $id; } function onadd() { $uid = intval($this->input('uid')); $friendid = $this->input('friendid'); $comment = $this->input('comment'); $id = $_ENV['friend']->add($uid, $friendid, $comment); return $id; } function ontotalnum() { $uid = intval($this->input('uid')); $direction = intval($this->input('direction')); $totalnum = $_ENV['friend']->get_totalnum_by_uid($uid, $direction); return $totalnum; } function onls() { $uid = intval($this->input('uid')); $page = intval($this->input('page')); $pagesize = intval($this->input('pagesize')); $totalnum = intval($this->input('totalnum')); $direction = intval($this->input('direction')); $pagesize = $pagesize ? $pagesize : UC_PPP; $totalnum = $totalnum ? $totalnum : $_ENV['friend']->get_totalnum_by_uid($uid); $data = $_ENV['friend']->get_list($uid, $page, $pagesize, $totalnum, $direction); return $data; } } ?>
PHP
<?php /* [UCenter] (C)2001-2009 Comsenz Inc. This is NOT a freeware, use is subject to license terms $Id: app.php 884 2008-12-16 01:13:31Z monkey $ */ !defined('IN_UC') && exit('Access Denied'); class appcontrol extends base { function __construct() { $this->appcontrol(); } function appcontrol() { parent::__construct(); $this->load('app'); } function onls() { $this->init_input(); $applist = $_ENV['app']->get_apps('appid, type, name, url, tagtemplates, viewprourl, synlogin'); $applist2 = array(); foreach($applist as $key => $app) { $app['tagtemplates'] = $this->unserialize($app['tagtemplates']); $applist2[$app['appid']] = $app; } return $applist2; } function onadd() { } function onucinfo() { } function _random($length, $numeric = 0) { } function _generate_key() { } function _format_notedata($notedata) { } } ?>
PHP
<?php /* [UCenter] (C)2001-2009 Comsenz Inc. This is NOT a freeware, use is subject to license terms $Id: feed.php 883 2008-12-16 00:51:21Z zhaoxiongfei $ */ !defined('IN_UC') && exit('Access Denied'); class feedcontrol extends base { function __construct() { $this->feedcontrol(); } function feedcontrol() { parent::__construct(); $this->init_input(); } function onadd() { $this->load('misc'); $appid = intval($this->input('appid')); $icon = $this->input('icon'); $uid = intval($this->input('uid')); $username = $this->input('username'); $body_data = $_ENV['misc']->array2string($this->input('body_data')); $title_data = $_ENV['misc']->array2string($this->input('title_data')); $title_template = $this->_parsetemplate($this->input('title_template')); $body_template = $this->_parsetemplate($this->input('body_template')); $body_general = $this->input('body_general'); $target_ids = $this->input('target_ids'); $image_1 = $this->input('image_1'); $image_1_link = $this->input('image_1_link'); $image_2 = $this->input('image_2'); $image_2_link = $this->input('image_2_link'); $image_3 = $this->input('image_3'); $image_3_link = $this->input('image_3_link'); $image_4 = $this->input('image_4'); $image_4_link = $this->input('image_4_link'); $hash_template = md5($title_template.$body_template); $hash_data = md5($title_template.$title_data.$body_template.$body_data); $dateline = $this->time; $this->db->query("INSERT INTO ".UC_DBTABLEPRE."feeds SET appid='$appid', icon='$icon', uid='$uid', username='$username', title_template='$title_template', title_data='$title_data', body_template='$body_template', body_data='$body_data', body_general='$body_general', image_1='$image_1', image_1_link='$image_1_link', image_2='$image_2', image_2_link='$image_2_link', image_3='$image_3', image_3_link='$image_3_link', image_4='$image_4', image_4_link='$image_4_link', hash_template='$hash_template', hash_data='$hash_data', target_ids='$target_ids', dateline='$dateline'"); return $this->db->insert_id(); } function ondelete() { $start = $this->input('start'); $limit = $this->input('limit'); $end = $start + $limit; $this->db->query("DELETE FROM ".UC_DBTABLEPRE."feeds WHERE feedid>'$start' AND feedid<'$end'"); } function onget() { $this->load('misc'); $limit = intval($this->input('limit')); $delete = $this->input('delete'); $feedlist = $this->db->fetch_all("SELECT * FROM ".UC_DBTABLEPRE."feeds ORDER BY feedid DESC LIMIT $limit"); if($feedlist) { $maxfeedid = $feedlist[0]['feedid']; foreach($feedlist as $key => $feed) { $feed['body_data'] = $_ENV['misc']->string2array($feed['body_data']); $feed['title_data'] = $_ENV['misc']->string2array($feed['title_data']); $feedlist[$key] = $feed; } } if(!empty($feedlist)) { if(!isset($delete) || $delete) { $this->_delete(0, $maxfeedid); } } return $feedlist; } function _delete($start, $end) { $this->db->query("DELETE FROM ".UC_DBTABLEPRE."feeds WHERE feedid>='$start' AND feedid<='$end'"); } function _parsetemplate($template) { $template = str_replace(array("\r", "\n"), '', $template); $template = str_replace(array('<br>', '<br />', '<BR>', '<BR />'), "\n", $template); $template = str_replace(array('<b>', '<B>'), '[B]', $template); $template = str_replace(array('<i>', '<I>'), '[I]', $template); $template = str_replace(array('<u>', '<U>'), '[U]', $template); $template = str_replace(array('</b>', '</B>'), '[/B]', $template); $template = str_replace(array('</i>', '</I>'), '[/I]', $template); $template = str_replace(array('</u>', '</U>'), '[/U]', $template); $template = htmlspecialchars($template); $template = nl2br($template); $template = str_replace(array('[B]', '[I]', '[U]', '[/B]', '[/I]', '[/U]'), array('<b>', '<i>', '<u>', '</b>', '</i>', '</u>'), $template); return $template; } } ?>
PHP
<?php /* [UCenter] (C)2001-2009 Comsenz Inc. This is NOT a freeware, use is subject to license terms $Id: tag.php 753 2008-11-14 06:48:25Z cnteacher $ */ !defined('IN_UC') && exit('Access Denied'); class tagcontrol extends base { function __construct() { $this->tagcontrol(); } function tagcontrol() { parent::__construct(); $this->init_input(); $this->load('tag'); $this->load('misc'); } function ongettag() { $appid = $this->input('appid'); $tagname = $this->input('tagname'); $nums = $this->input('nums'); if(empty($tagname)) { return NULL; } $return = $apparray = $appadd = array(); if($nums && is_array($nums)) { foreach($nums as $k => $num) { $apparray[$k] = $k; } } $data = $_ENV['tag']->get_tag_by_name($tagname); if($data) { $apparraynew = array(); foreach($data as $tagdata) { $row = $r = array(); $tmp = explode("\t", $tagdata['data']); $type = $tmp[0]; array_shift($tmp); foreach($tmp as $tmp1) { $tmp1 != '' && $r[] = $_ENV['misc']->string2array($tmp1); } if(in_array($tagdata['appid'], $apparray)) { if($tagdata['expiration'] > 0 && $this->time - $tagdata['expiration'] > 3600) { $appadd[] = $tagdata['appid']; $_ENV['tag']->formatcache($tagdata['appid'], $tagname); } else { $apparraynew[] = $tagdata['appid']; } $datakey = array(); $count = 0; foreach($r as $data) { $return[$tagdata['appid']]['data'][] = $data; $return[$tagdata['appid']]['type'] = $type; $count++; if($count >= $nums[$tagdata['appid']]) { break; } } } } $apparray = array_diff($apparray, $apparraynew); } else { foreach($apparray as $appid) { $_ENV['tag']->formatcache($appid, $tagname); } } if($apparray) { $this->load('note'); $_ENV['note']->add('gettag', "id=$tagname", '', $appadd, -1); } return $return; } } ?>
PHP
<?php /* [UCenter] (C)2001-2009 Comsenz Inc. This is NOT a freeware, use is subject to license terms $Id: cache.php 753 2008-11-14 06:48:25Z cnteacher $ */ !defined('IN_UC') && exit('Access Denied'); class cachecontrol extends base { function __construct() { $this->cachecontrol(); } function cachecontrol() { parent::__construct(); } function onupdate($arr) { $this->load("cache"); $_ENV['cache']->updatedata(); } } ?>
PHP
<?php /* [UCenter] (C)2001-2009 Comsenz Inc. This is NOT a freeware, use is subject to license terms $Id: client.php 963 2009-09-21 02:40:04Z zhaoxiongfei $ */ if(!defined('UC_API')) { exit('Access denied'); } error_reporting(0); define('IN_UC', TRUE); define('UC_CLIENT_VERSION', '1.5.1'); define('UC_CLIENT_RELEASE', '20100501'); define('UC_ROOT', substr(__FILE__, 0, -10)); define('UC_DATADIR', UC_ROOT.'./data/'); define('UC_DATAURL', UC_API.'/data'); define('UC_API_FUNC', UC_CONNECT == 'mysql' ? 'uc_api_mysql' : 'uc_api_post'); $GLOBALS['uc_controls'] = array(); function uc_addslashes($string, $force = 0, $strip = FALSE) { !defined('MAGIC_QUOTES_GPC') && define('MAGIC_QUOTES_GPC', get_magic_quotes_gpc()); if(!MAGIC_QUOTES_GPC || $force) { if(is_array($string)) { foreach($string as $key => $val) { $string[$key] = uc_addslashes($val, $force, $strip); } } else { $string = addslashes($strip ? stripslashes($string) : $string); } } return $string; } if(!function_exists('daddslashes')) { function daddslashes($string, $force = 0) { return uc_addslashes($string, $force); } } function uc_stripslashes($string) { !defined('MAGIC_QUOTES_GPC') && define('MAGIC_QUOTES_GPC', get_magic_quotes_gpc()); if(MAGIC_QUOTES_GPC) { return stripslashes($string); } else { return $string; } } function uc_api_post($module, $action, $arg = array()) { $s = $sep = ''; foreach($arg as $k => $v) { $k = urlencode($k); if(is_array($v)) { $s2 = $sep2 = ''; foreach($v as $k2 => $v2) { $k2 = urlencode($k2); $s2 .= "$sep2{$k}[$k2]=".urlencode(uc_stripslashes($v2)); $sep2 = '&'; } $s .= $sep.$s2; } else { $s .= "$sep$k=".urlencode(uc_stripslashes($v)); } $sep = '&'; } $postdata = uc_api_requestdata($module, $action, $s); return uc_fopen2(UC_API.'/index.php', 500000, $postdata, '', TRUE, UC_IP, 20); } function uc_api_requestdata($module, $action, $arg='', $extra='') { $input = uc_api_input($arg); $post = "m=$module&a=$action&inajax=2&release=".UC_CLIENT_RELEASE."&input=$input&appid=".UC_APPID.$extra; return $post; } function uc_api_url($module, $action, $arg='', $extra='') { $url = UC_API.'/index.php?'.uc_api_requestdata($module, $action, $arg, $extra); return $url; } function uc_api_input($data) { $s = urlencode(uc_authcode($data.'&agent='.md5($_SERVER['HTTP_USER_AGENT'])."&time=".time(), 'ENCODE', UC_KEY)); return $s; } function uc_api_mysql($model, $action, $args=array()) { global $uc_controls; if(empty($uc_controls[$model])) { include_once UC_ROOT.'./lib/db.class.php'; include_once UC_ROOT.'./model/base.php'; include_once UC_ROOT."./control/$model.php"; eval("\$uc_controls['$model'] = new {$model}control();"); } if($action{0} != '_') { $args = uc_addslashes($args, 1, TRUE); $action = 'on'.$action; $uc_controls[$model]->input = $args; return $uc_controls[$model]->$action($args); } else { return ''; } } function uc_serialize($arr, $htmlon = 0) { include_once UC_ROOT.'./lib/xml.class.php'; return xml_serialize($arr, $htmlon); } function uc_unserialize($s) { include_once UC_ROOT.'./lib/xml.class.php'; return xml_unserialize($s); } function uc_authcode($string, $operation = 'DECODE', $key = '', $expiry = 0) { $ckey_length = 4; $key = md5($key ? $key : UC_KEY); $keya = md5(substr($key, 0, 16)); $keyb = md5(substr($key, 16, 16)); $keyc = $ckey_length ? ($operation == 'DECODE' ? substr($string, 0, $ckey_length): substr(md5(microtime()), -$ckey_length)) : ''; $cryptkey = $keya.md5($keya.$keyc); $key_length = strlen($cryptkey); $string = $operation == 'DECODE' ? base64_decode(substr($string, $ckey_length)) : sprintf('%010d', $expiry ? $expiry + time() : 0).substr(md5($string.$keyb), 0, 16).$string; $string_length = strlen($string); $result = ''; $box = range(0, 255); $rndkey = array(); for($i = 0; $i <= 255; $i++) { $rndkey[$i] = ord($cryptkey[$i % $key_length]); } for($j = $i = 0; $i < 256; $i++) { $j = ($j + $box[$i] + $rndkey[$i]) % 256; $tmp = $box[$i]; $box[$i] = $box[$j]; $box[$j] = $tmp; } for($a = $j = $i = 0; $i < $string_length; $i++) { $a = ($a + 1) % 256; $j = ($j + $box[$a]) % 256; $tmp = $box[$a]; $box[$a] = $box[$j]; $box[$j] = $tmp; $result .= chr(ord($string[$i]) ^ ($box[($box[$a] + $box[$j]) % 256])); } if($operation == 'DECODE') { if((substr($result, 0, 10) == 0 || substr($result, 0, 10) - time() > 0) && substr($result, 10, 16) == substr(md5(substr($result, 26).$keyb), 0, 16)) { return substr($result, 26); } else { return ''; } } else { return $keyc.str_replace('=', '', base64_encode($result)); } } function uc_fopen2($url, $limit = 0, $post = '', $cookie = '', $bysocket = FALSE, $ip = '', $timeout = 15, $block = TRUE) { $__times__ = isset($_GET['__times__']) ? intval($_GET['__times__']) + 1 : 1; if($__times__ > 2) { return ''; } $url .= (strpos($url, '?') === FALSE ? '?' : '&')."__times__=$__times__"; return uc_fopen($url, $limit, $post, $cookie, $bysocket, $ip, $timeout, $block); } function uc_fopen($url, $limit = 0, $post = '', $cookie = '', $bysocket = FALSE, $ip = '', $timeout = 15, $block = TRUE) { $return = ''; $matches = parse_url($url); !isset($matches['host']) && $matches['host'] = ''; !isset($matches['path']) && $matches['path'] = ''; !isset($matches['query']) && $matches['query'] = ''; !isset($matches['port']) && $matches['port'] = ''; $host = $matches['host']; $path = $matches['path'] ? $matches['path'].($matches['query'] ? '?'.$matches['query'] : '') : '/'; $port = !empty($matches['port']) ? $matches['port'] : 80; if($post) { $out = "POST $path HTTP/1.0\r\n"; $out .= "Accept: */*\r\n"; //$out .= "Referer: $boardurl\r\n"; $out .= "Accept-Language: zh-cn\r\n"; $out .= "Content-Type: application/x-www-form-urlencoded\r\n"; $out .= "User-Agent: $_SERVER[HTTP_USER_AGENT]\r\n"; $out .= "Host: $host\r\n"; $out .= 'Content-Length: '.strlen($post)."\r\n"; $out .= "Connection: Close\r\n"; $out .= "Cache-Control: no-cache\r\n"; $out .= "Cookie: $cookie\r\n\r\n"; $out .= $post; } else { $out = "GET $path HTTP/1.0\r\n"; $out .= "Accept: */*\r\n"; //$out .= "Referer: $boardurl\r\n"; $out .= "Accept-Language: zh-cn\r\n"; $out .= "User-Agent: $_SERVER[HTTP_USER_AGENT]\r\n"; $out .= "Host: $host\r\n"; $out .= "Connection: Close\r\n"; $out .= "Cookie: $cookie\r\n\r\n"; } $fp = @fsockopen(($ip ? $ip : $host), $port, $errno, $errstr, $timeout); if(!$fp) { return ''; } else { stream_set_blocking($fp, $block); stream_set_timeout($fp, $timeout); @fwrite($fp, $out); $status = stream_get_meta_data($fp); if(!$status['timed_out']) { while (!feof($fp)) { if(($header = @fgets($fp)) && ($header == "\r\n" || $header == "\n")) { break; } } $stop = false; while(!feof($fp) && !$stop) { $data = fread($fp, ($limit == 0 || $limit > 8192 ? 8192 : $limit)); $return .= $data; if($limit) { $limit -= strlen($data); $stop = $limit <= 0; } } } @fclose($fp); return $return; } } function uc_app_ls() { $return = call_user_func(UC_API_FUNC, 'app', 'ls', array()); return UC_CONNECT == 'mysql' ? $return : uc_unserialize($return); } function uc_feed_add($icon, $uid, $username, $title_template='', $title_data='', $body_template='', $body_data='', $body_general='', $target_ids='', $images = array()) { return call_user_func(UC_API_FUNC, 'feed', 'add', array( 'icon'=>$icon, 'appid'=>UC_APPID, 'uid'=>$uid, 'username'=>$username, 'title_template'=>$title_template, 'title_data'=>$title_data, 'body_template'=>$body_template, 'body_data'=>$body_data, 'body_general'=>$body_general, 'target_ids'=>$target_ids, 'image_1'=>$images[0]['url'], 'image_1_link'=>$images[0]['link'], 'image_2'=>$images[1]['url'], 'image_2_link'=>$images[1]['link'], 'image_3'=>$images[2]['url'], 'image_3_link'=>$images[2]['link'], 'image_4'=>$images[3]['url'], 'image_4_link'=>$images[3]['link'] ) ); } function uc_feed_get($limit = 100, $delete = TRUE) { $return = call_user_func(UC_API_FUNC, 'feed', 'get', array('limit'=>$limit, 'delete'=>$delete)); return UC_CONNECT == 'mysql' ? $return : uc_unserialize($return); } function uc_friend_add($uid, $friendid, $comment='') { return call_user_func(UC_API_FUNC, 'friend', 'add', array('uid'=>$uid, 'friendid'=>$friendid, 'comment'=>$comment)); } function uc_friend_delete($uid, $friendids) { return call_user_func(UC_API_FUNC, 'friend', 'delete', array('uid'=>$uid, 'friendids'=>$friendids)); } function uc_friend_totalnum($uid, $direction = 0) { return call_user_func(UC_API_FUNC, 'friend', 'totalnum', array('uid'=>$uid, 'direction'=>$direction)); } function uc_friend_ls($uid, $page = 1, $pagesize = 10, $totalnum = 10, $direction = 0) { $return = call_user_func(UC_API_FUNC, 'friend', 'ls', array('uid'=>$uid, 'page'=>$page, 'pagesize'=>$pagesize, 'totalnum'=>$totalnum, 'direction'=>$direction)); return UC_CONNECT == 'mysql' ? $return : uc_unserialize($return); } function uc_user_register($username, $password, $email, $random, $questionid = '', $answer = '', $regip = '') { return call_user_func(UC_API_FUNC, 'user', 'register', array('username'=>$username, 'password'=>$password, 'random'=>$random, 'email'=>$email, 'questionid'=>$questionid, 'answer'=>$answer, 'regip' => $regip)); } function uc_user_login($username, $password, $isuid = 0, $checkques = 0, $questionid = '', $answer = '') { $isuid = intval($isuid); $return = call_user_func(UC_API_FUNC, 'user', 'login', array('username'=>$username, 'password'=>$password, 'isuid'=>$isuid, 'checkques'=>$checkques, 'questionid'=>$questionid, 'answer'=>$answer)); return UC_CONNECT == 'mysql' ? $return : uc_unserialize($return); } function uc_user_synlogin($uid) { $uid = intval($uid); $return = uc_api_post('user', 'synlogin', array('uid'=>$uid)); return $return; } function uc_user_synlogout() { return uc_api_post('user', 'synlogout', array()); } function uc_user_edit($username, $oldpw, $newpw, $email, $salt = '', $ignoreoldpw = 0, $questionid = '', $answer = '') { return call_user_func(UC_API_FUNC, 'user', 'edit', array('username'=>$username, 'oldpw'=>$oldpw, 'newpw'=>$newpw, 'salt'=>$salt, 'email'=>$email, 'ignoreoldpw'=>$ignoreoldpw, 'questionid'=>$questionid, 'answer'=>$answer)); } function uc_user_delete($uid) { return call_user_func(UC_API_FUNC, 'user', 'delete', array('uid'=>$uid)); } function uc_user_deleteavatar($uid) { uc_api_post('user', 'deleteavatar', array('uid'=>$uid)); } function uc_user_checkname($username) { return call_user_func(UC_API_FUNC, 'user', 'check_username', array('username'=>$username)); } function uc_user_checkemail($email) { return call_user_func(UC_API_FUNC, 'user', 'check_email', array('email'=>$email)); } function uc_user_addprotected($username, $admin='') { return call_user_func(UC_API_FUNC, 'user', 'addprotected', array('username'=>$username, 'admin'=>$admin)); } function uc_user_deleteprotected($username) { return call_user_func(UC_API_FUNC, 'user', 'deleteprotected', array('username'=>$username)); } function uc_user_getprotected() { $return = call_user_func(UC_API_FUNC, 'user', 'getprotected', array('1'=>1)); return UC_CONNECT == 'mysql' ? $return : uc_unserialize($return); } function uc_get_user($username, $isuid=0) { $return = call_user_func(UC_API_FUNC, 'user', 'get_user', array('username'=>$username, 'isuid'=>$isuid)); return UC_CONNECT == 'mysql' ? $return : uc_unserialize($return); } function uc_user_merge($oldusername, $newusername, $uid, $password, $email) { return call_user_func(UC_API_FUNC, 'user', 'merge', array('oldusername'=>$oldusername, 'newusername'=>$newusername, 'uid'=>$uid, 'password'=>$password, 'email'=>$email)); } function uc_user_merge_remove($username) { return call_user_func(UC_API_FUNC, 'user', 'merge_remove', array('username'=>$username)); } function uc_user_getcredit($appid, $uid, $credit) { return uc_api_post('user', 'getcredit', array('appid'=>$appid, 'uid'=>$uid, 'credit'=>$credit)); } function uc_pm_location($uid, $newpm = 0) { $apiurl = uc_api_url('pm_client', 'ls', "uid=$uid", ($newpm ? '&folder=newbox' : '')); @header("Expires: 0"); @header("Cache-Control: private, post-check=0, pre-check=0, max-age=0", FALSE); @header("Pragma: no-cache"); @header("location: $apiurl"); } function uc_pm_checknew($uid, $more = 0) { $return = call_user_func(UC_API_FUNC, 'pm', 'check_newpm', array('uid'=>$uid, 'more'=>$more)); return (!$more || UC_CONNECT == 'mysql') ? $return : uc_unserialize($return); } function uc_pm_send($fromuid, $msgto, $subject, $message, $instantly = 1, $replypmid = 0, $isusername = 0) { if($instantly) { $replypmid = @is_numeric($replypmid) ? $replypmid : 0; return call_user_func(UC_API_FUNC, 'pm', 'sendpm', array('fromuid'=>$fromuid, 'msgto'=>$msgto, 'subject'=>$subject, 'message'=>$message, 'replypmid'=>$replypmid, 'isusername'=>$isusername)); } else { $fromuid = intval($fromuid); $subject = rawurlencode($subject); $msgto = rawurlencode($msgto); $message = rawurlencode($message); $replypmid = @is_numeric($replypmid) ? $replypmid : 0; $replyadd = $replypmid ? "&pmid=$replypmid&do=reply" : ''; $apiurl = uc_api_url('pm_client', 'send', "uid=$fromuid", "&msgto=$msgto&subject=$subject&message=$message$replyadd"); @header("Expires: 0"); @header("Cache-Control: private, post-check=0, pre-check=0, max-age=0", FALSE); @header("Pragma: no-cache"); @header("location: ".$apiurl); } } function uc_pm_delete($uid, $folder, $pmids) { return call_user_func(UC_API_FUNC, 'pm', 'delete', array('uid'=>$uid, 'folder'=>$folder, 'pmids'=>$pmids)); } function uc_pm_deleteuser($uid, $touids) { return call_user_func(UC_API_FUNC, 'pm', 'deleteuser', array('uid'=>$uid, 'touids'=>$touids)); } function uc_pm_readstatus($uid, $uids, $pmids = array(), $status = 0) { return call_user_func(UC_API_FUNC, 'pm', 'readstatus', array('uid'=>$uid, 'uids'=>$uids, 'pmids'=>$pmids, 'status'=>$status)); } function uc_pm_list($uid, $page = 1, $pagesize = 10, $folder = 'inbox', $filter = 'newpm', $msglen = 0) { $uid = intval($uid); $page = intval($page); $pagesize = intval($pagesize); $return = call_user_func(UC_API_FUNC, 'pm', 'ls', array('uid'=>$uid, 'page'=>$page, 'pagesize'=>$pagesize, 'folder'=>$folder, 'filter'=>$filter, 'msglen'=>$msglen)); return UC_CONNECT == 'mysql' ? $return : uc_unserialize($return); } function uc_pm_ignore($uid) { $uid = intval($uid); return call_user_func(UC_API_FUNC, 'pm', 'ignore', array('uid'=>$uid)); } function uc_pm_view($uid, $pmid, $touid = 0, $daterange = 1) { $uid = intval($uid); $touid = intval($touid); $pmid = @is_numeric($pmid) ? $pmid : 0; $return = call_user_func(UC_API_FUNC, 'pm', 'view', array('uid'=>$uid, 'pmid'=>$pmid, 'touid'=>$touid, 'daterange'=>$daterange)); return UC_CONNECT == 'mysql' ? $return : uc_unserialize($return); } function uc_pm_viewnode($uid, $type = 0, $pmid = 0) { $uid = intval($uid); $pmid = @is_numeric($pmid) ? $pmid : 0; $return = call_user_func(UC_API_FUNC, 'pm', 'viewnode', array('uid'=>$uid, 'pmid'=>$pmid, 'type'=>$type)); return UC_CONNECT == 'mysql' ? $return : uc_unserialize($return); } function uc_pm_blackls_get($uid) { $uid = intval($uid); return call_user_func(UC_API_FUNC, 'pm', 'blackls_get', array('uid'=>$uid)); } function uc_pm_blackls_set($uid, $blackls) { $uid = intval($uid); return call_user_func(UC_API_FUNC, 'pm', 'blackls_set', array('uid'=>$uid, 'blackls'=>$blackls)); } function uc_pm_blackls_add($uid, $username) { $uid = intval($uid); return call_user_func(UC_API_FUNC, 'pm', 'blackls_add', array('uid'=>$uid, 'username'=>$username)); } function uc_pm_blackls_delete($uid, $username) { $uid = intval($uid); return call_user_func(UC_API_FUNC, 'pm', 'blackls_delete', array('uid'=>$uid, 'username'=>$username)); } function uc_domain_ls() { $return = call_user_func(UC_API_FUNC, 'domain', 'ls', array('1'=>1)); return UC_CONNECT == 'mysql' ? $return : uc_unserialize($return); } function uc_credit_exchange_request($uid, $from, $to, $toappid, $amount) { $uid = intval($uid); $from = intval($from); $toappid = intval($toappid); $to = intval($to); $amount = intval($amount); return uc_api_post('credit', 'request', array('uid'=>$uid, 'from'=>$from, 'to'=>$to, 'toappid'=>$toappid, 'amount'=>$amount)); } function uc_tag_get($tagname, $nums = 0) { $return = call_user_func(UC_API_FUNC, 'tag', 'gettag', array('tagname'=>$tagname, 'nums'=>$nums)); return UC_CONNECT == 'mysql' ? $return : uc_unserialize($return); } function uc_avatar($uid, $type = 'virtual', $returnhtml = 1) { $uid = intval($uid); $uc_input = uc_api_input("uid=$uid"); $uc_avatarflash = UC_API.'/images/camera.swf?inajax=1&appid='.UC_APPID.'&input='.$uc_input.'&agent='.md5($_SERVER['HTTP_USER_AGENT']).'&ucapi='.urlencode(str_replace('http://', '', UC_API)).'&avatartype='.$type.'&uploadSize=2048'; if($returnhtml) { return '<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,0,0" width="450" height="253" id="mycamera" align="middle"> <param name="allowScriptAccess" value="always" /> <param name="scale" value="exactfit" /> <param name="wmode" value="transparent" /> <param name="quality" value="high" /> <param name="bgcolor" value="#ffffff" /> <param name="movie" value="'.$uc_avatarflash.'" /> <param name="menu" value="false" /> <embed src="'.$uc_avatarflash.'" quality="high" bgcolor="#ffffff" width="450" height="253" name="mycamera" align="middle" allowScriptAccess="always" allowFullScreen="false" scale="exactfit" wmode="transparent" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" /> </object>'; } else { return array( 'width', '450', 'height', '253', 'scale', 'exactfit', 'src', $uc_avatarflash, 'id', 'mycamera', 'name', 'mycamera', 'quality','high', 'bgcolor','#ffffff', 'wmode','transparent', 'menu', 'false', 'swLiveConnect', 'true', 'allowScriptAccess', 'always' ); } } function uc_mail_queue($uids, $emails, $subject, $message, $frommail = '', $charset = 'gbk', $htmlon = FALSE, $level = 1) { return call_user_func(UC_API_FUNC, 'mail', 'add', array('uids' => $uids, 'emails' => $emails, 'subject' => $subject, 'message' => $message, 'frommail' => $frommail, 'charset' => $charset, 'htmlon' => $htmlon, 'level' => $level)); } function uc_check_avatar($uid, $size = 'middle', $type = 'virtual') { $url = UC_API."/avatar.php?uid=$uid&size=$size&type=$type&check_file_exists=1"; $res = uc_fopen2($url, 500000, '', '', TRUE, UC_IP, 20); if($res == 1) { return 1; } else { return 0; } } function uc_check_version() { $return = uc_api_post('version', 'check', array()); $data = uc_unserialize($return); return is_array($data) ? $data : $return; } ?>
PHP
<?php /* [UCenter] (C)2001-2009 Comsenz Inc. This is NOT a freeware, use is subject to license terms $Id: uccode.class.php 753 2008-11-14 06:48:25Z cnteacher $ */ class uccode { var $uccodes; function uccode() { $this->uccode = array( 'pcodecount' => -1, 'codecount' => 0, 'codehtml' => '' ); } function codedisp($code) { $this->uccode['pcodecount']++; $code = str_replace('\\"', '"', preg_replace("/^[\n\r]*(.+?)[\n\r]*$/is", "\\1", $code)); $this->uccode['codehtml'][$this->uccode['pcodecount']] = $this->tpl_codedisp($code); $this->uccode['codecount']++; return "[\tUCENTER_CODE_".$this->uccode[pcodecount]."\t]"; } function complie($message) { $message = htmlspecialchars($message); if(strpos($message, '[/code]') !== FALSE) { $message = preg_replace("/\s*\[code\](.+?)\[\/code\]\s*/ies", "\$this->codedisp('\\1')", $message); } if(strpos($message, '[/url]') !== FALSE) { $message = preg_replace("/\[url(=((https?|ftp|gopher|news|telnet|rtsp|mms|callto|bctp|ed2k|thunder|synacast){1}:\/\/|www\.)([^\[\"']+?))?\](.+?)\[\/url\]/ies", "\$this->parseurl('\\1', '\\5')", $message); } if(strpos($message, '[/email]') !== FALSE) { $message = preg_replace("/\[email(=([a-z0-9\-_.+]+)@([a-z0-9\-_]+[.][a-z0-9\-_.]+))?\](.+?)\[\/email\]/ies", "\$this->parseemail('\\1', '\\4')", $message); } $message = str_replace(array( '[/color]', '[/size]', '[/font]', '[/align]', '[b]', '[/b]', '[i]', '[/i]', '[u]', '[/u]', '[list]', '[list=1]', '[list=a]', '[list=A]', '[*]', '[/list]', '[indent]', '[/indent]', '[/float]' ), array( '</font>', '</font>', '</font>', '</p>', '<strong>', '</strong>', '<i>', '</i>', '<u>', '</u>', '<ul>', '<ul type="1">', '<ul type="a">', '<ul type="A">', '<li>', '</ul>', '<blockquote>', '</blockquote>', '</span>' ), preg_replace(array( "/\[color=([#\w]+?)\]/i", "/\[size=(\d+?)\]/i", "/\[size=(\d+(\.\d+)?(px|pt|in|cm|mm|pc|em|ex|%)+?)\]/i", "/\[font=([^\[\<]+?)\]/i", "/\[align=(left|center|right)\]/i", "/\[float=(left|right)\]/i" ), array( "<font color=\"\\1\">", "<font size=\"\\1\">", "<font style=\"font-size: \\1\">", "<font face=\"\\1 \">", "<p align=\"\\1\">", "<span style=\"float: \\1;\">" ), $message)); if(strpos($message, '[/quote]') !== FALSE) { $message = preg_replace("/\s*\[quote\][\n\r]*(.+?)[\n\r]*\[\/quote\]\s*/is", $this->tpl_quote(), $message); } if(strpos($message, '[/img]') !== FALSE) { $message = preg_replace(array( "/\[img\]\s*([^\[\<\r\n]+?)\s*\[\/img\]/ies", "/\[img=(\d{1,4})[x|\,](\d{1,4})\]\s*([^\[\<\r\n]+?)\s*\[\/img\]/ies" ), array( "\$this->bbcodeurl('\\1', '<img src=\"%s\" border=\"0\" alt=\"\" />')", "\$this->bbcodeurl('\\3', '<img width=\"\\1\" height=\"\\2\" src=\"%s\" border=\"0\" alt=\"\" />')" ), $message); } for($i = 0; $i <= $this->uccode['pcodecount']; $i++) { $message = str_replace("[\tUCENTER_CODE_$i\t]", $this->uccode['codehtml'][$i], $message); } return nl2br(str_replace(array("\t", ' ', ' '), array('&nbsp; &nbsp; &nbsp; &nbsp; ', '&nbsp; &nbsp;', '&nbsp;&nbsp;'), $message)); } function parseurl($url, $text) { if(!$url && preg_match("/((https?|ftp|gopher|news|telnet|rtsp|mms|callto|bctp|ed2k|thunder|synacast){1}:\/\/|www\.)[^\[\"']+/i", trim($text), $matches)) { $url = $matches[0]; $length = 65; if(strlen($url) > $length) { $text = substr($url, 0, intval($length * 0.5)).' ... '.substr($url, - intval($length * 0.3)); } return '<a href="'.(substr(strtolower($url), 0, 4) == 'www.' ? 'http://'.$url : $url).'" target="_blank">'.$text.'</a>'; } else { $url = substr($url, 1); if(substr(strtolower($url), 0, 4) == 'www.') { $url = 'http://'.$url; } return '<a href="'.$url.'" target="_blank">'.$text.'</a>'; } } function parseemail($email, $text) { if(!$email && preg_match("/\s*([a-z0-9\-_.+]+)@([a-z0-9\-_]+[.][a-z0-9\-_.]+)\s*/i", $text, $matches)) { $email = trim($matches[0]); return '<a href="mailto:'.$email.'">'.$email.'</a>'; } else { return '<a href="mailto:'.substr($email, 1).'">'.$text.'</a>'; } } function bbcodeurl($url, $tags) { if(!preg_match("/<.+?>/s", $url)) { if(!in_array(strtolower(substr($url, 0, 6)), array('http:/', 'https:', 'ftp://', 'rtsp:/', 'mms://'))) { $url = 'http://'.$url; } return str_replace(array('submit', 'logging.php'), array('', ''), sprintf($tags, $url, addslashes($url))); } else { return '&nbsp;'.$url; } } function tpl_codedisp($code) { return '<div class="blockcode"><code id="code'.$this->uccodes['codecount'].'">'.$code.'</code></div>'; } function tpl_quote() { return '<div class="quote"><blockquote>\\1</blockquote></div>'; } } /* Usage: $str = <<<EOF 1 2 3 EOF; require_once 'lib/uccode.class.php'; $this->uccode = new uccode(); echo $this->uccode->complie($str); */ ?>
PHP
<?php /* [UCenter] (C)2001-2009 Comsenz Inc. This is NOT a freeware, use is subject to license terms $Id: db.class.php 922 2009-02-19 01:30:22Z zhaoxiongfei $ */ class ucclient_db { var $querynum = 0; var $link; var $histories; var $dbhost; var $dbuser; var $dbpw; var $dbcharset; var $pconnect; var $tablepre; var $time; var $goneaway = 5; function connect($dbhost, $dbuser, $dbpw, $dbname = '', $dbcharset = '', $pconnect = 0, $tablepre='', $time = 0) { $this->dbhost = $dbhost; $this->dbuser = $dbuser; $this->dbpw = $dbpw; $this->dbname = $dbname; $this->dbcharset = $dbcharset; $this->pconnect = $pconnect; $this->tablepre = $tablepre; $this->time = $time; if($pconnect) { if(!$this->link = mysql_pconnect($dbhost, $dbuser, $dbpw)) { $this->halt('Can not connect to MySQL server'); } } else { if(!$this->link = mysql_connect($dbhost, $dbuser, $dbpw)) { $this->halt('Can not connect to MySQL server'); } } if($this->version() > '4.1') { if($dbcharset) { mysql_query("SET character_set_connection=".$dbcharset.", character_set_results=".$dbcharset.", character_set_client=binary", $this->link); } if($this->version() > '5.0.1') { mysql_query("SET sql_mode=''", $this->link); } } if($dbname) { mysql_select_db($dbname, $this->link); } } function fetch_array($query, $result_type = MYSQL_ASSOC) { return mysql_fetch_array($query, $result_type); } function result_first($sql) { $query = $this->query($sql); return $this->result($query, 0); } function fetch_first($sql) { $query = $this->query($sql); return $this->fetch_array($query); } function fetch_all($sql, $id = '') { $arr = array(); $query = $this->query($sql); while($data = $this->fetch_array($query)) { $id ? $arr[$data[$id]] = $data : $arr[] = $data; } return $arr; } function cache_gc() { $this->query("DELETE FROM {$this->tablepre}sqlcaches WHERE expiry<$this->time"); } function query($sql, $type = '', $cachetime = FALSE) { $func = $type == 'UNBUFFERED' && @function_exists('mysql_unbuffered_query') ? 'mysql_unbuffered_query' : 'mysql_query'; if(!($query = $func($sql, $this->link)) && $type != 'SILENT') { $this->halt('MySQL Query Error', $sql); } $this->querynum++; $this->histories[] = $sql; return $query; } function affected_rows() { return mysql_affected_rows($this->link); } function error() { return (($this->link) ? mysql_error($this->link) : mysql_error()); } function errno() { return intval(($this->link) ? mysql_errno($this->link) : mysql_errno()); } function result($query, $row) { $query = @mysql_result($query, $row); return $query; } function num_rows($query) { $query = mysql_num_rows($query); return $query; } function num_fields($query) { return mysql_num_fields($query); } function free_result($query) { return mysql_free_result($query); } function insert_id() { return ($id = mysql_insert_id($this->link)) >= 0 ? $id : $this->result($this->query("SELECT last_insert_id()"), 0); } function fetch_row($query) { $query = mysql_fetch_row($query); return $query; } function fetch_fields($query) { return mysql_fetch_field($query); } function version() { return mysql_get_server_info($this->link); } function close() { return mysql_close($this->link); } function halt($message = '', $sql = '') { $error = mysql_error(); $errorno = mysql_errno(); if($errorno == 2006 && $this->goneaway-- > 0) { $this->connect($this->dbhost, $this->dbuser, $this->dbpw, $this->dbname, $this->dbcharset, $this->pconnect, $this->tablepre, $this->time); $this->query($sql); } else { $s = ''; if($message) { $s = "<b>UCenter info:</b> $message<br />"; } if($sql) { $s .= '<b>SQL:</b>'.htmlspecialchars($sql).'<br />'; } $s .= '<b>Error:</b>'.$error.'<br />'; $s .= '<b>Errno:</b>'.$errorno.'<br />'; $s = str_replace(UC_DBTABLEPRE, '[Table]', $s); exit($s); } } } ?>
PHP
<?php /* [UCenter] (C)2001-2009 Comsenz Inc. This is NOT a freeware, use is subject to license terms $Id: sendmail.inc.php 753 2008-11-14 06:48:25Z cnteacher $ */ !defined('IN_UC') && exit('Access Denied'); if($mail_setting['mailsilent']) { error_reporting(0); } $maildelimiter = $mail_setting['maildelimiter'] == 1 ? "\r\n" : ($mail_setting['maildelimiter'] == 2 ? "\r" : "\n"); $mailusername = isset($mail_setting['mailusername']) ? $mail_setting['mailusername'] : 1; $appname = $this->base->cache['apps'][$mail['appid']]['name']; $mail['subject'] = '=?'.$mail['charset'].'?B?'.base64_encode(str_replace("\r", '', str_replace("\n", '', '['.$appname.'] '.$mail['subject']))).'?='; $mail['message'] = chunk_split(base64_encode(str_replace("\r\n.", " \r\n..", str_replace("\n", "\r\n", str_replace("\r", "\n", str_replace("\r\n", "\n", str_replace("\n\r", "\r", $mail['message']))))))); $email_from = $mail['frommail'] == '' ? '=?'.$mail['charset'].'?B?'.base64_encode($appname)."?= <$mail_setting[maildefault]>" : (preg_match('/^(.+?) \<(.+?)\>$/',$email_from, $from) ? '=?'.$mail['charset'].'?B?'.base64_encode($from[1])."?= <$from[2]>" : $mail['frommail']); foreach(explode(',', $mail['email_to']) as $touser) { $tousers[] = preg_match('/^(.+?) \<(.+?)\>$/',$touser, $to) ? ($mailusername ? '=?'.$mail['charset'].'?B?'.base64_encode($to[1])."?= <$to[2]>" : $to[2]) : $touser; } $mail['email_to'] = implode(',', $tousers); $headers = "From: $email_from{$maildelimiter}X-Priority: 3{$maildelimiter}X-Mailer: Discuz! $version{$maildelimiter}MIME-Version: 1.0{$maildelimiter}Content-type: text/".($mail['htmlon'] ? 'html' : 'plain')."; charset=$mail[charset]{$maildelimiter}Content-Transfer-Encoding: base64{$maildelimiter}"; $mail_setting['mailport'] = $mail_setting['mailport'] ? $mail_setting['mailport'] : 25; if($mail_setting['mailsend'] == 1 && function_exists('mail')) { return @mail($mail['email_to'], $mail['subject'], $mail['message'], $headers); } elseif($mail_setting['mailsend'] == 2) { if(!$fp = fsockopen($mail_setting['mailserver'], $mail_setting['mailport'], $errno, $errstr, 30)) { return false; } stream_set_blocking($fp, true); $lastmessage = fgets($fp, 512); if(substr($lastmessage, 0, 3) != '220') { return false; } fputs($fp, ($mail_setting['mailauth'] ? 'EHLO' : 'HELO')." discuz\r\n"); $lastmessage = fgets($fp, 512); if(substr($lastmessage, 0, 3) != 220 && substr($lastmessage, 0, 3) != 250) { return false; } while(1) { if(substr($lastmessage, 3, 1) != '-' || empty($lastmessage)) { break; } $lastmessage = fgets($fp, 512); } if($mail_setting['mailauth']) { fputs($fp, "AUTH LOGIN\r\n"); $lastmessage = fgets($fp, 512); if(substr($lastmessage, 0, 3) != 334) { return false; } fputs($fp, base64_encode($mail_setting['mailauth_username'])."\r\n"); $lastmessage = fgets($fp, 512); if(substr($lastmessage, 0, 3) != 334) { return false; } fputs($fp, base64_encode($mail_setting['mailauth_password'])."\r\n"); $lastmessage = fgets($fp, 512); if(substr($lastmessage, 0, 3) != 235) { return false; } $email_from = $mail_setting['mailfrom']; } fputs($fp, "MAIL FROM: <".preg_replace("/.*\<(.+?)\>.*/", "\\1", $email_from).">\r\n"); $lastmessage = fgets($fp, 512); if(substr($lastmessage, 0, 3) != 250) { fputs($fp, "MAIL FROM: <".preg_replace("/.*\<(.+?)\>.*/", "\\1", $email_from).">\r\n"); $lastmessage = fgets($fp, 512); if(substr($lastmessage, 0, 3) != 250) { return false; } } $email_tos = array(); foreach(explode(',', $mail['email_to']) as $touser) { $touser = trim($touser); if($touser) { fputs($fp, "RCPT TO: <".preg_replace("/.*\<(.+?)\>.*/", "\\1", $touser).">\r\n"); $lastmessage = fgets($fp, 512); if(substr($lastmessage, 0, 3) != 250) { fputs($fp, "RCPT TO: <".preg_replace("/.*\<(.+?)\>.*/", "\\1", $touser).">\r\n"); $lastmessage = fgets($fp, 512); return false; } } } fputs($fp, "DATA\r\n"); $lastmessage = fgets($fp, 512); if(substr($lastmessage, 0, 3) != 354) { return false; } $headers .= 'Message-ID: <'.gmdate('YmdHs').'.'.substr(md5($mail['message'].microtime()), 0, 6).rand(100000, 999999).'@'.$_SERVER['HTTP_HOST'].">{$maildelimiter}"; fputs($fp, "Date: ".gmdate('r')."\r\n"); fputs($fp, "To: ".$mail['email_to']."\r\n"); fputs($fp, "Subject: ".$mail['subject']."\r\n"); fputs($fp, $headers."\r\n"); fputs($fp, "\r\n\r\n"); fputs($fp, "$mail[message]\r\n.\r\n"); $lastmessage = fgets($fp, 512); if(substr($lastmessage, 0, 3) != 250) { return false; } fputs($fp, "QUIT\r\n"); return true; } elseif($mail_setting['mailsend'] == 3) { ini_set('SMTP', $mail_setting['mailserver']); ini_set('smtp_port', $mail_setting['mailport']); ini_set('sendmail_from', $email_from); return @mail($mail['email_to'], $mail['subject'], $mail['message'], $headers); } ?>
PHP
<?php /* [UCenter] (C)2001-2009 Comsenz Inc. This is NOT a freeware, use is subject to license terms $Id: xml.class.php 972 2009-11-16 02:20:39Z zhaoxiongfei $ */ function xml_unserialize(&$xml, $isnormal = FALSE) { $xml_parser = new XML($isnormal); $data = $xml_parser->parse($xml); $xml_parser->destruct(); return $data; } function xml_serialize($arr, $htmlon = FALSE, $isnormal = FALSE, $level = 1) { $s = $level == 1 ? "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\r\n<root>\r\n" : ''; $space = str_repeat("\t", $level); foreach($arr as $k => $v) { if(!is_array($v)) { $s .= $space."<item id=\"$k\">".($htmlon ? '<![CDATA[' : '').$v.($htmlon ? ']]>' : '')."</item>\r\n"; } else { $s .= $space."<item id=\"$k\">\r\n".xml_serialize($v, $htmlon, $isnormal, $level + 1).$space."</item>\r\n"; } } $s = preg_replace("/([\x01-\x08\x0b-\x0c\x0e-\x1f])+/", ' ', $s); return $level == 1 ? $s."</root>" : $s; } class XML { var $parser; var $document; var $stack; var $data; var $last_opened_tag; var $isnormal; var $attrs = array(); var $failed = FALSE; function __construct($isnormal) { $this->XML($isnormal); } function XML($isnormal) { $this->isnormal = $isnormal; $this->parser = xml_parser_create('ISO-8859-1'); xml_parser_set_option($this->parser, XML_OPTION_CASE_FOLDING, false); xml_set_object($this->parser, $this); xml_set_element_handler($this->parser, 'open','close'); xml_set_character_data_handler($this->parser, 'data'); } function destruct() { xml_parser_free($this->parser); } function parse(&$data) { $this->document = array(); $this->stack = array(); return xml_parse($this->parser, $data, true) && !$this->failed ? $this->document : ''; } function open(&$parser, $tag, $attributes) { $this->data = ''; $this->failed = FALSE; if(!$this->isnormal) { if(isset($attributes['id']) && !is_string($this->document[$attributes['id']])) { $this->document = &$this->document[$attributes['id']]; } else { $this->failed = TRUE; } } else { if(!isset($this->document[$tag]) || !is_string($this->document[$tag])) { $this->document = &$this->document[$tag]; } else { $this->failed = TRUE; } } $this->stack[] = &$this->document; $this->last_opened_tag = $tag; $this->attrs = $attributes; } function data(&$parser, $data) { if($this->last_opened_tag != NULL) { $this->data .= $data; } } function close(&$parser, $tag) { if($this->last_opened_tag == $tag) { $this->document = $this->data; $this->last_opened_tag = NULL; } array_pop($this->stack); if($this->stack) { $this->document = &$this->stack[count($this->stack)-1]; } } } ?>
PHP
<?php /* [UCenter] (C)2001-2009 Comsenz Inc. This is NOT a freeware, use is subject to license terms $Id: mail.php 848 2008-12-08 05:43:39Z zhaoxiongfei $ */ !defined('IN_UC') && exit('Access Denied'); define('UC_MAIL_REPEAT', 5); class mailmodel { var $db; var $base; var $apps; function __construct(&$base) { $this->mailmodel($base); } function mailmodel(&$base) { $this->base = $base; $this->db = $base->db; $this->apps = &$this->base->cache['apps']; } function get_total_num() { $data = $this->db->result_first("SELECT COUNT(*) FROM ".UC_DBTABLEPRE."mailqueue"); return $data; } function get_list($page, $ppp, $totalnum) { $start = $this->base->page_get_start($page, $ppp, $totalnum); $data = $this->db->fetch_all("SELECT m.*, u.username, u.email FROM ".UC_DBTABLEPRE."mailqueue m LEFT JOIN ".UC_DBTABLEPRE."members u ON m.touid=u.uid ORDER BY dateline DESC LIMIT $start, $ppp"); foreach((array)$data as $k => $v) { $data[$k]['subject'] = htmlspecialchars($v['subject']); $data[$k]['tomail'] = empty($v['tomail']) ? $v['email'] : $v['tomail']; $data[$k]['dateline'] = $v['dateline'] ? $this->base->date($data[$k]['dateline']) : ''; $data[$k]['appname'] = $this->base->cache['apps'][$v['appid']]['name']; } return $data; } function delete_mail($ids) { $ids = $this->base->implode($ids); $this->db->query("DELETE FROM ".UC_DBTABLEPRE."mailqueue WHERE mailid IN ($ids)"); return $this->db->affected_rows(); } function add($mail) { if($mail['level']) { $sql = "INSERT INTO ".UC_DBTABLEPRE."mailqueue (touid, tomail, subject, message, frommail, charset, htmlon, level, dateline, failures, appid) VALUES "; $values_arr = array(); foreach($mail['uids'] as $uid) { if(empty($uid)) continue; $values_arr[] = "('$uid', '', '$mail[subject]', '$mail[message]', '$mail[frommail]', '$mail[charset]', '$mail[htmlon]', '$mail[level]', '$mail[dateline]', '0', '$mail[appid]')"; } foreach($mail['emails'] as $email) { if(empty($email)) continue; $values_arr[] = "('', '$email', '$mail[subject]', '$mail[message]', '$mail[frommail]', '$mail[charset]', '$mail[htmlon]', '$mail[level]', '$mail[dateline]', '0', '$mail[appid]')"; } $sql .= implode(',', $values_arr); $this->db->query($sql); $insert_id = $this->db->insert_id(); $insert_id && $this->db->query("REPLACE INTO ".UC_DBTABLEPRE."vars SET name='mailexists', value='1'"); return $insert_id; } else { $mail['email_to'] = array(); $uids = 0; foreach($mail['uids'] as $uid) { if(empty($uid)) continue; $uids .= ','.$uid; } $users = $this->db->fetch_all("SELECT uid, username, email FROM ".UC_DBTABLEPRE."members WHERE uid IN ($uids)"); foreach($users as $v) { $mail['email_to'][] = $v['username'].'<'.$v['email'].'>'; } foreach($mail['emails'] as $email) { if(empty($email)) continue; $mail['email_to'][] = $email; } $mail['message'] = str_replace('\"', '"', $mail['message']); $mail['email_to'] = implode(',', $mail['email_to']); return $this->send_one_mail($mail); } } function send() { register_shutdown_function(array($this, '_send')); } function _send() { $mail = $this->_get_mail(); if(empty($mail)) { $this->db->query("REPLACE INTO ".UC_DBTABLEPRE."vars SET name='mailexists', value='0'"); return NULL; } else { $mail['email_to'] = $mail['tomail'] ? $mail['tomail'] : $mail['username'].'<'.$mail['email'].'>'; if($this->send_one_mail($mail)) { $this->_delete_one_mail($mail['mailid']); return true; } else { $this->_update_failures($mail['mailid']); return false; } } } function send_by_id($mailid) { if ($this->send_one_mail($this->_get_mail_by_id($mailid))) { $this->_delete_one_mail($mailid); return true; } } function send_one_mail($mail) { if(empty($mail)) return; $mail['email_to'] = $mail['email_to'] ? $mail['email_to'] : $mail['username'].'<'.$mail['email'].'>'; $mail_setting = $this->base->settings; return include UC_ROOT.'lib/sendmail.inc.php'; } function _get_mail() { $data = $this->db->fetch_first("SELECT m.*, u.username, u.email FROM ".UC_DBTABLEPRE."mailqueue m LEFT JOIN ".UC_DBTABLEPRE."members u ON m.touid=u.uid WHERE failures<'".UC_MAIL_REPEAT."' ORDER BY level DESC, mailid ASC LIMIT 1"); return $data; } function _get_mail_by_id($mailid) { $data = $this->db->fetch_first("SELECT m.*, u.username, u.email FROM ".UC_DBTABLEPRE."mailqueue m LEFT JOIN ".UC_DBTABLEPRE."members u ON m.touid=u.uid WHERE mailid='$mailid'"); return $data; } function _delete_one_mail($mailid) { $mailid = intval($mailid); return $this->db->query("DELETE FROM ".UC_DBTABLEPRE."mailqueue WHERE mailid='$mailid'"); } function _update_failures($mailid) { $mailid = intval($mailid); return $this->db->query("UPDATE ".UC_DBTABLEPRE."mailqueue SET failures=failures+1 WHERE mailid='$mailid'"); } } ?>
PHP
<?php /* [UCenter] (C)2001-2009 Comsenz Inc. This is NOT a freeware, use is subject to license terms $Id: base.php 837 2008-12-05 03:14:47Z zhaoxiongfei $ */ !defined('IN_UC') && exit('Access Denied'); if(!function_exists('getgpc')) { function getgpc($k, $var='G') { switch($var) { case 'G': $var = &$_GET; break; case 'P': $var = &$_POST; break; case 'C': $var = &$_COOKIE; break; case 'R': $var = &$_REQUEST; break; } return isset($var[$k]) ? $var[$k] : NULL; } } class base { var $time; var $onlineip; var $db; var $key; var $settings = array(); var $cache = array(); var $app = array(); var $user = array(); var $input = array(); function __construct() { $this->base(); } function base() { $this->init_var(); $this->init_db(); $this->init_cache(); $this->init_note(); $this->init_mail(); } function init_var() { $this->time = time(); $cip = getenv('HTTP_CLIENT_IP'); $xip = getenv('HTTP_X_FORWARDED_FOR'); $rip = getenv('REMOTE_ADDR'); $srip = $_SERVER['REMOTE_ADDR']; if($cip && strcasecmp($cip, 'unknown')) { $this->onlineip = $cip; } elseif($xip && strcasecmp($xip, 'unknown')) { $this->onlineip = $xip; } elseif($rip && strcasecmp($rip, 'unknown')) { $this->onlineip = $rip; } elseif($srip && strcasecmp($srip, 'unknown')) { $this->onlineip = $srip; } preg_match("/[\d\.]{7,15}/", $this->onlineip, $match); $this->onlineip = $match[0] ? $match[0] : 'unknown'; $this->app['appid'] = UC_APPID; } function init_input() { } function init_db() { require_once UC_ROOT.'lib/db.class.php'; $this->db = new ucclient_db(); $this->db->connect(UC_DBHOST, UC_DBUSER, UC_DBPW, UC_DBNAME, UC_DBCHARSET, UC_DBCONNECT, UC_DBTABLEPRE); } function load($model, $base = NULL) { $base = $base ? $base : $this; if(empty($_ENV[$model])) { require_once UC_ROOT."./model/$model.php"; eval('$_ENV[$model] = new '.$model.'model($base);'); } return $_ENV[$model]; } function date($time, $type = 3) { if(!$this->settings) { $this->settings = $this->cache('settings'); } $format[] = $type & 2 ? (!empty($this->settings['dateformat']) ? $this->settings['dateformat'] : 'Y-n-j') : ''; $format[] = $type & 1 ? (!empty($this->settings['timeformat']) ? $this->settings['timeformat'] : 'H:i') : ''; return gmdate(implode(' ', $format), $time + $this->settings['timeoffset']); } function page_get_start($page, $ppp, $totalnum) { $totalpage = ceil($totalnum / $ppp); $page = max(1, min($totalpage,intval($page))); return ($page - 1) * $ppp; } function implode($arr) { return "'".implode("','", (array)$arr)."'"; } function &cache($cachefile) { static $_CACHE = array(); if(!isset($_CACHE[$cachefile])) { $cachepath = UC_DATADIR.'./cache/'.$cachefile.'.php'; if(!file_exists($cachepath)) { $this->load('cache'); $_ENV['cache']->updatedata($cachefile); } else { include_once $cachepath; } } return $_CACHE[$cachefile]; } function get_setting($k = array(), $decode = FALSE) { $return = array(); $sqladd = $k ? "WHERE k IN (".$this->implode($k).")" : ''; $settings = $this->db->fetch_all("SELECT * FROM ".UC_DBTABLEPRE."settings $sqladd"); if(is_array($settings)) { foreach($settings as $arr) { $return[$arr['k']] = $decode ? unserialize($arr['v']) : $arr['v']; } } return $return; } function init_cache() { $this->settings = $this->cache('settings'); $this->cache['apps'] = $this->cache('apps'); if(PHP_VERSION > '5.1') { $timeoffset = intval($this->settings['timeoffset'] / 3600); @date_default_timezone_set('Etc/GMT'.($timeoffset > 0 ? '-' : '+').(abs($timeoffset))); } } function cutstr($string, $length, $dot = ' ...') { if(strlen($string) <= $length) { return $string; } $string = str_replace(array('&amp;', '&quot;', '&lt;', '&gt;'), array('&', '"', '<', '>'), $string); $strcut = ''; if(strtolower(UC_CHARSET) == 'utf-8') { $n = $tn = $noc = 0; while($n < strlen($string)) { $t = ord($string[$n]); if($t == 9 || $t == 10 || (32 <= $t && $t <= 126)) { $tn = 1; $n++; $noc++; } elseif(194 <= $t && $t <= 223) { $tn = 2; $n += 2; $noc += 2; } elseif(224 <= $t && $t < 239) { $tn = 3; $n += 3; $noc += 2; } elseif(240 <= $t && $t <= 247) { $tn = 4; $n += 4; $noc += 2; } elseif(248 <= $t && $t <= 251) { $tn = 5; $n += 5; $noc += 2; } elseif($t == 252 || $t == 253) { $tn = 6; $n += 6; $noc += 2; } else { $n++; } if($noc >= $length) { break; } } if($noc > $length) { $n -= $tn; } $strcut = substr($string, 0, $n); } else { for($i = 0; $i < $length; $i++) { $strcut .= ord($string[$i]) > 127 ? $string[$i].$string[++$i] : $string[$i]; } } $strcut = str_replace(array('&', '"', '<', '>'), array('&amp;', '&quot;', '&lt;', '&gt;'), $strcut); return $strcut.$dot; } function init_note() { if($this->note_exists()) { $this->load('note'); $_ENV['note']->send(); } } function note_exists() { $noteexists = $this->db->fetch_first("SELECT value FROM ".UC_DBTABLEPRE."vars WHERE name='noteexists".UC_APPID."'"); if(empty($noteexists)) { return FALSE; } else { return TRUE; } } function init_mail() { if($this->mail_exists() && !getgpc('inajax')) { $this->load('mail'); $_ENV['mail']->send(); } } function authcode($string, $operation = 'DECODE', $key = '', $expiry = 0) { return uc_authcode($string, $operation, $key, $expiry); } /* function serialize() { } */ function unserialize($s) { return uc_unserialize($s); } function input($k) { return isset($this->input[$k]) ? (is_array($this->input[$k]) ? $this->input[$k] : trim($this->input[$k])) : NULL; } function mail_exists() { $mailexists = $this->db->fetch_first("SELECT value FROM ".UC_DBTABLEPRE."vars WHERE name='mailexists'"); if(empty($mailexists)) { return FALSE; } else { return TRUE; } } function dstripslashes($string) { if(is_array($string)) { foreach($string as $key => $val) { $string[$key] = $this->dstripslashes($val); } } else { $string = stripslashes($string); } return $string; } } ?>
PHP
<?php /* [UCenter] (C)2001-2009 Comsenz Inc. This is NOT a freeware, use is subject to license terms $Id: pm.php 908 2008-12-26 07:27:51Z monkey $ */ !defined('IN_UC') && exit('Access Denied'); class pmmodel { var $db; var $base; function __construct(&$base) { $this->pmmodel($base); } function pmmodel(&$base) { $this->base = $base; $this->db = $base->db; } function pmintval($pmid) { return @is_numeric($pmid) ? $pmid : 0; } function get_pm_by_pmid($uid, $pmid) { $arr = $this->db->fetch_all("SELECT * FROM ".UC_DBTABLEPRE."pms WHERE pmid='$pmid' AND (msgtoid IN ('$uid','0') OR msgfromid='$uid')"); return $arr; } function get_pm_by_touid($uid, $touid, $starttime, $endtime) { $arr1 = $this->db->fetch_all("SELECT * FROM ".UC_DBTABLEPRE."pms WHERE msgfromid='$uid' AND msgtoid='$touid' AND dateline>='$starttime' AND dateline<'$endtime' AND related>'0' AND delstatus IN (0,2) ORDER BY dateline"); $arr2 = $this->db->fetch_all("SELECT * FROM ".UC_DBTABLEPRE."pms WHERE msgfromid='$touid' AND msgtoid='$uid' AND dateline>='$starttime' AND dateline<'$endtime' AND related>'0' AND delstatus IN (0,1) ORDER BY dateline"); $arr = array_merge($arr1, $arr2); uasort($arr, 'pm_datelinesort'); return $arr; } function get_pmnode_by_pmid($uid, $pmid, $type = 0) { $arr = array(); if($type == 1) { $arr = $this->db->fetch_first("SELECT * FROM ".UC_DBTABLEPRE."pms WHERE msgfromid='$uid' and folder='inbox' ORDER BY dateline DESC LIMIT 1"); } elseif($type == 2) { $arr = $this->db->fetch_first("SELECT * FROM ".UC_DBTABLEPRE."pms WHERE msgtoid='$uid' and folder='inbox' ORDER BY dateline DESC LIMIT 1"); } else { $arr = $this->db->fetch_first("SELECT * FROM ".UC_DBTABLEPRE."pms WHERE pmid='$pmid'"); } return $arr; } function set_pm_status($uid, $touid, $pmid = 0, $status = 0) { if(!$status) { $oldstatus = 1; $newstatus = 0; } else { $oldstatus = 0; $newstatus = 1; } if($touid) { $ids = is_array($touid) ? $this->base->implode($touid) : $touid; $this->db->query("UPDATE ".UC_DBTABLEPRE."pms SET new='$newstatus' WHERE msgfromid IN ($ids) AND msgtoid='$uid' AND new='$oldstatus'", 'UNBUFFERED'); } if($pmid) { $ids = is_array($pmid) ? $this->base->implode($pmid) : $pmid; $this->db->query("UPDATE ".UC_DBTABLEPRE."pms SET new='$newstatus' WHERE pmid IN ($ids) AND msgtoid='$uid' AND new='$oldstatus'", 'UNBUFFERED'); } } function get_pm_num() { } function get_num($uid, $folder, $filter = '') { switch($folder) { case 'newbox': $sql = "SELECT count(*) FROM ".UC_DBTABLEPRE."pms WHERE msgtoid='$uid' AND (related='0' AND msgfromid>'0' OR msgfromid='0') AND folder='inbox' AND new='1'"; $num = $this->db->result_first($sql); return $num; case 'outbox': case 'inbox': if($filter == 'newpm') { $filteradd = "msgtoid='$uid' AND (related='0' AND msgfromid>'0' OR msgfromid='0') AND folder='inbox' AND new='1'"; } elseif($filter == 'systempm') { $filteradd = "msgtoid='$uid' AND msgfromid='0' AND folder='inbox'"; } elseif($filter == 'privatepm') { $filteradd = "msgtoid='$uid' AND related='0' AND msgfromid>'0' AND folder='inbox'"; } elseif($filter == 'announcepm') { $filteradd = "msgtoid='0' AND folder='inbox'"; } else { $filteradd = "msgtoid='$uid' AND related='0' AND folder='inbox'"; } $sql = "SELECT count(*) FROM ".UC_DBTABLEPRE."pms WHERE $filteradd"; break; case 'savebox': break; } $num = $this->db->result_first($sql); return $num; } function get_pm_list($uid, $pmnum, $folder, $filter, $start, $ppp = 10) { $ppp = $ppp ? $ppp : 10; switch($folder) { case 'newbox': $folder = 'inbox'; $filter = 'newpm'; case 'outbox': case 'inbox': if($filter == 'newpm') { $filteradd = "pm.msgtoid='$uid' AND (pm.related='0' AND pm.msgfromid>'0' OR pm.msgfromid='0') AND pm.folder='inbox' AND pm.new='1'"; } elseif($filter == 'systempm') { $filteradd = "pm.msgtoid='$uid' AND pm.msgfromid='0' AND pm.folder='inbox'"; } elseif($filter == 'privatepm') { $filteradd = "pm.msgtoid='$uid' AND pm.related='0' AND pm.msgfromid>'0' AND pm.folder='inbox'"; } elseif($filter == 'announcepm') { $filteradd = "pm.msgtoid='0' AND pm.folder='inbox'"; } else { $filteradd = "pm.msgtoid='$uid' AND pm.related='0' AND pm.folder='inbox'"; } $sql = "SELECT pm.*,m.username as msgfrom FROM ".UC_DBTABLEPRE."pms pm LEFT JOIN ".UC_DBTABLEPRE."members m ON pm.msgfromid = m.uid WHERE $filteradd ORDER BY pm.dateline DESC LIMIT $start, $ppp"; break; case 'searchbox': $filteradd = "msgtoid='$uid' AND folder='inbox' AND message LIKE '%".(str_replace('_', '\_', addcslashes($filter, '%_')))."%'"; $sql = "SELECT * FROM ".UC_DBTABLEPRE."pms WHERE $filteradd ORDER BY dateline DESC LIMIT $start, $ppp"; break; case 'savebox': break; } $query = $this->db->query($sql); $array = array(); $today = $this->base->time - $this->base->time % 86400; while($data = $this->db->fetch_array($query)) { $daterange = 5; if($data['dateline'] >= $today) { $daterange = 1; } elseif($data['dateline'] >= $today - 86400) { $daterange = 2; } elseif($data['dateline'] >= $today - 172800) { $daterange = 3; } elseif($data['dateline'] >= $today - 604800) { $daterange = 4; } $data['daterange'] = $daterange; $data['subject'] = htmlspecialchars($data['subject']); if($filter == 'announcepm') { unset($data['msgfromid'], $data['msgfrom']); } $data['touid'] = $uid == $data['msgfromid'] ? $data['msgtoid'] : $data['msgfromid']; $array[] = $data; } if($folder == 'inbox') { $this->db->query("DELETE FROM ".UC_DBTABLEPRE."newpm WHERE uid='$uid'", 'UNBUFFERED'); } return $array; } function sendpm($subject, $message, $msgfrom, $msgto, $related = 0) { if($msgfrom['uid'] && $msgfrom['uid'] == $msgto) { return 0; } $_CACHE['badwords'] = $this->base->cache('badwords'); if($_CACHE['badwords']['findpattern']) { $subject = @preg_replace($_CACHE['badwords']['findpattern'], $_CACHE['badwords']['replace'], $subject); $message = @preg_replace($_CACHE['badwords']['findpattern'], $_CACHE['badwords']['replace'], $message); } $box = 'inbox'; $subject = trim($subject); if($subject == '' && !$related) { $subject = $this->removecode(trim($message), 75); } else { $subject = $this->base->cutstr(trim($subject), 75, ' '); } if($msgfrom['uid']) { $sessionexist = $this->db->result_first("SELECT count(*) FROM ".UC_DBTABLEPRE."pms WHERE msgfromid='$msgfrom[uid]' AND msgtoid='$msgto' AND folder='inbox' AND related='0'"); if(!$sessionexist || $sessionexist > 1) { if($sessionexist > 1) { $this->db->query("DELETE FROM ".UC_DBTABLEPRE."pms WHERE msgfromid='$msgfrom[uid]' AND msgtoid='$msgto' AND folder='inbox' AND related='0'"); } $this->db->query("INSERT INTO ".UC_DBTABLEPRE."pms (msgfrom,msgfromid,msgtoid,folder,new,subject,dateline,related,message,fromappid) VALUES ('".$msgfrom['username']."','".$msgfrom['uid']."','$msgto','$box','1','$subject','".$this->base->time."','0','$message','".$this->base->app['appid']."')"); $lastpmid = $this->db->insert_id(); } else { $this->db->query("UPDATE ".UC_DBTABLEPRE."pms SET subject='$subject', message='$message', dateline='".$this->base->time."', new='1', fromappid='".$this->base->app['appid']."' WHERE msgfromid='$msgfrom[uid]' AND msgtoid='$msgto' AND folder='inbox' AND related='0'"); } if(!$savebox) { $sessionexist = $this->db->result_first("SELECT count(*) FROM ".UC_DBTABLEPRE."pms WHERE msgfromid='$msgto' AND msgtoid='$msgfrom[uid]' AND folder='inbox' AND related='0'"); if($msgfrom['uid'] && !$sessionexist) { $this->db->query("INSERT INTO ".UC_DBTABLEPRE."pms (msgfrom,msgfromid,msgtoid,folder,new,subject,dateline,related,message,fromappid) VALUES ('".$msgfrom['username']."','$msgto','".$msgfrom['uid']."','$box','0','$subject','".$this->base->time."','0','$message','0')"); } $this->db->query("INSERT INTO ".UC_DBTABLEPRE."pms (msgfrom,msgfromid,msgtoid,folder,new,subject,dateline,related,message,fromappid) VALUES ('".$msgfrom['username']."','".$msgfrom['uid']."','$msgto','$box','1','$subject','".$this->base->time."','1','$message','".$this->base->app['appid']."')"); $lastpmid = $this->db->insert_id(); } } else { $this->db->query("INSERT INTO ".UC_DBTABLEPRE."pms (msgfrom,msgfromid,msgtoid,folder,new,subject,dateline,related,message,fromappid) VALUES ('".$msgfrom['username']."','".$msgfrom['uid']."','$msgto','$box','1','$subject','".$this->base->time."','0','$message','".$this->base->app['appid']."')"); $lastpmid = $this->db->insert_id(); } $this->db->query("REPLACE INTO ".UC_DBTABLEPRE."newpm (uid) VALUES ('$msgto')"); return $lastpmid; } function set_ignore($uid) { $this->db->query("DELETE FROM ".UC_DBTABLEPRE."newpm WHERE uid='$uid'"); } function check_newpm($uid, $more) { if($more < 2) { $newpm = $this->db->result_first("SELECT count(*) FROM ".UC_DBTABLEPRE."newpm WHERE uid='$uid'"); if($newpm) { $newpm = $this->db->result_first("SELECT count(*) FROM ".UC_DBTABLEPRE."pms WHERE (related='0' AND msgfromid>'0' OR msgfromid='0') AND msgtoid='$uid' AND folder='inbox' AND new='1'"); if($more) { $newprvpm = $this->db->result_first("SELECT count(*) FROM ".UC_DBTABLEPRE."pms WHERE related='0' AND msgfromid>'0' AND msgtoid='$uid' AND folder='inbox' AND new='1'"); return array('newpm' => $newpm, 'newprivatepm' => $newprvpm); } else { return $newpm; } } } else { $newpm = $this->db->result_first("SELECT count(*) FROM ".UC_DBTABLEPRE."pms WHERE (related='0' AND msgfromid>'0' OR msgfromid='0') AND msgtoid='$uid' AND folder='inbox' AND new='1'"); $newprvpm = $this->db->result_first("SELECT count(*) FROM ".UC_DBTABLEPRE."pms WHERE related='0' AND msgfromid>'0' AND msgtoid='$uid' AND folder='inbox' AND new='1'"); if($more == 2 || $more == 3) { $annpm = $this->db->result_first("SELECT count(*) FROM ".UC_DBTABLEPRE."pms WHERE related='0' AND msgtoid='0' AND folder='inbox'"); $syspm = $this->db->result_first("SELECT count(*) FROM ".UC_DBTABLEPRE."pms WHERE related='0' AND msgtoid='$uid' AND folder='inbox' AND msgfromid='0'"); } if($more == 2) { return array('newpm' => $newpm, 'newprivatepm' => $newprvpm, 'announcepm' => $annpm, 'systempm' => $syspm); } if($more == 4) { return array('newpm' => $newpm, 'newprivatepm' => $newprvpm); } else { $pm = $this->db->fetch_first("SELECT pm.dateline,pm.msgfromid,m.username as msgfrom,pm.message FROM ".UC_DBTABLEPRE."pms pm LEFT JOIN ".UC_DBTABLEPRE."members m ON pm.msgfromid = m.uid WHERE (pm.related='0' OR pm.msgfromid='0') AND pm.msgtoid='$uid' AND pm.folder='inbox' ORDER BY pm.dateline DESC LIMIT 1"); return array('newpm' => $newpm, 'newprivatepm' => $newprvpm, 'announcepm' => $annpm, 'systempm' => $syspm, 'lastdate' => $pm['dateline'], 'lastmsgfromid' => $pm['msgfromid'], 'lastmsgfrom' => $pm['msgfrom'], 'lastmsg' => $pm['message']); } } } function deletepm($uid, $pmids) { $this->db->query("DELETE FROM ".UC_DBTABLEPRE."pms WHERE msgtoid='$uid' AND pmid IN (".$this->base->implode($pmids).")"); $delnum = $this->db->affected_rows(); return $delnum; } function deleteuidpm($uid, $ids) { $delnum = 0; if($ids) { $delnum = 1; $deluids = $this->base->implode($ids); $this->db->query("DELETE FROM ".UC_DBTABLEPRE."pms WHERE msgfromid IN ($deluids) AND msgtoid='$uid' AND folder='inbox' AND related='0'", 'UNBUFFERED'); $this->db->query("UPDATE ".UC_DBTABLEPRE."pms SET delstatus=2 WHERE msgfromid IN ($deluids) AND msgtoid='$uid' AND folder='inbox' AND delstatus=0", 'UNBUFFERED'); $this->db->query("UPDATE ".UC_DBTABLEPRE."pms SET delstatus=1 WHERE msgtoid IN ($deluids) AND msgfromid='$uid' AND folder='inbox' AND delstatus=0", 'UNBUFFERED'); $this->db->query("DELETE FROM ".UC_DBTABLEPRE."pms WHERE msgfromid IN ($deluids) AND msgtoid='$uid' AND delstatus=1 AND folder='inbox'", 'UNBUFFERED'); $this->db->query("DELETE FROM ".UC_DBTABLEPRE."pms WHERE msgtoid IN ($deluids) AND msgfromid='$uid' AND delstatus=2 AND folder='inbox'", 'UNBUFFERED'); } return $delnum; } function get_blackls($uid, $uids = array()) { if(!$uids) { $blackls = $this->db->result_first("SELECT blacklist FROM ".UC_DBTABLEPRE."memberfields WHERE uid='$uid'"); } else { $uids = $this->base->implode($uids); $blackls = array(); $query = $this->db->query("SELECT uid, blacklist FROM ".UC_DBTABLEPRE."memberfields WHERE uid IN ($uids)"); while($data = $this->db->fetch_array($query)) { $blackls[$data['uid']] = explode(',', $data['blacklist']); } } return $blackls; } function set_blackls($uid, $blackls) { $this->db->query("UPDATE ".UC_DBTABLEPRE."memberfields SET blacklist='$blackls' WHERE uid='$uid'"); return $this->db->affected_rows(); } function update_blackls($uid, $username, $action = 1) { $username = !is_array($username) ? array($username) : $username; if($action == 1) { if(!in_array('{ALL}', $username)) { $usernames = $this->base->implode($username); $query = $this->db->query("SELECT username FROM ".UC_DBTABLEPRE."members WHERE username IN ($usernames)"); $usernames = array(); while($data = $this->db->fetch_array($query)) { $usernames[addslashes($data['username'])] = addslashes($data['username']); } if(!$usernames) { return 0; } $blackls = addslashes($this->db->result_first("SELECT blacklist FROM ".UC_DBTABLEPRE."memberfields WHERE uid='$uid'")); if($blackls) { $list = explode(',', $blackls); foreach($list as $k => $v) { if(in_array($v, $usernames)) { unset($usernames[$v]); } } } if(!$usernames) { return 1; } $listnew = implode(',', $usernames); $blackls .= $blackls !== '' ? ','.$listnew : $listnew; } else { $blackls = addslashes($this->db->result_first("SELECT blacklist FROM ".UC_DBTABLEPRE."memberfields WHERE uid='$uid'")); $blackls .= ',{ALL}'; } } else { $blackls = addslashes($this->db->result_first("SELECT blacklist FROM ".UC_DBTABLEPRE."memberfields WHERE uid='$uid'")); $list = $blackls = explode(',', $blackls); foreach($list as $k => $v) { if(in_array($v, $username)) { unset($blackls[$k]); } } $blackls = implode(',', $blackls); } $this->db->query("UPDATE ".UC_DBTABLEPRE."memberfields SET blacklist='$blackls' WHERE uid='$uid'"); return 1; } function removecode($str, $length) { return trim($this->base->cutstr(preg_replace(array( "/\[(email|code|quote|img)=?.*\].*?\[\/(email|code|quote|img)\]/siU", "/\[\/?(b|i|url|u|color|size|font|align|list|indent|float)=?.*\]/siU", "/\r\n/", ), '', $str), $length)); } function count_pm_by_fromuid($uid, $timeoffset = 86400) { $dateline = $this->base->time - intval($timeoffset); return $this->db->result_first("SELECT COUNT(*) FROM ".UC_DBTABLEPRE."pms WHERE msgfromid='$uid' AND dateline>'$dateline'"); } function is_reply_pm($uid, $touids) { $touid_str = implode("', '", $touids); $pm_reply = $this->db->fetch_all("SELECT msgfromid, msgtoid FROM ".UC_DBTABLEPRE."pms WHERE msgfromid IN ('$touid_str') AND msgtoid='$uid' AND related=1", 'msgfromid'); foreach($touids as $val) { if(!isset($pm_reply[$val])) { return false; } } return true; } } function pm_datelinesort($a, $b) { if ($a['dateline'] == $b['dateline']) { return 0; } return ($a['dateline'] < $b['dateline']) ? -1 : 1; } ?>
PHP
<?php /* [UCenter] (C)2001-2009 Comsenz Inc. This is NOT a freeware, use is subject to license terms $Id: domain.php 848 2008-12-08 05:43:39Z zhaoxiongfei $ */ !defined('IN_UC') && exit('Access Denied'); class domainmodel { var $db; var $base; function __construct(&$base) { $this->domainmodel($base); } function domainmodel(&$base) { $this->base = $base; $this->db = $base->db; } function add_domain($domain, $ip) { if($domain) { $this->db->query("INSERT INTO ".UC_DBTABLEPRE."domains SET domain='$domain', ip='$ip'"); } return $this->db->insert_id(); } function get_total_num() { $data = $this->db->result_first("SELECT COUNT(*) FROM ".UC_DBTABLEPRE."domains"); return $data; } function get_list($page, $ppp, $totalnum) { $start = $this->base->page_get_start($page, $ppp, $totalnum); $data = $this->db->fetch_all("SELECT * FROM ".UC_DBTABLEPRE."domains LIMIT $start, $ppp"); return $data; } function delete_domain($arr) { $domainids = $this->base->implode($arr); $this->db->query("DELETE FROM ".UC_DBTABLEPRE."domains WHERE id IN ($domainids)"); return $this->db->affected_rows(); } function update_domain($domain, $ip, $id) { $this->db->query("UPDATE ".UC_DBTABLEPRE."domains SET domain='$domain', ip='$ip' WHERE id='$id'"); return $this->db->affected_rows(); } } ?>
PHP
<?php /* [UCenter] (C)2001-2009 Comsenz Inc. This is NOT a freeware, use is subject to license terms $Id: note.php 916 2009-01-19 05:56:07Z monkey $ */ !defined('IN_UC') && exit('Access Denied'); define('UC_NOTE_REPEAT', 5); define('UC_NOTE_TIMEOUT', 15); define('UC_NOTE_GC', 10000); define('API_RETURN_FAILED', '-1'); class notemodel { var $db; var $base; var $apps; var $operations = array(); var $notetype = 'HTTP'; function __construct(&$base) { $this->notemodel($base); } function notemodel(&$base) { $this->base = $base; $this->db = $base->db; $this->apps = $this->base->cache('apps'); $this->operations = array( 'test'=>array('', 'action=test'), 'deleteuser'=>array('', 'action=deleteuser'), 'renameuser'=>array('', 'action=renameuser'), 'deletefriend'=>array('', 'action=deletefriend'), 'gettag'=>array('', 'action=gettag', 'tag', 'updatedata'), 'getcreditsettings'=>array('', 'action=getcreditsettings'), 'getcredit'=>array('', 'action=getcredit'), 'updatecreditsettings'=>array('', 'action=updatecreditsettings'), 'updateclient'=>array('', 'action=updateclient'), 'updatepw'=>array('', 'action=updatepw'), 'updatebadwords'=>array('', 'action=updatebadwords'), 'updatehosts'=>array('', 'action=updatehosts'), 'updateapps'=>array('', 'action=updateapps'), 'updatecredit'=>array('', 'action=updatecredit'), ); } function get_total_num($all = TRUE) { } function get_list($page, $ppp, $totalnum, $all = TRUE) { } function delete_note($ids) { } function add($operation, $getdata='', $postdata='', $appids=array(), $pri = 0) { $extra = $varextra = ''; $appadd = $varadd = array(); foreach((array)$this->apps as $appid => $app) { $appid = $app['appid']; if($appid == intval($appid)) { if($appids && !in_array($appid, $appids)) { $appadd[] = 'app'.$appid."='1'"; } else { $varadd[] = "('noteexists{$appid}', '1')"; } } } if($appadd) { $extra = implode(',', $appadd); $extra = $extra ? ', '.$extra : ''; } if($varadd) { $varextra = implode(', ', $varadd); $varextra = $varextra ? ', '.$varextra : ''; } $getdata = addslashes($getdata); $postdata = addslashes($postdata); $this->db->query("INSERT INTO ".UC_DBTABLEPRE."notelist SET getdata='$getdata', operation='$operation', pri='$pri', postdata='$postdata'$extra"); $insert_id = $this->db->insert_id(); $insert_id && $this->db->query("REPLACE INTO ".UC_DBTABLEPRE."vars (name, value) VALUES ('noteexists', '1')$varextra"); return $insert_id; } function send() { register_shutdown_function(array($this, '_send')); } function _send() { $note = $this->_get_note(); if(empty($note)) { $this->db->query("REPLACE INTO ".UC_DBTABLEPRE."vars SET name='noteexists".UC_APPID."', value='0'"); return NULL; } $this->sendone(UC_APPID, 0, $note); $this->_gc(); } function sendone($appid, $noteid = 0, $note = '') { require_once UC_ROOT.'./lib/xml.class.php'; $return = FALSE; $app = $this->apps[$appid]; if($noteid) { $note = $this->_get_note_by_id($noteid); } $this->base->load('misc'); $apifilename = isset($app['apifilename']) && $app['apifilename'] ? $app['apifilename'] : 'uc.php'; if($app['extra']['apppath'] && @include $app['extra']['apppath'].'./api/'.$apifilename) { $uc_note = new uc_note(); $method = $note['operation']; if(is_string($method) && !empty($method)) { parse_str($note['getdata'], $note['getdata']); if(get_magic_quotes_gpc()) { $note['getdata'] = $this->base->dstripslashes($note['getdata']); } $note['postdata'] = xml_unserialize($note['postdata']); $response = $uc_note->$method($note['getdata'], $note['postdata']); } unset($uc_note); } else { $url = $this->get_url_code($note['operation'], $note['getdata'], $appid); $note['postdata'] = str_replace(array("\n", "\r"), '', $note['postdata']); $response = trim($_ENV['misc']->dfopen2($url, 0, $note['postdata'], '', 1, $app['ip'], UC_NOTE_TIMEOUT, TRUE)); } $returnsucceed = $response != '' && ($response == 1 || is_array(xml_unserialize($response))); $closedsqladd = $this->_close_note($note, $this->apps, $returnsucceed, $appid) ? ",closed='1'" : '';// if($returnsucceed) { if($this->operations[$note['operation']][2]) { $this->base->load($this->operations[$note['operation']][2]); $func = $this->operations[$note['operation']][3]; $_ENV[$this->operations[$note['operation']][2]]->$func($appid, $response); } $this->db->query("UPDATE ".UC_DBTABLEPRE."notelist SET app$appid='1', totalnum=totalnum+1, succeednum=succeednum+1, dateline='{$this->base->time}' $closedsqladd WHERE noteid='$note[noteid]'", 'SILENT'); $return = TRUE; } else { $this->db->query("UPDATE ".UC_DBTABLEPRE."notelist SET app$appid = app$appid-'1', totalnum=totalnum+1, dateline='{$this->base->time}' $closedsqladd WHERE noteid='$note[noteid]'", 'SILENT'); $return = FALSE; } return $return; } function _get_note() { $app_field = 'app'.UC_APPID; $data = $this->db->fetch_first("SELECT * FROM ".UC_DBTABLEPRE."notelist WHERE closed='0' AND $app_field<'1' AND $app_field>'-".UC_NOTE_REPEAT."' LIMIT 1"); return $data; } function _gc() { rand(0, UC_NOTE_GC) == 0 && $this->db->query("DELETE FROM ".UC_DBTABLEPRE."notelist WHERE closed='1'"); } function _close_note($note, $apps, $returnsucceed, $appid) { $note['app'.$appid] = $returnsucceed ? 1 : $note['app'.$appid] - 1; $appcount = count($apps); foreach($apps as $key => $app) { $appstatus = $note['app'.$app['appid']]; if(!$app['recvnote'] || $appstatus == 1 || $appstatus <= -UC_NOTE_REPEAT) { $appcount--; } } if($appcount < 1) { return TRUE; //$closedsqladd = ",closed='1'"; } } function _get_note_by_id($noteid) { $data = $this->db->fetch_first("SELECT * FROM ".UC_DBTABLEPRE."notelist WHERE noteid='$noteid'"); return $data; } function get_url_code($operation, $getdata, $appid) { $app = $this->apps[$appid]; $authkey = UC_KEY; $url = $app['url']; $apifilename = isset($app['apifilename']) && $app['apifilename'] ? $app['apifilename'] : 'uc.php'; $action = $this->operations[$operation][1]; $code = urlencode($this->base->authcode("$action&".($getdata ? "$getdata&" : '')."time=".$this->base->time, 'ENCODE', $authkey)); return $url."/api/$apifilename?code=$code"; } } ?>
PHP
<?php /* [UCenter] (C)2001-2009 Comsenz Inc. This is NOT a freeware, use is subject to license terms $Id: user.php 968 2009-10-29 02:06:45Z zhaoxiongfei $ */ !defined('IN_UC') && exit('Access Denied'); class usermodel { var $db; var $base; function __construct(&$base) { $this->usermodel($base); } function usermodel(&$base) { $this->base = $base; $this->db = $base->db; } function get_user_by_uid($uid) { $arr = $this->db->fetch_first("SELECT * FROM ".UC_DBTABLEPRE."members WHERE uid='$uid'"); return $arr; } function get_user_by_username($username) { $arr = $this->db->fetch_first("SELECT * FROM ".UC_DBTABLEPRE."members WHERE username='$username'"); return $arr; } function get_user_by_email($email) { $arr = $this->db->fetch_first("SELECT * FROM ".UC_DBTABLEPRE."members WHERE email='$email'"); return $arr; } function check_username($username) { $guestexp = '\xA1\xA1|\xAC\xA3|^Guest|^\xD3\xCE\xBF\xCD|\xB9\x43\xAB\xC8'; $len = strlen($username); if($len > 15 || $len < 3 || preg_match("/\s+|^c:\\con\\con|[%,\*\"\s\<\>\&]|$guestexp/is", $username)) { return FALSE; } else { return TRUE; } } function check_mergeuser($username) { $data = $this->db->result_first("SELECT count(*) FROM ".UC_DBTABLEPRE."mergemembers WHERE appid='".$this->base->app['appid']."' AND username='$username'"); return $data; } function check_usernamecensor($username) { $_CACHE['badwords'] = $this->base->cache('badwords'); $censorusername = $this->base->get_setting('censorusername'); $censorusername = $censorusername['censorusername']; $censorexp = '/^('.str_replace(array('\\*', "\r\n", ' '), array('.*', '|', ''), preg_quote(($censorusername = trim($censorusername)), '/')).')$/i'; $usernamereplaced = isset($_CACHE['badwords']['findpattern']) && !empty($_CACHE['badwords']['findpattern']) ? @preg_replace($_CACHE['badwords']['findpattern'], $_CACHE['badwords']['replace'], $username) : $username; if(($usernamereplaced != $username) || ($censorusername && preg_match($censorexp, $username))) { return FALSE; } else { return TRUE; } } function check_usernameexists($username) { $data = $this->db->result_first("SELECT username FROM ".UC_DBTABLEPRE."members WHERE username='$username'"); return $data; } function check_emailformat($email) { return strlen($email) > 6 && preg_match("/^[\w\-\.]+@[\w\-\.]+(\.\w+)+$/", $email); } function check_emailaccess($email) { $setting = $this->base->get_setting(array('accessemail', 'censoremail')); $accessemail = $setting['accessemail']; $censoremail = $setting['censoremail']; $accessexp = '/('.str_replace("\r\n", '|', preg_quote(trim($accessemail), '/')).')$/i'; $censorexp = '/('.str_replace("\r\n", '|', preg_quote(trim($censoremail), '/')).')$/i'; if($accessemail || $censoremail) { if(($accessemail && !preg_match($accessexp, $email)) || ($censoremail && preg_match($censorexp, $email))) { return FALSE; } else { return TRUE; } } else { return TRUE; } } function check_emailexists($email, $username = '') { $sqladd = $username !== '' ? "AND username<>'$username'" : ''; $email = $this->db->result_first("SELECT email FROM ".UC_DBTABLEPRE."members WHERE email='$email' $sqladd"); return $email; } function check_login($username, $password, &$user) { $user = $this->get_user_by_username($username); if(empty($user['username'])) { return -1; } elseif($user['password'] != md5(md5($password).$user['salt'])) { return -2; } return $user['uid']; } function add_user($username, $password, $email, $salt, $uid = 0, $questionid = '', $answer = '', $regip = '') { $regip = empty($regip) ? $this->base->onlineip : $regip; $password = md5(md5($password).$salt); $sqladd = $uid ? "uid='".intval($uid)."'," : ''; $sqladd .= $questionid > 0 ? " secques='".$this->quescrypt($questionid, $answer)."'," : " secques='',"; $this->db->query("INSERT INTO ".UC_DBTABLEPRE."members SET $sqladd username='$username', password='$password', email='$email', regip='$regip', regdate='".$this->base->time."', salt='$salt'"); $uid = $this->db->insert_id(); $this->db->query("INSERT INTO ".UC_DBTABLEPRE."memberfields SET uid='$uid'"); return $uid; } function edit_user($username, $oldpw, $newpw, $email, $salt = '', $ignoreoldpw = 0, $questionid = '', $answer = '') { $data = $this->db->fetch_first("SELECT username, uid, password FROM ".UC_DBTABLEPRE."members WHERE username='$username'"); if($ignoreoldpw) { $isprotected = $this->db->result_first("SELECT COUNT(*) FROM ".UC_DBTABLEPRE."protectedmembers WHERE uid = '$data[uid]'"); if($isprotected) { return -8; } } if(!$ignoreoldpw && $data['password'] != md5(md5($oldpw).$salt)) { return -1; } $sqladd = $newpw ? "password='".md5(md5($newpw).$salt)."', `salt`='$salt'" : ''; $sqladd .= $email ? ($sqladd ? ',' : '')." email='$email'" : ''; if($questionid !== '') { if($questionid > 0) { $sqladd .= ($sqladd ? ',' : '')." secques='".$this->quescrypt($questionid, $answer)."'"; } else { $sqladd .= ($sqladd ? ',' : '')." secques=''"; } } if($sqladd || $emailadd) { $this->db->query("UPDATE ".UC_DBTABLEPRE."members SET $sqladd WHERE username='$username'"); return $this->db->affected_rows(); } else { return -7; } } function delete_user($uidsarr) { $uidsarr = (array)$uidsarr; if(!$uidsarr) { return 0; } $uids = $this->base->implode($uidsarr); $arr = $this->db->fetch_all("SELECT uid FROM ".UC_DBTABLEPRE."protectedmembers WHERE uid IN ($uids)"); $puids = array(); foreach((array)$arr as $member) { $puids[] = $member['uid']; } $uids = $this->base->implode(array_diff($uidsarr, $puids)); if($uids) { $this->db->query("DELETE FROM ".UC_DBTABLEPRE."members WHERE uid IN($uids)"); $this->db->query("DELETE FROM ".UC_DBTABLEPRE."memberfields WHERE uid IN($uids)"); uc_user_deleteavatar($uidsarr); $this->base->load('note'); $_ENV['note']->add('deleteuser', "ids=$uids"); return $this->db->affected_rows(); } else { return 0; } } function get_total_num($sqladd = '') { $data = $this->db->result_first("SELECT COUNT(*) FROM ".UC_DBTABLEPRE."members $sqladd"); return $data; } function get_list($page, $ppp, $totalnum, $sqladd) { $start = $this->base->page_get_start($page, $ppp, $totalnum); $data = $this->db->fetch_all("SELECT * FROM ".UC_DBTABLEPRE."members $sqladd LIMIT $start, $ppp"); return $data; } function name2id($usernamesarr) { $usernamesarr = uc_addslashes($usernamesarr, 1, TRUE); $usernames = $this->base->implode($usernamesarr); $query = $this->db->query("SELECT uid FROM ".UC_DBTABLEPRE."members WHERE username IN($usernames)"); $arr = array(); while($user = $this->db->fetch_array($query)) { $arr[] = $user['uid']; } return $arr; } function quescrypt($questionid, $answer) { return $questionid > 0 && $answer != '' ? substr(md5($answer.md5($questionid)), 16, 8) : ''; } } ?>
PHP
<?php /* [UCenter] (C)2001-2009 Comsenz Inc. This is NOT a freeware, use is subject to license terms $Id: friend.php 773 2008-11-26 08:45:08Z zhaoxiongfei $ */ !defined('IN_UC') && exit('Access Denied'); class friendmodel { var $db; var $base; function __construct(&$base) { $this->friendmodel($base); } function friendmodel(&$base) { $this->base = $base; $this->db = $base->db; } function add($uid, $friendid, $comment='') { $direction = $this->db->result_first("SELECT direction FROM ".UC_DBTABLEPRE."friends WHERE uid='$friendid' AND friendid='$uid' LIMIT 1"); if($direction == 1) { $this->db->query("INSERT INTO ".UC_DBTABLEPRE."friends SET uid='$uid', friendid='$friendid', comment='$comment', direction='3'", 'SILENT'); $this->db->query("UPDATE ".UC_DBTABLEPRE."friends SET direction='3' WHERE uid='$friendid' AND friendid='$uid'"); return 1; } elseif($direction == 2) { return 1; } elseif($direction == 3) { return -1; } else { $this->db->query("INSERT INTO ".UC_DBTABLEPRE."friends SET uid='$uid', friendid='$friendid', comment='$comment', direction='1'", 'SILENT'); return $this->db->insert_id(); } } function delete($uid, $friendids) { $friendids = $this->base->implode($friendids); $this->db->query("DELETE FROM ".UC_DBTABLEPRE."friends WHERE uid='$uid' AND friendid IN ($friendids)"); $affectedrows = $this->db->affected_rows(); if($affectedrows > 0) { $this->db->query("UPDATE ".UC_DBTABLEPRE."friends SET direction=1 WHERE uid IN ($friendids) AND friendid='$uid' AND direction='3'"); } return $affectedrows; } function get_totalnum_by_uid($uid, $direction = 0) { $sqladd = ''; if($direction == 0) { $sqladd = "uid='$uid'"; } elseif($direction == 1) { $sqladd = "uid='$uid' AND direction='1'"; } elseif($direction == 2) { $sqladd = "friendid='$uid' AND direction='1'"; } elseif($direction == 3) { $sqladd = "uid='$uid' AND direction='3'"; } $totalnum = $this->db->result_first("SELECT COUNT(*) FROM ".UC_DBTABLEPRE."friends WHERE $sqladd"); return $totalnum; } function get_list($uid, $page, $pagesize, $totalnum, $direction = 0) { $start = $this->base->page_get_start($page, $pagesize, $totalnum); $sqladd = ''; if($direction == 0) { $sqladd = "f.uid='$uid'"; } elseif($direction == 1) { $sqladd = "f.uid='$uid' AND f.direction='1'"; } elseif($direction == 2) { $sqladd = "f.friendid='$uid' AND f.direction='1'"; } elseif($direction == 3) { $sqladd = "f.uid='$uid' AND f.direction='3'"; } if($sqladd) { $data = $this->db->fetch_all("SELECT f.*, m.username FROM ".UC_DBTABLEPRE."friends f LEFT JOIN ".UC_DBTABLEPRE."members m ON f.friendid=m.uid WHERE $sqladd LIMIT $start, $pagesize"); return $data; } else { return array(); } } function is_friend($uid, $friendids, $direction = 0) { $friendid_str = implode("', '", $friendids); $sqladd = ''; if($direction == 0) { $sqladd = "uid='$uid'"; } elseif($direction == 1) { $sqladd = "uid='$uid' AND friendid IN ('$friendid_str') AND direction='1'"; } elseif($direction == 2) { $sqladd = "friendid='$uid' AND uid IN ('$friendid_str') AND direction='1'"; } elseif($direction == 3) { $sqladd = "uid='$uid' AND friendid IN ('$friendid_str') AND direction='3'"; } if($this->db->result_first("SELECT COUNT(*) FROM ".UC_DBTABLEPRE."friends WHERE $sqladd") == count($friendids)) { return true; } else { return false; } } } ?>
PHP
<?php /* [UCenter] (C)2001-2009 Comsenz Inc. This is NOT a freeware, use is subject to license terms $Id: app.php 846 2008-12-08 05:37:05Z zhaoxiongfei $ */ !defined('IN_UC') && exit('Access Denied'); class appmodel { var $db; var $base; function __construct(&$base) { $this->appmodel($base); } function appmodel(&$base) { $this->base = $base; $this->db = $base->db; } function get_apps($col = '*', $where = '') { $arr = $this->db->fetch_all("SELECT $col FROM ".UC_DBTABLEPRE."applications".($where ? ' WHERE '.$where : ''), 'appid'); foreach($arr as $k => $v) { isset($v['extra']) && !empty($v['extra']) && $v['extra'] = unserialize($v['extra']); unset($v['authkey']); $arr[$k] = $v; } return $arr; } } ?>
PHP
<?php /* [UCenter] (C)2001-2009 Comsenz Inc. This is NOT a freeware, use is subject to license terms $Id: misc.php 846 2008-12-08 05:37:05Z zhaoxiongfei $ */ !defined('IN_UC') && exit('Access Denied'); define('UC_ARRAY_SEP_1', 'UC_ARRAY_SEP_1'); define('UC_ARRAY_SEP_2', 'UC_ARRAY_SEP_2'); class miscmodel { var $db; var $base; function __construct(&$base) { $this->miscmodel($base); } function miscmodel(&$base) { $this->base = $base; $this->db = $base->db; } function get_apps($col = '*', $where = '') { $arr = $this->db->fetch_all("SELECT $col FROM ".UC_DBTABLEPRE."applications".($where ? ' WHERE '.$where : '')); return $arr; } function delete_apps($appids) { } function update_app($appid, $name, $url, $authkey, $charset, $dbcharset) { } //private function alter_app_table($appid, $operation = 'ADD') { } function get_host_by_url($url) { } function check_url($url) { } function check_ip($url) { } function test_api($url, $ip = '') { } function dfopen2($url, $limit = 0, $post = '', $cookie = '', $bysocket = FALSE, $ip = '', $timeout = 15, $block = TRUE, $encodetype = 'URLENCODE') { $__times__ = isset($_GET['__times__']) ? intval($_GET['__times__']) + 1 : 1; if($__times__ > 2) { return ''; } $url .= (strpos($url, '?') === FALSE ? '?' : '&')."__times__=$__times__"; return $this->dfopen($url, $limit, $post, $cookie, $bysocket, $ip, $timeout, $block, $encodetype); } function dfopen($url, $limit = 0, $post = '', $cookie = '', $bysocket = FALSE , $ip = '', $timeout = 15, $block = TRUE, $encodetype = 'URLENCODE') { //error_log("[uc_client]\r\nurl: $url\r\npost: $post\r\n\r\n", 3, 'c:/log/php_fopen.txt'); $return = ''; $matches = parse_url($url); $host = $matches['host']; $path = $matches['path'] ? $matches['path'].($matches['query'] ? '?'.$matches['query'] : '') : '/'; $port = !empty($matches['port']) ? $matches['port'] : 80; if($post) { $out = "POST $path HTTP/1.0\r\n"; $out .= "Accept: */*\r\n"; //$out .= "Referer: $boardurl\r\n"; $out .= "Accept-Language: zh-cn\r\n"; $boundary = $encodetype == 'URLENCODE' ? '' : ';'.substr($post, 0, trim(strpos($post, "\n"))); $out .= $encodetype == 'URLENCODE' ? "Content-Type: application/x-www-form-urlencoded\r\n" : "Content-Type: multipart/form-data$boundary\r\n"; $out .= "User-Agent: $_SERVER[HTTP_USER_AGENT]\r\n"; $out .= "Host: $host\r\n"; $out .= 'Content-Length: '.strlen($post)."\r\n"; $out .= "Connection: Close\r\n"; $out .= "Cache-Control: no-cache\r\n"; $out .= "Cookie: $cookie\r\n\r\n"; $out .= $post; } else { $out = "GET $path HTTP/1.0\r\n"; $out .= "Accept: */*\r\n"; //$out .= "Referer: $boardurl\r\n"; $out .= "Accept-Language: zh-cn\r\n"; $out .= "User-Agent: $_SERVER[HTTP_USER_AGENT]\r\n"; $out .= "Host: $host\r\n"; $out .= "Connection: Close\r\n"; $out .= "Cookie: $cookie\r\n\r\n"; } $fp = @fsockopen(($ip ? $ip : $host), $port, $errno, $errstr, $timeout); if(!$fp) { return ''; } else { stream_set_blocking($fp, $block); stream_set_timeout($fp, $timeout); @fwrite($fp, $out); $status = stream_get_meta_data($fp); if(!$status['timed_out']) { while (!feof($fp)) { if(($header = @fgets($fp)) && ($header == "\r\n" || $header == "\n")) { break; } } $stop = false; while(!feof($fp) && !$stop) { $data = fread($fp, ($limit == 0 || $limit > 8192 ? 8192 : $limit)); $return .= $data; if($limit) { $limit -= strlen($data); $stop = $limit <= 0; } } } @fclose($fp); return $return; } } function array2string($arr) { $s = $sep = ''; if($arr && is_array($arr)) { foreach($arr as $k => $v) { $s .= $sep.$k.UC_ARRAY_SEP_1.$v; $sep = UC_ARRAY_SEP_2; } } return $s; } function string2array($s) { $arr = explode(UC_ARRAY_SEP_2, $s); $arr2 = array(); foreach($arr as $k => $v) { list($key, $val) = explode(UC_ARRAY_SEP_1, $v); $arr2[$key] = $val; } return $arr2; } } ?>
PHP
<?php /* [UCenter] (C)2001-2009 Comsenz Inc. This is NOT a freeware, use is subject to license terms $Id: tag.php 753 2008-11-14 06:48:25Z cnteacher $ */ !defined('IN_UC') && exit('Access Denied'); class tagmodel { var $db; var $base; function __construct(&$base) { $this->tagmodel($base); } function tagmodel(&$base) { $this->base = $base; $this->db = $base->db; } function get_tag_by_name($tagname) { $arr = $this->db->fetch_all("SELECT * FROM ".UC_DBTABLEPRE."tags WHERE tagname='$tagname'"); return $arr; } function get_template($appid) { $result = $this->db->result_first("SELECT tagtemplates FROM ".UC_DBTABLEPRE."applications WHERE appid='$appid'"); return $result; } function updatedata($appid, $data) { $appid = intval($appid); include_once UC_ROOT.'lib/xml.class.php'; $data = xml_unserialize($data); $this->base->load('app'); $data[0] = addslashes($data[0]); $datanew = array(); if(is_array($data[1])) { foreach($data[1] as $r) { $datanew[] = $_ENV['misc']->array2string($r); } } $tmp = $_ENV['app']->get_apps('type', "appid='$appid'"); $datanew = addslashes($tmp[0]['type']."\t".implode("\t", $datanew)); if(!empty($data[0])) { $return = $this->db->result_first("SELECT count(*) FROM ".UC_DBTABLEPRE."tags WHERE tagname='$data[0]' AND appid='$appid'"); if($return) { $this->db->query("UPDATE ".UC_DBTABLEPRE."tags SET data='$datanew', expiration='".$this->base->time."' WHERE tagname='$data[0]' AND appid='$appid'"); } else { $this->db->query("INSERT INTO ".UC_DBTABLEPRE."tags (tagname, appid, data, expiration) VALUES ('$data[0]', '$appid', '$datanew', '".$this->base->time."')"); } } } function formatcache($appid, $tagname) { $return = $this->db->result_first("SELECT count(*) FROM ".UC_DBTABLEPRE."tags WHERE tagname='$tagname' AND appid='$appid'"); if($return) { $this->db->query("UPDATE ".UC_DBTABLEPRE."tags SET expiration='0' WHERE tagname='$tagname' AND appid='$appid'"); } else { $this->db->query("INSERT INTO ".UC_DBTABLEPRE."tags (tagname, appid, expiration) VALUES ('$tagname', '$appid', '0')"); } } } ?>
PHP
<?php /* [UCenter] (C)2001-2009 Comsenz Inc. This is NOT a freeware, use is subject to license terms $Id: cache.php 846 2008-12-08 05:37:05Z zhaoxiongfei $ */ !defined('IN_UC') && exit('Access Denied'); if(!function_exists('file_put_contents')) { function file_put_contents($filename, $s) { $fp = @fopen($filename, 'w'); @fwrite($fp, $s); @fclose($fp); } } class cachemodel { var $db; var $base; var $map; function __construct(&$base) { $this->cachemodel($base); } function cachemodel(&$base) { $this->base = $base; $this->db = $base->db; $this->map = array( 'settings' => array('settings'), 'badwords' => array('badwords'), 'apps' => array('apps') ); } //public function updatedata($cachefile = '') { if($cachefile) { foreach((array)$this->map[$cachefile] as $modules) { $s = "<?php\r\n"; foreach((array)$modules as $m) { $method = "_get_$m"; $s .= '$_CACHE[\''.$m.'\'] = '.var_export($this->$method(), TRUE).";\r\n"; } $s .= "\r\n?>"; @file_put_contents(UC_DATADIR."./cache/$cachefile.php", $s); } } else { foreach((array)$this->map as $file => $modules) { $s = "<?php\r\n"; foreach($modules as $m) { $method = "_get_$m"; $s .= '$_CACHE[\''.$m.'\'] = '.var_export($this->$method(), TRUE).";\r\n"; } $s .= "\r\n?>"; @file_put_contents(UC_DATADIR."./cache/$file.php", $s); } } } function updatetpl() { } //private function _get_badwords() { $data = $this->db->fetch_all("SELECT * FROM ".UC_DBTABLEPRE."badwords"); $return = array(); if(is_array($data)) { foreach($data as $k => $v) { $return['findpattern'][$k] = $v['findpattern']; $return['replace'][$k] = $v['replacement']; } } return $return; } //private function _get_apps() { $this->base->load('app'); $apps = $_ENV['app']->get_apps(); $apps2 = array(); if(is_array($apps)) { foreach($apps as $v) { $v['extra'] = unserialize($v['extra']); $apps2[$v['appid']] = $v; } } return $apps2; } function _get_settings() { return $this->base->get_setting(); } } ?>
PHP
<?php return array ( 'default' => array ( 'hostname' => 'localhost', 'database' => '108wo_new', 'username' => 'root', 'password' => '123', 'tablepre' => '108wo_sso_', 'charset' => 'utf8', 'type' => 'mysql', 'debug' => true, 'pconnect' => 0, 'autoconnect' => 0 ) ); ?>
PHP
<?php /** * 路由配置文件 * 默认配置为default如下: * 'default'=>array( * 'm'=>'phpcms', * 'c'=>'index', * 'a'=>'init', * 'data'=>array( * 'POST'=>array( * 'catid'=>1 * ), * 'GET'=>array( * 'contentid'=>1 * ) * ) * ) * 基中“m”为模型,“c”为控制器,“a”为事件,“data”为其他附加参数。 * data为一个二维数组,可设置POST和GET的默认参数。POST和GET分别对应PHP中的$_POST和$_GET两个超全局变量。在程序中您可以使用$_POST['catid']来得到data下面POST中的数组的值。 * data中的所设置的参数等级比较低。如果外部程序有提交相同的名字的变量,将会覆盖配置文件中所设置的值。如: * 外部程序POST了一个变量catid=2那么你在程序中使用$_POST取到的值是2,而不是配置文件中所设置的1。 */ return array( 'default'=>array('m'=>'admin', 'c'=>'index', 'a'=>'init'), );
PHP
<?php define('UC_CONNECT', 'mysql'); define('UC_API', 'http://localhost/comsenz/uc'); define('UC_IP', ''); define('UC_DBHOST', 'localhost'); define('UC_DBUSER', 'root'); define('UC_DBPW', 'root'); define('UC_DBNAME', 'ucenter'); define('UC_DBTABLEPRE', 'uc_'); define('UC_DBCHARSET', 'gbk'); define('UC_APPID', '8'); define('UC_KEY', 'arqFDAQRFWQE2346fweqre'); define('UCUSE', '0');
PHP
<?php return array( //网站路径 'web_path' => '/108wo/phpsso_server/', //Session配置 'session_storage' => 'mysql', 'session_ttl' => 1800, 'session_savepath' => CACHE_PATH.'sessions/', 'session_n' => 0, //Cookie配置 'cookie_domain' => '', //Cookie 作用域 'cookie_path' => '/', //Cookie 作用路径 'cookie_pre' => 'vAyKg_', //Cookie 前缀,同一域名下安装多套系统时,请修改Cookie前缀 'cookie_ttl' => 0, //Cookie 生命周期,0 表示随浏览器进程 'js_path' => 'http://localhost/108wo/phpsso_server/statics/js/', //CDN JS 'css_path' => 'http://localhost/108wo/phpsso_server/statics/css/', //CDN CSS 'img_path' => 'http://localhost/108wo/phpsso_server/statics/images/', //CDN img 'upload_path' => PHPCMS_PATH.'uploadfile/', //上传文件路径 'app_path' => 'http://localhost/108wo/phpsso_server/',//动态域名配置地址 'charset' => 'utf-8', //网站字符集 'timezone' => 'Etc/GMT-8', //网站时区(只对php 5.1以上版本有效),Etc/GMT-8 实际表示的是 GMT+8 'debug' => 1, //是否显示调试信息 'admin_log' => 0, //是否记录后台操作日志 'errorlog' => 0, //是否保存错误日志 'gzip' => 1, //是否Gzip压缩后输出 'auth_key' => '6OeEUIM0ZYRwkZ7ScM4d', // //Cookie密钥 'lang' => 'zh-cn', //网站语言包 'admin_founders' => '1', //网站创始人ID,多个ID逗号分隔 'execution_sql' => 0, //EXECUTION_SQL //UCenter配置开始 'ucuse'=>'0',//是否开启UC 'uc_api'=>'http://localhost/comsenz/uc',//Ucenter api 地址 'uc_ip'=>'',//Ucenter api IP 'uc_dbhost'=>'localhost',//Ucenter 数据库主机名 'uc_dbuser'=>'root',//Ucenter 数据库用户名 'uc_dbpw'=>'root',//Ucenter 数据库密码 'uc_dbname'=>'ucenter',//Ucenter 数据库名 'uc_dbtablepre'=>'uc_',//Ucenter 数据库表前缀 'uc_dbcharset'=>'gbk',//Ucenter 数据库字符集 'uc_appid'=>'',//应用id(APP ID) 'uc_key'=>'',//Ucenter 通信密钥 ); ?>
PHP
<?php return array ( 'file1' => array ( 'type' => 'file', 'debug' => true, 'pconnect' => 0, 'autoconnect' => 0 ), 'template' => array ( 'hostname' => '210.78.140.2', 'port' => 11211, 'timeout' => 0, 'type' => 'memcache', 'debug' => true, 'pconnect' => 0, 'autoconnect' => 0 ) ); ?>
PHP
<?php return array ( 1 => array ( 'appid' => '1', 'type' => 'phpcms_v9', 'name' => 'phpcms v9', 'url' => 'http://localhost/108wo_new/', 'authkey' => 'qZdQRVXybU0wdhOnvbUq90PXZt0eF1gg', 'ip' => '', 'apifilename' => 'api.php?op=phpsso', 'charset' => 'utf-8', 'synlogin' => '1', ), ); ?>
PHP
<?php /** * index.php API 入口 * * @copyright (C) 2005-2010 PHPCMS * @license http://www.phpcms.cn/license/ * @lastmodify 2010-7-26 */ define('PHPCMS_PATH', dirname(__FILE__).DIRECTORY_SEPARATOR); include './phpcms/base.php'; $param = pc_base::load_sys_class('param'); $op = isset($_GET['op']) && trim($_GET['op']) ? trim($_GET['op']) : exit('Operation can not be empty'); if (!preg_match('/([^a-z_]+)/i',$op) && file_exists('api'.DIRECTORY_SEPARATOR.$op.'.php')) { include 'api'.DIRECTORY_SEPARATOR.$op.'.php'; } else { exit('API handler does not exist'); } ?>
PHP
<?php /** * index.php PHPCMS 入口 * * @copyright (C) 2005-2010 PHPCMS * @license http://www.phpcms.cn/license/ * @lastmodify 2010-6-1 */ //PHPCMS根目录 define('PHPCMS_PATH', dirname(__FILE__).DIRECTORY_SEPARATOR); include PHPCMS_PATH.'/phpcms/base.php'; pc_base::creat_app(); ?>
PHP
<?php header('location:index.php?m=admin'); ?>
PHP
<?php $filetype['dir'] = "文件夹"; $filetype['gif'] = "GIF 图像"; $filetype['htm'] = "HTML Document"; $filetype['html'] = "HTML Document"; $filetype['shtml'] = "shtmlfile"; $filetype['php'] = "php 脚本"; $filetype['asp'] = "Active Server Page"; $filetype['do'] = "DO 文件"; $filetype['swf'] = "Shockwave Flash Object"; $filetype['xml'] = "XML 文档"; $filetype['jpg'] = "JPEG 图像"; $filetype['jpeg'] = "JPEG 图像"; $filetype['bmp'] = "BMP 图像"; $filetype['tif'] = "TIF 文件"; $filetype['js'] = "JavaScript 文件"; $filetype['doc'] = "Microsoft Word 文档"; $filetype['docx'] = "Microsoft Word 文档"; $filetype['mp3'] = "MP3 格式声音"; $filetype['rar'] = "WinRAR 压缩文件"; $filetype['psd'] = "Adobe Photoshop Image"; $filetype['png'] = "Macromedia Firewords Doc"; $filetype['pdf'] = "Adobe Acrobat 7.0 Document"; $filetype['zip'] = "WinRAR ZIP 压缩文件"; $filetype['rm'] = "RealMedia"; $filetype['rmvb'] = "RealVideo VBR"; $filetype['wav'] = "波形声音"; $filetype['mid'] = "MIDI 序列"; $filetype['midi'] = "MIDI 序列"; $filetype['mpg'] = "电影剪辑"; $filetype['mpeg'] = "电影剪辑"; $filetype['asf'] = "Windows Media 音频/视频文件"; $filetype['asx'] = "Windows Media 音频/视频播放列表"; $filetype['mov'] = "QuickTime 影片"; $filetype['xls'] = "Microsoft Excel 工作表"; $filetype['chm'] = "已编译的 HTML 帮助文件"; $filetype['hlp'] = "帮助文件"; $filetype['exe'] = "应用程序"; $filetype['txt'] = "文本文档"; $filetype['other'] = "未知"; ?>
PHP
<?php /** * base.php PHPCMS框架入口文件 * * @copyright (C) 2005-2010 PHPCMS * @license http://www.phpcms.cn/license/ * @lastmodify 2010-6-7 */ define('IN_PHPCMS', true); //PHPCMS框架路径 define('PC_PATH', dirname(__FILE__).DIRECTORY_SEPARATOR); if(!defined('PHPCMS_PATH')) define('PHPCMS_PATH', PC_PATH.'..'.DIRECTORY_SEPARATOR); //缓存文件夹地址 define('CACHE_PATH', PHPCMS_PATH.'caches'.DIRECTORY_SEPARATOR); //主机协议 define('SITE_PROTOCOL', isset($_SERVER['SERVER_PORT']) && $_SERVER['SERVER_PORT'] == '443' ? 'https://' : 'http://'); //当前访问的主机名 define('SITE_URL', (isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : '')); //来源 define('HTTP_REFERER', isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : ''); //系统开始时间 define('SYS_START_TIME', microtime()); //加载公用函数库 pc_base::load_sys_func('global'); pc_base::load_sys_func('extention'); pc_base::auto_load_func(); pc_base::load_config('system','errorlog') ? set_error_handler('my_error_handler') : error_reporting(E_ERROR | E_WARNING | E_PARSE); //设置本地时差 function_exists('date_default_timezone_set') && date_default_timezone_set(pc_base::load_config('system','timezone')); define('CHARSET' ,pc_base::load_config('system','charset')); //输出页面字符集 header('Content-type: text/html; charset='.CHARSET); define('SYS_TIME', time()); //定义网站根路径 define('WEB_PATH',pc_base::load_config('system','web_path')); //js 路径 define('JS_PATH',pc_base::load_config('system','js_path')); //css 路径 define('CSS_PATH',pc_base::load_config('system','css_path')); //img 路径 define('IMG_PATH',pc_base::load_config('system','img_path')); //动态程序路径 define('APP_PATH',pc_base::load_config('system','app_path')); //应用静态文件路径 define('PLUGIN_STATICS_PATH',WEB_PATH.'statics/plugin/'); if(pc_base::load_config('system','gzip') && function_exists('ob_gzhandler')) { ob_start('ob_gzhandler'); } else { ob_start(); } //eddy 定义顶部产品栏目ID define('TOP_PRODUCT_CATID', 7); class pc_base { /** * 初始化应用程序 */ public static function creat_app() { return self::load_sys_class('application'); } /** * 加载系统类方法 * @param string $classname 类名 * @param string $path 扩展地址 * @param intger $initialize 是否初始化 */ public static function load_sys_class($classname, $path = '', $initialize = 1) { return self::_load_class($classname, $path, $initialize); } /** * 加载应用类方法 * @param string $classname 类名 * @param string $m 模块 * @param intger $initialize 是否初始化 */ public static function load_app_class($classname, $m = '', $initialize = 1) { $m = empty($m) && defined('ROUTE_M') ? ROUTE_M : $m; if (empty($m)) return false; return self::_load_class($classname, 'modules'.DIRECTORY_SEPARATOR.$m.DIRECTORY_SEPARATOR.'classes', $initialize); } /** * 加载数据模型 * @param string $classname 类名 */ public static function load_model($classname) { return self::_load_class($classname,'model'); } /** * 加载类文件函数 * @param string $classname 类名 * @param string $path 扩展地址 * @param intger $initialize 是否初始化 */ private static function _load_class($classname, $path = '', $initialize = 1) { static $classes = array(); if (empty($path)) $path = 'libs'.DIRECTORY_SEPARATOR.'classes'; $key = md5($path.$classname); if (isset($classes[$key])) { if (!empty($classes[$key])) { return $classes[$key]; } else { return true; } } if (file_exists(PC_PATH.$path.DIRECTORY_SEPARATOR.$classname.'.class.php')) { include PC_PATH.$path.DIRECTORY_SEPARATOR.$classname.'.class.php'; $name = $classname; if ($my_path = self::my_path(PC_PATH.$path.DIRECTORY_SEPARATOR.$classname.'.class.php')) { include $my_path; $name = 'MY_'.$classname; } if ($initialize) { $classes[$key] = new $name; } else { $classes[$key] = true; } return $classes[$key]; } else { return false; } } /** * 加载系统的函数库 * @param string $func 函数库名 */ public static function load_sys_func($func) { return self::_load_func($func); } /** * 自动加载autoload目录下函数库 * @param string $func 函数库名 */ public static function auto_load_func($path='') { return self::_auto_load_func($path); } /** * 加载应用函数库 * @param string $func 函数库名 * @param string $m 模型名 */ public static function load_app_func($func, $m = '') { $m = empty($m) && defined('ROUTE_M') ? ROUTE_M : $m; if (empty($m)) return false; return self::_load_func($func, 'modules'.DIRECTORY_SEPARATOR.$m.DIRECTORY_SEPARATOR.'functions'); } /** * 加载插件类库 */ public static function load_plugin_class($classname, $identification = '' ,$initialize = 1) { $identification = empty($identification) && defined('PLUGIN_ID') ? PLUGIN_ID : $identification; if (empty($identification)) return false; return pc_base::load_sys_class($classname, 'plugin'.DIRECTORY_SEPARATOR.$identification.DIRECTORY_SEPARATOR.'classes', $initialize); } /** * 加载插件函数库 * @param string $func 函数文件名称 * @param string $identification 插件标识 */ public static function load_plugin_func($func,$identification) { static $funcs = array(); $identification = empty($identification) && defined('PLUGIN_ID') ? PLUGIN_ID : $identification; if (empty($identification)) return false; $path = 'plugin'.DIRECTORY_SEPARATOR.$identification.DIRECTORY_SEPARATOR.'functions'.DIRECTORY_SEPARATOR.$func.'.func.php'; $key = md5($path); if (isset($funcs[$key])) return true; if (file_exists(PC_PATH.$path)) { include PC_PATH.$path; } else { $funcs[$key] = false; return false; } $funcs[$key] = true; return true; } /** * 加载插件数据模型 * @param string $classname 类名 */ public static function load_plugin_model($classname,$identification) { $identification = empty($identification) && defined('PLUGIN_ID') ? PLUGIN_ID : $identification; $path = 'plugin'.DIRECTORY_SEPARATOR.$identification.DIRECTORY_SEPARATOR.'model'; return self::_load_class($classname,$path); } /** * 加载函数库 * @param string $func 函数库名 * @param string $path 地址 */ private static function _load_func($func, $path = '') { static $funcs = array(); if (empty($path)) $path = 'libs'.DIRECTORY_SEPARATOR.'functions'; $path .= DIRECTORY_SEPARATOR.$func.'.func.php'; $key = md5($path); if (isset($funcs[$key])) return true; if (file_exists(PC_PATH.$path)) { include PC_PATH.$path; } else { $funcs[$key] = false; return false; } $funcs[$key] = true; return true; } /** * 加载函数库 * @param string $func 函数库名 * @param string $path 地址 */ private static function _auto_load_func($path = '') { if (empty($path)) $path = 'libs'.DIRECTORY_SEPARATOR.'functions'.DIRECTORY_SEPARATOR.'autoload'; $path .= DIRECTORY_SEPARATOR.'*.func.php'; $auto_funcs = glob(PC_PATH.DIRECTORY_SEPARATOR.$path); if(!empty($auto_funcs) && is_array($auto_funcs)) { foreach($auto_funcs as $func_path) { include $func_path; } } } /** * 是否有自己的扩展文件 * @param string $filepath 路径 */ public static function my_path($filepath) { $path = pathinfo($filepath); if (file_exists($path['dirname'].DIRECTORY_SEPARATOR.'MY_'.$path['basename'])) { return $path['dirname'].DIRECTORY_SEPARATOR.'MY_'.$path['basename']; } else { return false; } } /** * 加载配置文件 * @param string $file 配置文件 * @param string $key 要获取的配置荐 * @param string $default 默认配置。当获取配置项目失败时该值发生作用。 * @param boolean $reload 强制重新加载。 */ public static function load_config($file, $key = '', $default = '', $reload = false) { static $configs = array(); if (!$reload && isset($configs[$file])) { if (empty($key)) { return $configs[$file]; } elseif (isset($configs[$file][$key])) { return $configs[$file][$key]; } else { return $default; } } $path = CACHE_PATH.'configs'.DIRECTORY_SEPARATOR.$file.'.php'; if (file_exists($path)) { $configs[$file] = include $path; } if (empty($key)) { return $configs[$file]; } elseif (isset($configs[$file][$key])) { return $configs[$file][$key]; } else { return $default; } } }
PHP
<?php defined('IN_PHPCMS') or exit('Access Denied'); defined('UNINSTALL') or exit('Access Denied'); return array('tags', 'tags_content'); ?>
PHP
<?php defined('IN_PHPCMS') or exit('Access Denied'); defined('UNINSTALL') or exit('Access Denied'); ?>
PHP
<?php defined('IN_ADMIN') or exit('No permission resources.'); include $this->admin_tpl('header','admin'); $models = getcache('model', 'commons'); $sitelist = getcache('sitelist', 'commons'); $i=0; foreach($models as $model_v){ $model_arr .= 'model_arr['.$i++.'] = new Array("'.$model_v['modelid'].'","'.$model_v['name'].'","'.$model_v['siteid'].'");'."\n"; } ?> <script type="text/javascript"> var model_arr = new Array(); <?php echo $model_arr ?> function select_modelid(modelid){ var model_option = '<option value="0">所有模型</option>'; for(i=0; i< <?php echo $i?>; i++){ if(model_arr[i][2] == modelid){ model_option += '<option value="'+model_arr[i][0]+'" >'+model_arr[i][1]+'</option>'; } } $('#modelid').html(model_option); } </script> <div class="pad_10"> <form action="?m=tags&c=tags&a=create" method="post" name="myform" > <table cellpadding="2" cellspacing="1" class="table_form" width="100%"> <tr> <th width="20%">请选择需要重建的站点:</th> <td><select name="siteid" onchange="select_modelid($(this).val())"> <option value="0">所有站点</option> <?php foreach($sitelist as $site_v){ ?> <option value="<?php echo $site_v['siteid'];?>"><?php echo $site_v['name'];?></option> <?php }?> </select></td> </tr> <tr> <th width="20%">请选择需要重建的模型:</th> <td><select name="modelid" id="modelid" > <option value="0">所有模型</option> </select></td> </tr> <tr> <th></th> <td><input type="submit" name="dosubmit" id="dosubmit" value=" <?php echo L('submit')?> "></td> </tr> </table> </form> </div> </body> </html>
PHP
<?php defined('IN_ADMIN') or exit('No permission resources.'); include $this->admin_tpl('header','admin'); ?> <div class="pad-lr-10"> <form action="?m=tags&c=tags&a=edit&tagid=<?php echo $_GET['tagid']?>" method="post" id="myform"> <table width="100%" class="table_form"> <tr> <th width="120">关键字:</th> <td class="y-bg"><input type="text" name="info[tag]" value="<?php echo $data['tag']?>" /></td> </tr> <tr> <th width="120">附加状态码</th> <td class="y-bg"><input type="text" name="info[style]" value="<?php echo $data['style']?>" /></td> </tr> <tr> <th width="120">使用次数</th> <td class="y-bg"><input type="text" name="info[usetimes]" value="<?php echo $data['usetimes']?>" /></td> </tr> <tr> <th>最后使用时间</th> <td class="y-bg"><?php echo form::date("info[lastusetime]",date('Y-m-d H:i:s', $data['lastusetime']),1,1)?></td> </tr> <tr> <th>点击量</th> <td class="y-bg"><input type="text" name="info[hits]" value="<?php echo $data['hits']?>" /></td> </tr> <tr> <th>最后点击时间</th> <td class="y-bg"><?php echo form::date("info[lasthittime]",date('Y-m-d H:i:s', $data['lasthittime']),1,1)?></td> </tr> <tr> <th><input type="hidden" name="tagid" value="<?php echo $_GET['tagid']?>" /></th> <td> <input type="submit" id="dosubmit" name="dosubmit" value="<?php echo L('submit')?>" /></td> </tr> </table> </form> </div> </body> </html>
PHP
<?php defined('IN_ADMIN') or exit('No permission resources.'); include $this->admin_tpl('header', 'admin'); ?> <div class="pad_10"> <div class="table-list"> <form action="" method="get"> <input type="hidden" name="m" value="tags" /> <input type="hidden" name="c" value="tags" /> <input type="hidden" name="a" id="action" value="delete" /> <table width="100%" cellspacing="0"> <thead> <tr> <th width="50"><input type="checkbox" value="" id="check_box" onclick="selectall('tagid[]');"></th> <th width="50">排序</th> <th>关键字</th> <th>使用次数</th> <th>最后使用时间</th> <th>点击次数</th> <th>最近访问时间</th> <th>相关操作</th> </tr> </thead> <tbody> <?php if(is_array($data)) foreach($data as $v){ ?> <tr> <td width="50" align="center"><input type="checkbox" value="<?php echo $v['tagid']?>" name="tagid[]"></td> <td><input type="text" name="listorder[]" value="<?php echo $v['listorder']?>" size="5" /></td> <td align="center"><?php echo $v['tag']?></td> <td align="center"><?php echo $v['usetimes']?></td> <td align="center"><?php echo date('Y-m-d H:i:s', $v['lastusetime'])?></td> <td align="center"><?php echo $v['hits']?></td> <td align="center"><?php echo date('Y-m-d H:i:s', $v['lasthittime'])?></td> <td align="center"><a href="?m=tags&c=tags&a=edit&tagid=<?php echo $v['tagid']?>">修改</a> | <a href="?m=tags&c=tags&a=delete&tagid=<?php echo $v['tagid']?>" onclick="return confirm('<?php echo htmlspecialchars(new_addslashes(L('confirm', array('message'=>$v['tag']))))?>')">删除</a></td> </tr> <?php } ?> </tbody> </table> <div class="btn"> <label for="check_box"><?php echo L('select_all')?>/<?php echo L('cancel')?></label> <input type="submit" class="button" name="dosubmit" value="<?php echo L('delete')?>" onclick="return confirm('您确认删除么,该操作无法恢复!')" /> <input type="submit" class="button" name="dosubmit" onclick="$('#action').val('listorder')" value=" 更新排序 " </div> </from> </div> </div> <div id="pages"><?php echo $pages?></div> </body> </html>
PHP
<?php defined('IN_PHPCMS') or exit('No permission resources.'); class index { public function __construct(){ $this->db = pc_base::load_model('tags_model'); $this->db_content = pc_base::load_model('tags_content_model'); } public function init(){ $tag = $_GET['tag']; $models = getcache('model', 'commons'); $sitelist = getcache('sitelist', 'commons'); $i=0; $siteid = intval($_GET['siteid']); $modelid = intval($_GET['modelid']); $orderby = intval($_GET['orderby']); foreach($models as $model_v){ $model_arr .= 'model_arr['.$i++.'] = new Array("'.$model_v['modelid'].'","'.$model_v['name'].'","'.$model_v['siteid'].'");'."\n"; } $page = isset($_GET['page']) && intval($_GET['page']) ? intval($_GET['page']) : 1; if($tag){ if($this->db->get_one(array('tag'=>$tag))){ $sql_arr = array('tag'=>$tag); if($siteid){ $sql_arr['siteid'] = $siteid; } if($modelid){ $sql_arr['modelid'] = $modelid; } if($orderby){ $sql_ord = 'updatetime desc'; }else{ $sql_ord = 'updatetime asc'; } $tagdata = $this->db_content->listinfo($sql_arr,$sql_ord, $page, 40); $pages = $this->db_content->pages; $total = $this->db_content->number; }else{ showmessage('标签不存在!'); } $CATEGORYS = getcache('category_content_'.$siteid,'commons'); include template('tags', 'tag'); }else{ $tagdata = $this->db->listinfo('','tagid desc', $page, 100); $pages = $this->db->pages; $total = $this->db->number; include template('tags', 'index'); } } }
PHP
<?php defined('IN_PHPCMS') or exit('No permission resources.'); pc_base::load_app_class('admin', 'admin', 0); class tags extends admin { private $db; public function __construct() { $this->db = pc_base::load_model('tags_model'); parent::__construct(); } public function init() { $page = isset($_GET['page']) && intval($_GET['page']) ? intval($_GET['page']) : 1; $data = $this->db->listinfo('','tagid desc', $page, 20); $pages = $this->db->pages; include $this->admin_tpl('tags_list'); } public function create(){ if(isset($_POST['dosubmit'])){ //$siteid = get_siteid(); $this->db_content = pc_base::load_model('tags_content_model'); $modelid = intval($_POST['modelid']); $siteid = intval($_POST['siteid']); if($siteid){ $this->db_content->delete(array('siteid'=>$siteid)); }else{ $this->db_content->query("TRUNCATE TABLE `phpcms_tags_content`"); $this->db->query("TRUNCATE TABLE `phpcms_tags`"); } $models = getcache('model', 'commons'); foreach($models as $models_v){ if($siteid && $models_v['siteid']!=$siteid)continue; if($modelid && $models_v['modelid']!=$modelid)continue; $keywords = $this->db->query("SELECT `keywords`,`url`,`id`,`title`,`catid`,`updatetime` FROM `phpcms_".$models_v[tablename]."`"); $keywords = $this->db->fetch_array(); foreach($keywords as $keyword){ $key = explode(' ', $keyword['keywords']); foreach($key as $key_v){ if($this->db->get_one("`tag`='$key_v'", 'tagid')){ $this->db->query("UPDATE `phpcms_tags` SET `usetimes`=usetimes+1 WHERE tag='$key_v'"); }else{ $this->db->query("INSERT INTO `phpcms_tags`(`tag`,`usetimes`,`lastusetime`,`lasthittime`)VALUES('$key_v',1,".SYS_TIME.",".SYS_TIME.")"); } $sql .= ",('$key_v','$keyword[url]','$keyword[title]',$models_v[siteid],$models_v[modelid],$keyword[id],$keyword[catid],$keyword[updatetime])\n"; } } } if(!$sql)showmessage('没有需要导入的数据', '?m=tags&c=tags&a=init'); $sql = "INSERT INTO `phpcms_tags_content` (`tag`,`url`,`title`,`siteid`,`modelid`,`contentid`,`catid`,`updatetime`) VALUES ".substr($sql, 1); $this->db->query($sql); showmessage('重建成功!', '?m=tags&c=tags&a=init'); }else{ include $this->admin_tpl('tags_create'); } } public function edit(){ if(isset($_POST['dosubmit'])){ $_POST['info']['lastusetime'] = strtotime($_POST['info']['lastusetime']); $_POST['info']['lasthittime'] = strtotime($_POST['info']['lasthittime']); $this->db->update($_POST['info'], array('tagid'=>$_GET['tagid'])); showmessage('更新成功!'); }else{ $data = $this->db->get_one("`tagid` = '$_GET[tagid]'"); if(!$data)showmessage('信息不存在或者已被删除!!', '?m=tags&c=tags&a=init'); pc_base::load_sys_class('form','',0); include $this->admin_tpl('tags_edit'); } } public function delete(){ if($_GET['tagid']){ if(is_array($_GET['tagid'])){ $_GET['tagid'] = implode(',', $_GET['tagid']); $this->db->query("DELETE FROM `phpcms_tags` WHERE `tagid` in ($_GET[tagid])"); }else{ $this->db->query("DELETE FROM `phpcms_tags` WHERE `tagid` in ($_GET[tagid])"); } showmessage('操作成功', '?m=tags&c=tags&a=init'); }else{ showmessage('参数不正确', '?m=tags&c=tags&a=init'); } } public function listorder(){ $tagid = $_GET['tagid']; if($tagid){ foreach($tagid as $n=>$id){ if(!$id)continue; $this->db->update('`listorder`='.intval($_GET['listorder'][$n]), array('tagid'=>$id)); } showmessage('更新成功!', '?m=tags&c=tags&a=init'); }else{ showmessage('参数不正确', '?m=tags&c=tags&a=init'); } } } ?>
PHP
<?php defined('IN_PHPCMS') or exit('Access Denied'); defined('INSTALL') or exit('Access Denied'); return array('tags', 'tags_content'); ?>
PHP
<?php error_reporting(E_ALL); defined('IN_PHPCMS') or exit('Access Denied'); defined('INSTALL') or exit('Access Denied'); $parentid = $menu_db->insert(array('name'=>'tags', 'parentid'=>29, 'm'=>'tags', 'c'=>'tags', 'a'=>'init', 'data'=>'', 'listorder'=>0, 'display'=>'1'), true); $menu_db->insert(array('name'=>'tags_create', 'parentid'=>$parentid, 'm'=>'tags', 'c'=>'tags', 'a'=>'create', 'data'=>'', 'listorder'=>0, 'display'=>'1')); $language = array('tags'=>'tags管理', 'tags_create'=>'tags重建'); ?>
PHP
<?php defined('IN_PHPCMS') or exit('Access Denied'); defined('INSTALL') or exit('Access Denied'); $module = 'tags'; $modulename = 'tags 标签'; $introduce = 'tags 标签模块'; $author = '世界首富'; $authorsite = 'http://www.phpcms.cn'; $authoremail = '754157556@qq.com'; ?>
PHP
<?php defined('IN_PHPCMS') or exit('Access Denied'); defined('UNINSTALL') or exit('Access Denied'); return ''; ?>
PHP
<?php defined('IN_PHPCMS') or exit('Access Denied'); defined('UNINSTALL') or exit('Access Denied'); $type_db = pc_base::load_model('type_model'); $typeid = $type_db->delete(array('module'=>'upgrade')); if(!$typeid) return FALSE; ?>
PHP
<?php defined('IN_ADMIN') or exit('No permission resources.');?> <?php include $this->admin_tpl('header', 'admin');?> <div class="pad-lr-10"> <div class="table-list"> <div class="explain-col"> <?php echo L('upgrade_notice');?> </div> <div class="bk15"></div> <form name="myform" action="" method="get" id="myform"> <input type="hidden" name="s" value="1" /> <input type="hidden" name="cover" value="<?php echo $_GET['cover']?>" /> <input name="m" value="upgrade" type="hidden" /> <input name="c" value="index" type="hidden" /> <input name="a" value="init" type="hidden" /> <table width="100%" cellspacing="0"> <thead> <tr> <th align="left" width="300"><?php echo L('currentversion')?><?php if(empty($pathlist)) {?><?php echo L('lastversion')?><?php }?></th> <th align="left"><?php echo L('updatetime')?></th> </tr> </thead> <tbody> <tr> <td align="left"><?php echo $current_version['pc_version'];?></td> <td align="left"><?php echo $current_version['pc_release'];?></td> </tr> </tbody> </table> <?php if(!empty($pathlist)) {?> <div class="bk15"></div> <table width="100%" cellspacing="0"> <thead> <tr> <th align="left" width="300"><?php echo L('updatelist')?></th> <th align="left"><?php echo L('updatetime')?></th> </tr> </thead> <tbody> <?php foreach($pathlist as $v) { ?> <tr> <td><?php echo $v;?></td> <td><?php echo substr($v, 15, 8);?></td> </tr> <?php }?> </tbody> </table> <div class="bk15"></div> <label for="cover"><font color="red"><?php echo L('covertemplate')?></font></label><input name="cover" id="cover" type="checkbox" value=1> <input name="dosubmit" type="submit" id="dosubmit" value="<?php echo L('begin_upgrade')?>" class="button"> <?php }?> </form> </div> </div> </body> </html>
PHP
<?php defined('IN_ADMIN') or exit('No permission resources.');?> <?php include $this->admin_tpl('header', 'admin');?> <div class="pad-lr-10"> <div class="table-list"> <div class="explain-col"> <?php echo L('check_file_notice');?> </div> <div class="bk15"></div> <table width="100%" cellspacing="0"> <thead> <tr> <th align="left"><?php echo L('modifyedfile')?></th> <th align="left"><?php echo L('lostfile')?></th> <th align="left"><?php echo L('unknowfile')?></th> </tr> </thead> <tbody> <tr> <td align="left"><?php echo count($diff);?></td> <td align="left"><?php echo count($lostfile);?></td> <td align="left"><?php echo count($unknowfile);?></td> </tr> </tbody> </table> <div class="bk15"></div> <?php if(!empty($diff)) {?> <table width="100%" cellspacing="0"> <thead> <tr> <th align="left"><?php echo L('modifyedfile')?></th> <th align="left"><?php echo L('lastmodifytime')?></th> <th align="left"><?php echo L('filesize')?></th> <th align="left"><?php echo L('operation')?></th> </tr> </thead> <tbody> <?php foreach($diff as $k=>$v) { ?> <tr> <td align="left"><?php echo base64_decode($k)?></td> <td align="left"><?php echo date("Y-m-d H:i:s", filemtime(base64_decode($k)))?></td> <td align="left"><?php echo sizecount(filesize(base64_decode($k)))?></td> <td align="left"><a href="javascript:void(0)" onclick="view('<?php echo base64_decode($k)?>')"><?php echo L('view')?></a> <a href="<?php echo APP_PATH,base64_decode($k);?>" target="_blank"><?php echo L('access')?></a></td> </tr> <?php } ?> </tbody> </table> <div class="bk15"></div> <?php }?> <?php if(!empty($unknowfile)) {?> <table width="100%" cellspacing="0"> <thead> <tr> <th align="left"><?php echo L('unknowfile')?></th> <th align="left"><?php echo L('lastmodifytime')?></th> <th align="left"><?php echo L('filesize')?></th> <th align="left"><?php echo L('operation')?></th> </tr> </thead> <tbody> <?php foreach($unknowfile as $k=>$v) { ?> <tr> <td align="left"><?php echo base64_decode($v)?></td> <td align="left"><?php echo date("Y-m-d H:i:s", filectime(base64_decode($v)))?></td> <td align="left"><?php echo sizecount(filesize(base64_decode($v)))?></td> <td align="left"><a href="javascript:void(0)" onclick="view('<?php echo base64_decode($v)?>')"><?php echo L('view')?></a> <a href="<?php echo APP_PATH,base64_decode($v);?>" target="_blank"><?php echo L('access')?></a></td> </tr> <?php } ?> </tbody> </table> <div class="bk15"></div> <?php }?> <?php if(!empty($lostfile)) {?> <table width="100%" cellspacing="0"> <thead> <tr> <th align="left"><?php echo L('lostfile')?></th> </tr> </thead> <tbody> <?php foreach($lostfile as $k) { ?> <tr> <td align="left"><?php echo base64_decode($k)?></td> </tr> <?php } ?> </tbody> </table> <?php }?> </div> </div> <script type="text/javascript"> <!-- function view(url) { window.top.art.dialog({id:'edit'}).close(); window.top.art.dialog({title:'<?php echo L('view_code')?>',id:'edit',iframe:'?m=scan&c=index&a=public_view&url='+url,width:'700',height:'500'}); } //--> </script> </body> </html>
PHP
<?php defined('IN_PHPCMS') or exit('No permission resources.'); pc_base::load_app_class('admin', 'admin', 0); class index extends admin { private $_filearr = array('api', 'phpcms', 'statics', ''); //md5验证地址 private $_upgrademd5 = 'http://www.phpcms.cn/upgrademd5/'; //补丁地址 private $_patchurl = 'http://download.phpcms.cn/v9/9.0/patch/'; public function __construct() { parent::__construct(); } public function init() { $patch_charset = str_replace('-', '', CHARSET); $upgrade_path_base = $this->_patchurl.$patch_charset.'/'; //获取当前版本 $current_version = pc_base::load_config('version'); $pathlist_str = @file_get_contents($upgrade_path_base); $pathlist = $allpathlist = array(); $key = -1; //获取压缩包列表 preg_match_all("/\"(patch_[\w_]+\.zip)\"/", $pathlist_str, $allpathlist); $allpathlist = $allpathlist[1]; //获取可供当前版本升级的压缩包 foreach($allpathlist as $k=>$v) { if(strstr($v, 'patch_'.$current_version['pc_release'])) { $key = $k; break; } } $key = $key < 0 ? 9999 : $key; foreach($allpathlist as $k=>$v) { if($k >= $key) { $pathlist[$k] = $v; } } //开始升级 if(!empty($_GET['s'])) { if(empty($_GET['do'])) { showmessage(L('upgradeing'), '?m=upgrade&c=index&a=init&s=1&do=1&cover='.$_GET['cover']); } //检查服务器是否支持zip if(empty($pathlist)) { showmessage(L('upgrade_success'), '?m=upgrade&c=index&a=checkfile'); } //创建缓存文件夹 if(!file_exists(CACHE_PATH.'caches_upgrade')) { @mkdir(CACHE_PATH.'caches_upgrade'); } //根据版本下载zip升级包,解压覆盖 pc_base::load_app_class('pclzip', 'upgrade', 0); foreach($pathlist as $k=>$v) { //远程压缩包地址 $upgradezip_url = $upgrade_path_base.$v; //保存到本地地址 $upgradezip_path = CACHE_PATH.'caches_upgrade'.DIRECTORY_SEPARATOR.$v; //解压路径 $upgradezip_source_path = CACHE_PATH.'caches_upgrade'.DIRECTORY_SEPARATOR.basename($v,".zip"); //下载压缩包 @file_put_contents($upgradezip_path, @file_get_contents($upgradezip_url)); //解压缩 $archive = new PclZip($upgradezip_path); if($archive->extract(PCLZIP_OPT_PATH, $upgradezip_source_path, PCLZIP_OPT_REPLACE_NEWER) == 0) { die("Error : ".$archive->errorInfo(true)); } //拷贝gbk/upload文件夹到根目录 $copy_from = $upgradezip_source_path.DIRECTORY_SEPARATOR.$patch_charset.DIRECTORY_SEPARATOR.'upload'.DIRECTORY_SEPARATOR; $copy_to = PHPCMS_PATH; $this->copyfailnum = 0; $this->copydir($copy_from, $copy_to, $_GET['cover']); //检查文件操作权限,是否复制成功 if($this->copyfailnum > 0) { //如果失败,恢复当前版本 @file_put_contents(CACHE_PATH.'configs'.DIRECTORY_SEPARATOR.'version.php', '<?php return '.var_export($current_version, true).';?>'); showmessage(L('please_check_filepri')); } //执行sql //sql目录地址 $sql_path = CACHE_PATH.'caches_upgrade'.DIRECTORY_SEPARATOR.basename($v,".zip").DIRECTORY_SEPARATOR.$patch_charset.DIRECTORY_SEPARATOR.'upgrade'.DIRECTORY_SEPARATOR.'ext'.DIRECTORY_SEPARATOR; $file_list = glob($sql_path.'*'); if(!empty($file_list)) { foreach ($file_list as $fk=>$fv) { if(in_array(strtolower(substr($fv, -3, 3)), array('php', 'sql'))) { if (strtolower(substr($file_list[$fk], -3, 3)) == 'sql' && $data = file_get_contents($file_list[$fk])) { $model_name = substr(basename($fv), 0, -4); if (!$db = pc_base::load_model($model_name.'_model')) { showmessage($model_name.L('lost'), '?m=upgrade&c=index&a=init&s=1'); } $mysql_server_version = $db->version(); $dbcharset = pc_base::load_config('database','default'); $dbcharset = $dbcharset['charset']; $sqls = explode(';', $data); foreach ($sqls as $sql) { if (empty($sql)) continue; if(mysql_get_server_info > '4.1' && $dbcharset) { $sql = preg_replace("/TYPE=(InnoDB|MyISAM|MEMORY)( DEFAULT CHARSET=[^; ]+)?/", "TYPE=\\1 DEFAULT CHARSET=".$dbcharset,$sql); } $db->query($sql); } } elseif (strtolower(substr($file_list[$fk], -3, 3)) == 'php' && file_exists($file_list[$fk])) { include $file_list[$fk]; //同步菜单语言包 if (strtolower(basename($file_list[$fk])) == 'system_menu.lang.php' && file_exists($file_list[$fk])) { include $file_list[$fk]; $new_lan = $LANG; unset($LANG); $lang = pc_base::load_config('system','lang'); $menu_lan_file = PC_PATH.'languages'.DIRECTORY_SEPARATOR.$lang.DIRECTORY_SEPARATOR.'system_menu.lang.php'; include $menu_lan_file; $original_lan = $LANG; unset($LANG); $diff_lan = array_diff($new_lan, $original_lan); $content = file_get_contents($menu_lan_file); $content = substr($content,0,-2); $data = ''; foreach ($diff_lan as $lk => $l) { $data .= "\$LANG['".$lk."'] = '".$l."';\n\r"; } $data = $content.$data."?>"; file_put_contents($menu_lan_file, $data); } } } } } //读取版本号写入version.php文件 //配置文件地址 $configpath = CACHE_PATH.'caches_upgrade'.DIRECTORY_SEPARATOR.basename($v,".zip").DIRECTORY_SEPARATOR.$patch_charset.DIRECTORY_SEPARATOR.'upgrade'.DIRECTORY_SEPARATOR.'config.php'; if(file_exists($configpath)) { $config_arr = include $configpath; $version_arr = array('pc_version'=>$config_arr['to_version'], 'pc_release'=>$config_arr['to_release']); //版本文件地址 $version_filepath = CACHE_PATH.'configs'.DIRECTORY_SEPARATOR.'version.php'; @file_put_contents($version_filepath, '<?php return '.var_export($version_arr, true).';?>'); } //删除文件 @unlink($upgradezip_path); //删除文件夹 $this->deletedir($upgradezip_source_path); //提示语 $tmp_k = $k + 1; if(!empty($pathlist[$tmp_k])) { $next_update = '<br />'.L('upgradeing').basename($pathlist[$tmp_k],".zip"); } else { $next_update; } //文件校验是否升级成功 showmessage(basename($v,".zip").L('upgrade_success').$next_update, '?m=upgrade&c=index&a=init&s=1&do=1&cover='.$_GET['cover']); } } else { include $this->admin_tpl('upgrade_index'); } } //检查文件md5值 public function checkfile() { if(!empty($_GET['do'])) { $this->md5_arr = array(); $this->_pc_readdir("."); //读取phpcms接口 $current_version = pc_base::load_config('version'); $phpcms_md5 = @file_get_contents($this->_upgrademd5.$current_version['pc_release'].'_'.CHARSET.".php"); $phpcms_md5_arr = json_decode($phpcms_md5, 1); //计算数组差集 $diff = array_diff($phpcms_md5_arr, $this->md5_arr); //丢失文件列表 $lostfile = array(); foreach($phpcms_md5_arr as $k=>$v) { if(!in_array($k, array_keys($this->md5_arr))) { $lostfile[] = $k; unset($diff[$k]); } } //未知文件列表 $unknowfile = array_diff(array_keys($this->md5_arr), array_keys($phpcms_md5_arr)); include $this->admin_tpl('check_file'); } else { showmessage(L('begin_checkfile'), '?m=upgrade&c=index&a=checkfile&do=1&menuid='.$_GET['menuid']); } } private function _pc_readdir($path='') { $dir_arr = explode('/', dirname($path)); if(is_dir($path)) { $handler = opendir($path); while(($filename = @readdir($handler)) !== false) { if(substr($filename, 0, 1) != ".") { $this->_pc_readdir($path.'/'.$filename); } } closedir($handler); } else { if (dirname($path) == '.' || (isset($dir_arr[1]) && in_array($dir_arr[1], $this->_filearr))) { $this->md5_arr[base64_encode($path)] = md5_file($path); } } } public function copydir($dirfrom, $dirto, $cover='') { //如果遇到同名文件无法复制,则直接退出 if(is_file($dirto)){ die(L('have_no_pri').$dirto); } //如果目录不存在,则建立之 if(!file_exists($dirto)){ mkdir($dirto); } $handle = opendir($dirfrom); //打开当前目录 //循环读取文件 while(false !== ($file = readdir($handle))) { if($file != '.' && $file != '..'){ //排除"."和"." //生成源文件名 $filefrom = $dirfrom.DIRECTORY_SEPARATOR.$file; //生成目标文件名 $fileto = $dirto.DIRECTORY_SEPARATOR.$file; if(is_dir($filefrom)){ //如果是子目录,则进行递归操作 $this->copydir($filefrom, $fileto, $cover); } else { //如果是文件,则直接用copy函数复制 if(!empty($cover)) { if(!copy($filefrom, $fileto)) { $this->copyfailnum++; echo L('copy').$filefrom.L('to').$fileto.L('failed')."<br />"; } } else { if(fileext($fileto) == 'html' && file_exists($fileto)) { } else { if(!copy($filefrom, $fileto)) { $this->copyfailnum++; echo L('copy').$filefrom.L('to').$fileto.L('failed')."<br />"; } } } } } } } function deletedir($dirname){ $result = false; if(! is_dir($dirname)){ echo " $dirname is not a dir!"; exit(0); } $handle = opendir($dirname); //打开目录 while(($file = readdir($handle)) !== false) { if($file != '.' && $file != '..'){ //排除"."和"." $dir = $dirname.DIRECTORY_SEPARATOR.$file; //$dir是目录时递归调用deletedir,是文件则直接删除 is_dir($dir) ? $this->deletedir($dir) : unlink($dir); } } closedir($handle); $result = rmdir($dirname) ? true : false; return $result; } }
PHP
<?php // -------------------------------------------------------------------------------- // PhpConcept Library - Zip Module 2.8.2 // -------------------------------------------------------------------------------- // License GNU/LGPL - Vincent Blavet - August 2009 // http://www.phpconcept.net // -------------------------------------------------------------------------------- // // Presentation : // PclZip is a PHP library that manage ZIP archives. // So far tests show that archives generated by PclZip are readable by // WinZip application and other tools. // // Description : // See readme.txt and http://www.phpconcept.net // // Warning : // This library and the associated files are non commercial, non professional // work. // It should not have unexpected results. However if any damage is caused by // this software the author can not be responsible. // The use of this software is at the risk of the user. // // -------------------------------------------------------------------------------- // $Id: pclzip.lib.php,v 1.60 2009/09/30 21:01:04 vblavet Exp $ // -------------------------------------------------------------------------------- // ----- Constants if (!defined('PCLZIP_READ_BLOCK_SIZE')) { define( 'PCLZIP_READ_BLOCK_SIZE', 2048 ); } // ----- File list separator // In version 1.x of PclZip, the separator for file list is a space // (which is not a very smart choice, specifically for windows paths !). // A better separator should be a comma (,). This constant gives you the // abilty to change that. // However notice that changing this value, may have impact on existing // scripts, using space separated filenames. // Recommanded values for compatibility with older versions : //define( 'PCLZIP_SEPARATOR', ' ' ); // Recommanded values for smart separation of filenames. if (!defined('PCLZIP_SEPARATOR')) { define( 'PCLZIP_SEPARATOR', ',' ); } // ----- Error configuration // 0 : PclZip Class integrated error handling // 1 : PclError external library error handling. By enabling this // you must ensure that you have included PclError library. // [2,...] : reserved for futur use if (!defined('PCLZIP_ERROR_EXTERNAL')) { define( 'PCLZIP_ERROR_EXTERNAL', 0 ); } // ----- Optional static temporary directory // By default temporary files are generated in the script current // path. // If defined : // - MUST BE terminated by a '/'. // - MUST be a valid, already created directory // Samples : // define( 'PCLZIP_TEMPORARY_DIR', '/temp/' ); // define( 'PCLZIP_TEMPORARY_DIR', 'C:/Temp/' ); if (!defined('PCLZIP_TEMPORARY_DIR')) { define( 'PCLZIP_TEMPORARY_DIR', '' ); } // ----- Optional threshold ratio for use of temporary files // Pclzip sense the size of the file to add/extract and decide to // use or not temporary file. The algorythm is looking for // memory_limit of PHP and apply a ratio. // threshold = memory_limit * ratio. // Recommended values are under 0.5. Default 0.47. // Samples : // define( 'PCLZIP_TEMPORARY_FILE_RATIO', 0.5 ); if (!defined('PCLZIP_TEMPORARY_FILE_RATIO')) { define( 'PCLZIP_TEMPORARY_FILE_RATIO', 0.47 ); } // -------------------------------------------------------------------------------- // ***** UNDER THIS LINE NOTHING NEEDS TO BE MODIFIED ***** // -------------------------------------------------------------------------------- // ----- Global variables $g_pclzip_version = "2.8.2"; // ----- Error codes // -1 : Unable to open file in binary write mode // -2 : Unable to open file in binary read mode // -3 : Invalid parameters // -4 : File does not exist // -5 : Filename is too long (max. 255) // -6 : Not a valid zip file // -7 : Invalid extracted file size // -8 : Unable to create directory // -9 : Invalid archive extension // -10 : Invalid archive format // -11 : Unable to delete file (unlink) // -12 : Unable to rename file (rename) // -13 : Invalid header checksum // -14 : Invalid archive size define( 'PCLZIP_ERR_USER_ABORTED', 2 ); define( 'PCLZIP_ERR_NO_ERROR', 0 ); define( 'PCLZIP_ERR_WRITE_OPEN_FAIL', -1 ); define( 'PCLZIP_ERR_READ_OPEN_FAIL', -2 ); define( 'PCLZIP_ERR_INVALID_PARAMETER', -3 ); define( 'PCLZIP_ERR_MISSING_FILE', -4 ); define( 'PCLZIP_ERR_FILENAME_TOO_LONG', -5 ); define( 'PCLZIP_ERR_INVALID_ZIP', -6 ); define( 'PCLZIP_ERR_BAD_EXTRACTED_FILE', -7 ); define( 'PCLZIP_ERR_DIR_CREATE_FAIL', -8 ); define( 'PCLZIP_ERR_BAD_EXTENSION', -9 ); define( 'PCLZIP_ERR_BAD_FORMAT', -10 ); define( 'PCLZIP_ERR_DELETE_FILE_FAIL', -11 ); define( 'PCLZIP_ERR_RENAME_FILE_FAIL', -12 ); define( 'PCLZIP_ERR_BAD_CHECKSUM', -13 ); define( 'PCLZIP_ERR_INVALID_ARCHIVE_ZIP', -14 ); define( 'PCLZIP_ERR_MISSING_OPTION_VALUE', -15 ); define( 'PCLZIP_ERR_INVALID_OPTION_VALUE', -16 ); define( 'PCLZIP_ERR_ALREADY_A_DIRECTORY', -17 ); define( 'PCLZIP_ERR_UNSUPPORTED_COMPRESSION', -18 ); define( 'PCLZIP_ERR_UNSUPPORTED_ENCRYPTION', -19 ); define( 'PCLZIP_ERR_INVALID_ATTRIBUTE_VALUE', -20 ); define( 'PCLZIP_ERR_DIRECTORY_RESTRICTION', -21 ); // ----- Options values define( 'PCLZIP_OPT_PATH', 77001 ); define( 'PCLZIP_OPT_ADD_PATH', 77002 ); define( 'PCLZIP_OPT_REMOVE_PATH', 77003 ); define( 'PCLZIP_OPT_REMOVE_ALL_PATH', 77004 ); define( 'PCLZIP_OPT_SET_CHMOD', 77005 ); define( 'PCLZIP_OPT_EXTRACT_AS_STRING', 77006 ); define( 'PCLZIP_OPT_NO_COMPRESSION', 77007 ); define( 'PCLZIP_OPT_BY_NAME', 77008 ); define( 'PCLZIP_OPT_BY_INDEX', 77009 ); define( 'PCLZIP_OPT_BY_EREG', 77010 ); define( 'PCLZIP_OPT_BY_PREG', 77011 ); define( 'PCLZIP_OPT_COMMENT', 77012 ); define( 'PCLZIP_OPT_ADD_COMMENT', 77013 ); define( 'PCLZIP_OPT_PREPEND_COMMENT', 77014 ); define( 'PCLZIP_OPT_EXTRACT_IN_OUTPUT', 77015 ); define( 'PCLZIP_OPT_REPLACE_NEWER', 77016 ); define( 'PCLZIP_OPT_STOP_ON_ERROR', 77017 ); // Having big trouble with crypt. Need to multiply 2 long int // which is not correctly supported by PHP ... //define( 'PCLZIP_OPT_CRYPT', 77018 ); define( 'PCLZIP_OPT_EXTRACT_DIR_RESTRICTION', 77019 ); define( 'PCLZIP_OPT_TEMP_FILE_THRESHOLD', 77020 ); define( 'PCLZIP_OPT_ADD_TEMP_FILE_THRESHOLD', 77020 ); // alias define( 'PCLZIP_OPT_TEMP_FILE_ON', 77021 ); define( 'PCLZIP_OPT_ADD_TEMP_FILE_ON', 77021 ); // alias define( 'PCLZIP_OPT_TEMP_FILE_OFF', 77022 ); define( 'PCLZIP_OPT_ADD_TEMP_FILE_OFF', 77022 ); // alias // ----- File description attributes define( 'PCLZIP_ATT_FILE_NAME', 79001 ); define( 'PCLZIP_ATT_FILE_NEW_SHORT_NAME', 79002 ); define( 'PCLZIP_ATT_FILE_NEW_FULL_NAME', 79003 ); define( 'PCLZIP_ATT_FILE_MTIME', 79004 ); define( 'PCLZIP_ATT_FILE_CONTENT', 79005 ); define( 'PCLZIP_ATT_FILE_COMMENT', 79006 ); // ----- Call backs values define( 'PCLZIP_CB_PRE_EXTRACT', 78001 ); define( 'PCLZIP_CB_POST_EXTRACT', 78002 ); define( 'PCLZIP_CB_PRE_ADD', 78003 ); define( 'PCLZIP_CB_POST_ADD', 78004 ); /* For futur use define( 'PCLZIP_CB_PRE_LIST', 78005 ); define( 'PCLZIP_CB_POST_LIST', 78006 ); define( 'PCLZIP_CB_PRE_DELETE', 78007 ); define( 'PCLZIP_CB_POST_DELETE', 78008 ); */ // -------------------------------------------------------------------------------- // Class : PclZip // Description : // PclZip is the class that represent a Zip archive. // The public methods allow the manipulation of the archive. // Attributes : // Attributes must not be accessed directly. // Methods : // PclZip() : Object creator // create() : Creates the Zip archive // listContent() : List the content of the Zip archive // extract() : Extract the content of the archive // properties() : List the properties of the archive // -------------------------------------------------------------------------------- class PclZip { // ----- Filename of the zip file var $zipname = ''; // ----- File descriptor of the zip file var $zip_fd = 0; // ----- Internal error handling var $error_code = 1; var $error_string = ''; // ----- Current status of the magic_quotes_runtime // This value store the php configuration for magic_quotes // The class can then disable the magic_quotes and reset it after var $magic_quotes_status; // -------------------------------------------------------------------------------- // Function : PclZip() // Description : // Creates a PclZip object and set the name of the associated Zip archive // filename. // Note that no real action is taken, if the archive does not exist it is not // created. Use create() for that. // -------------------------------------------------------------------------------- function PclZip($p_zipname) { // ----- Tests the zlib if (!function_exists('gzopen')) { die('Abort '.basename(__FILE__).' : Missing zlib extensions'); } // ----- Set the attributes $this->zipname = $p_zipname; $this->zip_fd = 0; $this->magic_quotes_status = -1; // ----- Return return; } // -------------------------------------------------------------------------------- // -------------------------------------------------------------------------------- // Function : // create($p_filelist, $p_add_dir="", $p_remove_dir="") // create($p_filelist, $p_option, $p_option_value, ...) // Description : // This method supports two different synopsis. The first one is historical. // This method creates a Zip Archive. The Zip file is created in the // filesystem. The files and directories indicated in $p_filelist // are added in the archive. See the parameters description for the // supported format of $p_filelist. // When a directory is in the list, the directory and its content is added // in the archive. // In this synopsis, the function takes an optional variable list of // options. See bellow the supported options. // Parameters : // $p_filelist : An array containing file or directory names, or // a string containing one filename or one directory name, or // a string containing a list of filenames and/or directory // names separated by spaces. // $p_add_dir : A path to add before the real path of the archived file, // in order to have it memorized in the archive. // $p_remove_dir : A path to remove from the real path of the file to archive, // in order to have a shorter path memorized in the archive. // When $p_add_dir and $p_remove_dir are set, $p_remove_dir // is removed first, before $p_add_dir is added. // Options : // PCLZIP_OPT_ADD_PATH : // PCLZIP_OPT_REMOVE_PATH : // PCLZIP_OPT_REMOVE_ALL_PATH : // PCLZIP_OPT_COMMENT : // PCLZIP_CB_PRE_ADD : // PCLZIP_CB_POST_ADD : // Return Values : // 0 on failure, // The list of the added files, with a status of the add action. // (see PclZip::listContent() for list entry format) // -------------------------------------------------------------------------------- function create($p_filelist) { $v_result=1; // ----- Reset the error handler $this->privErrorReset(); // ----- Set default values $v_options = array(); $v_options[PCLZIP_OPT_NO_COMPRESSION] = FALSE; // ----- Look for variable options arguments $v_size = func_num_args(); // ----- Look for arguments if ($v_size > 1) { // ----- Get the arguments $v_arg_list = func_get_args(); // ----- Remove from the options list the first argument array_shift($v_arg_list); $v_size--; // ----- Look for first arg if ((is_integer($v_arg_list[0])) && ($v_arg_list[0] > 77000)) { // ----- Parse the options $v_result = $this->privParseOptions($v_arg_list, $v_size, $v_options, array (PCLZIP_OPT_REMOVE_PATH => 'optional', PCLZIP_OPT_REMOVE_ALL_PATH => 'optional', PCLZIP_OPT_ADD_PATH => 'optional', PCLZIP_CB_PRE_ADD => 'optional', PCLZIP_CB_POST_ADD => 'optional', PCLZIP_OPT_NO_COMPRESSION => 'optional', PCLZIP_OPT_COMMENT => 'optional', PCLZIP_OPT_TEMP_FILE_THRESHOLD => 'optional', PCLZIP_OPT_TEMP_FILE_ON => 'optional', PCLZIP_OPT_TEMP_FILE_OFF => 'optional' //, PCLZIP_OPT_CRYPT => 'optional' )); if ($v_result != 1) { return 0; } } // ----- Look for 2 args // Here we need to support the first historic synopsis of the // method. else { // ----- Get the first argument $v_options[PCLZIP_OPT_ADD_PATH] = $v_arg_list[0]; // ----- Look for the optional second argument if ($v_size == 2) { $v_options[PCLZIP_OPT_REMOVE_PATH] = $v_arg_list[1]; } else if ($v_size > 2) { PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Invalid number / type of arguments"); return 0; } } } // ----- Look for default option values $this->privOptionDefaultThreshold($v_options); // ----- Init $v_string_list = array(); $v_att_list = array(); $v_filedescr_list = array(); $p_result_list = array(); // ----- Look if the $p_filelist is really an array if (is_array($p_filelist)) { // ----- Look if the first element is also an array // This will mean that this is a file description entry if (isset($p_filelist[0]) && is_array($p_filelist[0])) { $v_att_list = $p_filelist; } // ----- The list is a list of string names else { $v_string_list = $p_filelist; } } // ----- Look if the $p_filelist is a string else if (is_string($p_filelist)) { // ----- Create a list from the string $v_string_list = explode(PCLZIP_SEPARATOR, $p_filelist); } // ----- Invalid variable type for $p_filelist else { PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Invalid variable type p_filelist"); return 0; } // ----- Reformat the string list if (sizeof($v_string_list) != 0) { foreach ($v_string_list as $v_string) { if ($v_string != '') { $v_att_list[][PCLZIP_ATT_FILE_NAME] = $v_string; } else { } } } // ----- For each file in the list check the attributes $v_supported_attributes = array ( PCLZIP_ATT_FILE_NAME => 'mandatory' ,PCLZIP_ATT_FILE_NEW_SHORT_NAME => 'optional' ,PCLZIP_ATT_FILE_NEW_FULL_NAME => 'optional' ,PCLZIP_ATT_FILE_MTIME => 'optional' ,PCLZIP_ATT_FILE_CONTENT => 'optional' ,PCLZIP_ATT_FILE_COMMENT => 'optional' ); foreach ($v_att_list as $v_entry) { $v_result = $this->privFileDescrParseAtt($v_entry, $v_filedescr_list[], $v_options, $v_supported_attributes); if ($v_result != 1) { return 0; } } // ----- Expand the filelist (expand directories) $v_result = $this->privFileDescrExpand($v_filedescr_list, $v_options); if ($v_result != 1) { return 0; } // ----- Call the create fct $v_result = $this->privCreate($v_filedescr_list, $p_result_list, $v_options); if ($v_result != 1) { return 0; } // ----- Return return $p_result_list; } // -------------------------------------------------------------------------------- // -------------------------------------------------------------------------------- // Function : // add($p_filelist, $p_add_dir="", $p_remove_dir="") // add($p_filelist, $p_option, $p_option_value, ...) // Description : // This method supports two synopsis. The first one is historical. // This methods add the list of files in an existing archive. // If a file with the same name already exists, it is added at the end of the // archive, the first one is still present. // If the archive does not exist, it is created. // Parameters : // $p_filelist : An array containing file or directory names, or // a string containing one filename or one directory name, or // a string containing a list of filenames and/or directory // names separated by spaces. // $p_add_dir : A path to add before the real path of the archived file, // in order to have it memorized in the archive. // $p_remove_dir : A path to remove from the real path of the file to archive, // in order to have a shorter path memorized in the archive. // When $p_add_dir and $p_remove_dir are set, $p_remove_dir // is removed first, before $p_add_dir is added. // Options : // PCLZIP_OPT_ADD_PATH : // PCLZIP_OPT_REMOVE_PATH : // PCLZIP_OPT_REMOVE_ALL_PATH : // PCLZIP_OPT_COMMENT : // PCLZIP_OPT_ADD_COMMENT : // PCLZIP_OPT_PREPEND_COMMENT : // PCLZIP_CB_PRE_ADD : // PCLZIP_CB_POST_ADD : // Return Values : // 0 on failure, // The list of the added files, with a status of the add action. // (see PclZip::listContent() for list entry format) // -------------------------------------------------------------------------------- function add($p_filelist) { $v_result=1; // ----- Reset the error handler $this->privErrorReset(); // ----- Set default values $v_options = array(); $v_options[PCLZIP_OPT_NO_COMPRESSION] = FALSE; // ----- Look for variable options arguments $v_size = func_num_args(); // ----- Look for arguments if ($v_size > 1) { // ----- Get the arguments $v_arg_list = func_get_args(); // ----- Remove form the options list the first argument array_shift($v_arg_list); $v_size--; // ----- Look for first arg if ((is_integer($v_arg_list[0])) && ($v_arg_list[0] > 77000)) { // ----- Parse the options $v_result = $this->privParseOptions($v_arg_list, $v_size, $v_options, array (PCLZIP_OPT_REMOVE_PATH => 'optional', PCLZIP_OPT_REMOVE_ALL_PATH => 'optional', PCLZIP_OPT_ADD_PATH => 'optional', PCLZIP_CB_PRE_ADD => 'optional', PCLZIP_CB_POST_ADD => 'optional', PCLZIP_OPT_NO_COMPRESSION => 'optional', PCLZIP_OPT_COMMENT => 'optional', PCLZIP_OPT_ADD_COMMENT => 'optional', PCLZIP_OPT_PREPEND_COMMENT => 'optional', PCLZIP_OPT_TEMP_FILE_THRESHOLD => 'optional', PCLZIP_OPT_TEMP_FILE_ON => 'optional', PCLZIP_OPT_TEMP_FILE_OFF => 'optional' //, PCLZIP_OPT_CRYPT => 'optional' )); if ($v_result != 1) { return 0; } } // ----- Look for 2 args // Here we need to support the first historic synopsis of the // method. else { // ----- Get the first argument $v_options[PCLZIP_OPT_ADD_PATH] = $v_add_path = $v_arg_list[0]; // ----- Look for the optional second argument if ($v_size == 2) { $v_options[PCLZIP_OPT_REMOVE_PATH] = $v_arg_list[1]; } else if ($v_size > 2) { // ----- Error log PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Invalid number / type of arguments"); // ----- Return return 0; } } } // ----- Look for default option values $this->privOptionDefaultThreshold($v_options); // ----- Init $v_string_list = array(); $v_att_list = array(); $v_filedescr_list = array(); $p_result_list = array(); // ----- Look if the $p_filelist is really an array if (is_array($p_filelist)) { // ----- Look if the first element is also an array // This will mean that this is a file description entry if (isset($p_filelist[0]) && is_array($p_filelist[0])) { $v_att_list = $p_filelist; } // ----- The list is a list of string names else { $v_string_list = $p_filelist; } } // ----- Look if the $p_filelist is a string else if (is_string($p_filelist)) { // ----- Create a list from the string $v_string_list = explode(PCLZIP_SEPARATOR, $p_filelist); } // ----- Invalid variable type for $p_filelist else { PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Invalid variable type '".gettype($p_filelist)."' for p_filelist"); return 0; } // ----- Reformat the string list if (sizeof($v_string_list) != 0) { foreach ($v_string_list as $v_string) { $v_att_list[][PCLZIP_ATT_FILE_NAME] = $v_string; } } // ----- For each file in the list check the attributes $v_supported_attributes = array ( PCLZIP_ATT_FILE_NAME => 'mandatory' ,PCLZIP_ATT_FILE_NEW_SHORT_NAME => 'optional' ,PCLZIP_ATT_FILE_NEW_FULL_NAME => 'optional' ,PCLZIP_ATT_FILE_MTIME => 'optional' ,PCLZIP_ATT_FILE_CONTENT => 'optional' ,PCLZIP_ATT_FILE_COMMENT => 'optional' ); foreach ($v_att_list as $v_entry) { $v_result = $this->privFileDescrParseAtt($v_entry, $v_filedescr_list[], $v_options, $v_supported_attributes); if ($v_result != 1) { return 0; } } // ----- Expand the filelist (expand directories) $v_result = $this->privFileDescrExpand($v_filedescr_list, $v_options); if ($v_result != 1) { return 0; } // ----- Call the create fct $v_result = $this->privAdd($v_filedescr_list, $p_result_list, $v_options); if ($v_result != 1) { return 0; } // ----- Return return $p_result_list; } // -------------------------------------------------------------------------------- // -------------------------------------------------------------------------------- // Function : listContent() // Description : // This public method, gives the list of the files and directories, with their // properties. // The properties of each entries in the list are (used also in other functions) : // filename : Name of the file. For a create or add action it is the filename // given by the user. For an extract function it is the filename // of the extracted file. // stored_filename : Name of the file / directory stored in the archive. // size : Size of the stored file. // compressed_size : Size of the file's data compressed in the archive // (without the headers overhead) // mtime : Last known modification date of the file (UNIX timestamp) // comment : Comment associated with the file // folder : true | false // index : index of the file in the archive // status : status of the action (depending of the action) : // Values are : // ok : OK ! // filtered : the file / dir is not extracted (filtered by user) // already_a_directory : the file can not be extracted because a // directory with the same name already exists // write_protected : the file can not be extracted because a file // with the same name already exists and is // write protected // newer_exist : the file was not extracted because a newer file exists // path_creation_fail : the file is not extracted because the folder // does not exist and can not be created // write_error : the file was not extracted because there was a // error while writing the file // read_error : the file was not extracted because there was a error // while reading the file // invalid_header : the file was not extracted because of an archive // format error (bad file header) // Note that each time a method can continue operating when there // is an action error on a file, the error is only logged in the file status. // Return Values : // 0 on an unrecoverable failure, // The list of the files in the archive. // -------------------------------------------------------------------------------- function listContent() { $v_result=1; // ----- Reset the error handler $this->privErrorReset(); // ----- Check archive if (!$this->privCheckFormat()) { return(0); } // ----- Call the extracting fct $p_list = array(); if (($v_result = $this->privList($p_list)) != 1) { unset($p_list); return(0); } // ----- Return return $p_list; } // -------------------------------------------------------------------------------- // -------------------------------------------------------------------------------- // Function : // extract($p_path="./", $p_remove_path="") // extract([$p_option, $p_option_value, ...]) // Description : // This method supports two synopsis. The first one is historical. // This method extract all the files / directories from the archive to the // folder indicated in $p_path. // If you want to ignore the 'root' part of path of the memorized files // you can indicate this in the optional $p_remove_path parameter. // By default, if a newer file with the same name already exists, the // file is not extracted. // // If both PCLZIP_OPT_PATH and PCLZIP_OPT_ADD_PATH aoptions // are used, the path indicated in PCLZIP_OPT_ADD_PATH is append // at the end of the path value of PCLZIP_OPT_PATH. // Parameters : // $p_path : Path where the files and directories are to be extracted // $p_remove_path : First part ('root' part) of the memorized path // (if any similar) to remove while extracting. // Options : // PCLZIP_OPT_PATH : // PCLZIP_OPT_ADD_PATH : // PCLZIP_OPT_REMOVE_PATH : // PCLZIP_OPT_REMOVE_ALL_PATH : // PCLZIP_CB_PRE_EXTRACT : // PCLZIP_CB_POST_EXTRACT : // Return Values : // 0 or a negative value on failure, // The list of the extracted files, with a status of the action. // (see PclZip::listContent() for list entry format) // -------------------------------------------------------------------------------- function extract() { $v_result=1; // ----- Reset the error handler $this->privErrorReset(); // ----- Check archive if (!$this->privCheckFormat()) { return(0); } // ----- Set default values $v_options = array(); // $v_path = "./"; $v_path = ''; $v_remove_path = ""; $v_remove_all_path = false; // ----- Look for variable options arguments $v_size = func_num_args(); // ----- Default values for option $v_options[PCLZIP_OPT_EXTRACT_AS_STRING] = FALSE; // ----- Look for arguments if ($v_size > 0) { // ----- Get the arguments $v_arg_list = func_get_args(); // ----- Look for first arg if ((is_integer($v_arg_list[0])) && ($v_arg_list[0] > 77000)) { // ----- Parse the options $v_result = $this->privParseOptions($v_arg_list, $v_size, $v_options, array (PCLZIP_OPT_PATH => 'optional', PCLZIP_OPT_REMOVE_PATH => 'optional', PCLZIP_OPT_REMOVE_ALL_PATH => 'optional', PCLZIP_OPT_ADD_PATH => 'optional', PCLZIP_CB_PRE_EXTRACT => 'optional', PCLZIP_CB_POST_EXTRACT => 'optional', PCLZIP_OPT_SET_CHMOD => 'optional', PCLZIP_OPT_BY_NAME => 'optional', PCLZIP_OPT_BY_EREG => 'optional', PCLZIP_OPT_BY_PREG => 'optional', PCLZIP_OPT_BY_INDEX => 'optional', PCLZIP_OPT_EXTRACT_AS_STRING => 'optional', PCLZIP_OPT_EXTRACT_IN_OUTPUT => 'optional', PCLZIP_OPT_REPLACE_NEWER => 'optional' ,PCLZIP_OPT_STOP_ON_ERROR => 'optional' ,PCLZIP_OPT_EXTRACT_DIR_RESTRICTION => 'optional', PCLZIP_OPT_TEMP_FILE_THRESHOLD => 'optional', PCLZIP_OPT_TEMP_FILE_ON => 'optional', PCLZIP_OPT_TEMP_FILE_OFF => 'optional' )); if ($v_result != 1) { return 0; } // ----- Set the arguments if (isset($v_options[PCLZIP_OPT_PATH])) { $v_path = $v_options[PCLZIP_OPT_PATH]; } if (isset($v_options[PCLZIP_OPT_REMOVE_PATH])) { $v_remove_path = $v_options[PCLZIP_OPT_REMOVE_PATH]; } if (isset($v_options[PCLZIP_OPT_REMOVE_ALL_PATH])) { $v_remove_all_path = $v_options[PCLZIP_OPT_REMOVE_ALL_PATH]; } if (isset($v_options[PCLZIP_OPT_ADD_PATH])) { // ----- Check for '/' in last path char if ((strlen($v_path) > 0) && (substr($v_path, -1) != '/')) { $v_path .= '/'; } $v_path .= $v_options[PCLZIP_OPT_ADD_PATH]; } } // ----- Look for 2 args // Here we need to support the first historic synopsis of the // method. else { // ----- Get the first argument $v_path = $v_arg_list[0]; // ----- Look for the optional second argument if ($v_size == 2) { $v_remove_path = $v_arg_list[1]; } else if ($v_size > 2) { // ----- Error log PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Invalid number / type of arguments"); // ----- Return return 0; } } } // ----- Look for default option values $this->privOptionDefaultThreshold($v_options); // ----- Trace // ----- Call the extracting fct $p_list = array(); $v_result = $this->privExtractByRule($p_list, $v_path, $v_remove_path, $v_remove_all_path, $v_options); if ($v_result < 1) { unset($p_list); return(0); } // ----- Return return $p_list; } // -------------------------------------------------------------------------------- // -------------------------------------------------------------------------------- // Function : // extractByIndex($p_index, $p_path="./", $p_remove_path="") // extractByIndex($p_index, [$p_option, $p_option_value, ...]) // Description : // This method supports two synopsis. The first one is historical. // This method is doing a partial extract of the archive. // The extracted files or folders are identified by their index in the // archive (from 0 to n). // Note that if the index identify a folder, only the folder entry is // extracted, not all the files included in the archive. // Parameters : // $p_index : A single index (integer) or a string of indexes of files to // extract. The form of the string is "0,4-6,8-12" with only numbers // and '-' for range or ',' to separate ranges. No spaces or ';' // are allowed. // $p_path : Path where the files and directories are to be extracted // $p_remove_path : First part ('root' part) of the memorized path // (if any similar) to remove while extracting. // Options : // PCLZIP_OPT_PATH : // PCLZIP_OPT_ADD_PATH : // PCLZIP_OPT_REMOVE_PATH : // PCLZIP_OPT_REMOVE_ALL_PATH : // PCLZIP_OPT_EXTRACT_AS_STRING : The files are extracted as strings and // not as files. // The resulting content is in a new field 'content' in the file // structure. // This option must be used alone (any other options are ignored). // PCLZIP_CB_PRE_EXTRACT : // PCLZIP_CB_POST_EXTRACT : // Return Values : // 0 on failure, // The list of the extracted files, with a status of the action. // (see PclZip::listContent() for list entry format) // -------------------------------------------------------------------------------- //function extractByIndex($p_index, options...) function extractByIndex($p_index) { $v_result=1; // ----- Reset the error handler $this->privErrorReset(); // ----- Check archive if (!$this->privCheckFormat()) { return(0); } // ----- Set default values $v_options = array(); // $v_path = "./"; $v_path = ''; $v_remove_path = ""; $v_remove_all_path = false; // ----- Look for variable options arguments $v_size = func_num_args(); // ----- Default values for option $v_options[PCLZIP_OPT_EXTRACT_AS_STRING] = FALSE; // ----- Look for arguments if ($v_size > 1) { // ----- Get the arguments $v_arg_list = func_get_args(); // ----- Remove form the options list the first argument array_shift($v_arg_list); $v_size--; // ----- Look for first arg if ((is_integer($v_arg_list[0])) && ($v_arg_list[0] > 77000)) { // ----- Parse the options $v_result = $this->privParseOptions($v_arg_list, $v_size, $v_options, array (PCLZIP_OPT_PATH => 'optional', PCLZIP_OPT_REMOVE_PATH => 'optional', PCLZIP_OPT_REMOVE_ALL_PATH => 'optional', PCLZIP_OPT_EXTRACT_AS_STRING => 'optional', PCLZIP_OPT_ADD_PATH => 'optional', PCLZIP_CB_PRE_EXTRACT => 'optional', PCLZIP_CB_POST_EXTRACT => 'optional', PCLZIP_OPT_SET_CHMOD => 'optional', PCLZIP_OPT_REPLACE_NEWER => 'optional' ,PCLZIP_OPT_STOP_ON_ERROR => 'optional' ,PCLZIP_OPT_EXTRACT_DIR_RESTRICTION => 'optional', PCLZIP_OPT_TEMP_FILE_THRESHOLD => 'optional', PCLZIP_OPT_TEMP_FILE_ON => 'optional', PCLZIP_OPT_TEMP_FILE_OFF => 'optional' )); if ($v_result != 1) { return 0; } // ----- Set the arguments if (isset($v_options[PCLZIP_OPT_PATH])) { $v_path = $v_options[PCLZIP_OPT_PATH]; } if (isset($v_options[PCLZIP_OPT_REMOVE_PATH])) { $v_remove_path = $v_options[PCLZIP_OPT_REMOVE_PATH]; } if (isset($v_options[PCLZIP_OPT_REMOVE_ALL_PATH])) { $v_remove_all_path = $v_options[PCLZIP_OPT_REMOVE_ALL_PATH]; } if (isset($v_options[PCLZIP_OPT_ADD_PATH])) { // ----- Check for '/' in last path char if ((strlen($v_path) > 0) && (substr($v_path, -1) != '/')) { $v_path .= '/'; } $v_path .= $v_options[PCLZIP_OPT_ADD_PATH]; } if (!isset($v_options[PCLZIP_OPT_EXTRACT_AS_STRING])) { $v_options[PCLZIP_OPT_EXTRACT_AS_STRING] = FALSE; } else { } } // ----- Look for 2 args // Here we need to support the first historic synopsis of the // method. else { // ----- Get the first argument $v_path = $v_arg_list[0]; // ----- Look for the optional second argument if ($v_size == 2) { $v_remove_path = $v_arg_list[1]; } else if ($v_size > 2) { // ----- Error log PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Invalid number / type of arguments"); // ----- Return return 0; } } } // ----- Trace // ----- Trick // Here I want to reuse extractByRule(), so I need to parse the $p_index // with privParseOptions() $v_arg_trick = array (PCLZIP_OPT_BY_INDEX, $p_index); $v_options_trick = array(); $v_result = $this->privParseOptions($v_arg_trick, sizeof($v_arg_trick), $v_options_trick, array (PCLZIP_OPT_BY_INDEX => 'optional' )); if ($v_result != 1) { return 0; } $v_options[PCLZIP_OPT_BY_INDEX] = $v_options_trick[PCLZIP_OPT_BY_INDEX]; // ----- Look for default option values $this->privOptionDefaultThreshold($v_options); // ----- Call the extracting fct if (($v_result = $this->privExtractByRule($p_list, $v_path, $v_remove_path, $v_remove_all_path, $v_options)) < 1) { return(0); } // ----- Return return $p_list; } // -------------------------------------------------------------------------------- // -------------------------------------------------------------------------------- // Function : // delete([$p_option, $p_option_value, ...]) // Description : // This method removes files from the archive. // If no parameters are given, then all the archive is emptied. // Parameters : // None or optional arguments. // Options : // PCLZIP_OPT_BY_INDEX : // PCLZIP_OPT_BY_NAME : // PCLZIP_OPT_BY_EREG : // PCLZIP_OPT_BY_PREG : // Return Values : // 0 on failure, // The list of the files which are still present in the archive. // (see PclZip::listContent() for list entry format) // -------------------------------------------------------------------------------- function delete() { $v_result=1; // ----- Reset the error handler $this->privErrorReset(); // ----- Check archive if (!$this->privCheckFormat()) { return(0); } // ----- Set default values $v_options = array(); // ----- Look for variable options arguments $v_size = func_num_args(); // ----- Look for arguments if ($v_size > 0) { // ----- Get the arguments $v_arg_list = func_get_args(); // ----- Parse the options $v_result = $this->privParseOptions($v_arg_list, $v_size, $v_options, array (PCLZIP_OPT_BY_NAME => 'optional', PCLZIP_OPT_BY_EREG => 'optional', PCLZIP_OPT_BY_PREG => 'optional', PCLZIP_OPT_BY_INDEX => 'optional' )); if ($v_result != 1) { return 0; } } // ----- Magic quotes trick $this->privDisableMagicQuotes(); // ----- Call the delete fct $v_list = array(); if (($v_result = $this->privDeleteByRule($v_list, $v_options)) != 1) { $this->privSwapBackMagicQuotes(); unset($v_list); return(0); } // ----- Magic quotes trick $this->privSwapBackMagicQuotes(); // ----- Return return $v_list; } // -------------------------------------------------------------------------------- // -------------------------------------------------------------------------------- // Function : deleteByIndex() // Description : // ***** Deprecated ***** // delete(PCLZIP_OPT_BY_INDEX, $p_index) should be prefered. // -------------------------------------------------------------------------------- function deleteByIndex($p_index) { $p_list = $this->delete(PCLZIP_OPT_BY_INDEX, $p_index); // ----- Return return $p_list; } // -------------------------------------------------------------------------------- // -------------------------------------------------------------------------------- // Function : properties() // Description : // This method gives the properties of the archive. // The properties are : // nb : Number of files in the archive // comment : Comment associated with the archive file // status : not_exist, ok // Parameters : // None // Return Values : // 0 on failure, // An array with the archive properties. // -------------------------------------------------------------------------------- function properties() { // ----- Reset the error handler $this->privErrorReset(); // ----- Magic quotes trick $this->privDisableMagicQuotes(); // ----- Check archive if (!$this->privCheckFormat()) { $this->privSwapBackMagicQuotes(); return(0); } // ----- Default properties $v_prop = array(); $v_prop['comment'] = ''; $v_prop['nb'] = 0; $v_prop['status'] = 'not_exist'; // ----- Look if file exists if (@is_file($this->zipname)) { // ----- Open the zip file if (($this->zip_fd = @fopen($this->zipname, 'rb')) == 0) { $this->privSwapBackMagicQuotes(); // ----- Error log PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, 'Unable to open archive \''.$this->zipname.'\' in binary read mode'); // ----- Return return 0; } // ----- Read the central directory informations $v_central_dir = array(); if (($v_result = $this->privReadEndCentralDir($v_central_dir)) != 1) { $this->privSwapBackMagicQuotes(); return 0; } // ----- Close the zip file $this->privCloseFd(); // ----- Set the user attributes $v_prop['comment'] = $v_central_dir['comment']; $v_prop['nb'] = $v_central_dir['entries']; $v_prop['status'] = 'ok'; } // ----- Magic quotes trick $this->privSwapBackMagicQuotes(); // ----- Return return $v_prop; } // -------------------------------------------------------------------------------- // -------------------------------------------------------------------------------- // Function : duplicate() // Description : // This method creates an archive by copying the content of an other one. If // the archive already exist, it is replaced by the new one without any warning. // Parameters : // $p_archive : The filename of a valid archive, or // a valid PclZip object. // Return Values : // 1 on success. // 0 or a negative value on error (error code). // -------------------------------------------------------------------------------- function duplicate($p_archive) { $v_result = 1; // ----- Reset the error handler $this->privErrorReset(); // ----- Look if the $p_archive is a PclZip object if ((is_object($p_archive)) && (get_class($p_archive) == 'pclzip')) { // ----- Duplicate the archive $v_result = $this->privDuplicate($p_archive->zipname); } // ----- Look if the $p_archive is a string (so a filename) else if (is_string($p_archive)) { // ----- Check that $p_archive is a valid zip file // TBC : Should also check the archive format if (!is_file($p_archive)) { // ----- Error log PclZip::privErrorLog(PCLZIP_ERR_MISSING_FILE, "No file with filename '".$p_archive."'"); $v_result = PCLZIP_ERR_MISSING_FILE; } else { // ----- Duplicate the archive $v_result = $this->privDuplicate($p_archive); } } // ----- Invalid variable else { // ----- Error log PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Invalid variable type p_archive_to_add"); $v_result = PCLZIP_ERR_INVALID_PARAMETER; } // ----- Return return $v_result; } // -------------------------------------------------------------------------------- // -------------------------------------------------------------------------------- // Function : merge() // Description : // This method merge the $p_archive_to_add archive at the end of the current // one ($this). // If the archive ($this) does not exist, the merge becomes a duplicate. // If the $p_archive_to_add archive does not exist, the merge is a success. // Parameters : // $p_archive_to_add : It can be directly the filename of a valid zip archive, // or a PclZip object archive. // Return Values : // 1 on success, // 0 or negative values on error (see below). // -------------------------------------------------------------------------------- function merge($p_archive_to_add) { $v_result = 1; // ----- Reset the error handler $this->privErrorReset(); // ----- Check archive if (!$this->privCheckFormat()) { return(0); } // ----- Look if the $p_archive_to_add is a PclZip object if ((is_object($p_archive_to_add)) && (get_class($p_archive_to_add) == 'pclzip')) { // ----- Merge the archive $v_result = $this->privMerge($p_archive_to_add); } // ----- Look if the $p_archive_to_add is a string (so a filename) else if (is_string($p_archive_to_add)) { // ----- Create a temporary archive $v_object_archive = new PclZip($p_archive_to_add); // ----- Merge the archive $v_result = $this->privMerge($v_object_archive); } // ----- Invalid variable else { // ----- Error log PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Invalid variable type p_archive_to_add"); $v_result = PCLZIP_ERR_INVALID_PARAMETER; } // ----- Return return $v_result; } // -------------------------------------------------------------------------------- // -------------------------------------------------------------------------------- // Function : errorCode() // Description : // Parameters : // -------------------------------------------------------------------------------- function errorCode() { if (PCLZIP_ERROR_EXTERNAL == 1) { return(PclErrorCode()); } else { return($this->error_code); } } // -------------------------------------------------------------------------------- // -------------------------------------------------------------------------------- // Function : errorName() // Description : // Parameters : // -------------------------------------------------------------------------------- function errorName($p_with_code=false) { $v_name = array ( PCLZIP_ERR_NO_ERROR => 'PCLZIP_ERR_NO_ERROR', PCLZIP_ERR_WRITE_OPEN_FAIL => 'PCLZIP_ERR_WRITE_OPEN_FAIL', PCLZIP_ERR_READ_OPEN_FAIL => 'PCLZIP_ERR_READ_OPEN_FAIL', PCLZIP_ERR_INVALID_PARAMETER => 'PCLZIP_ERR_INVALID_PARAMETER', PCLZIP_ERR_MISSING_FILE => 'PCLZIP_ERR_MISSING_FILE', PCLZIP_ERR_FILENAME_TOO_LONG => 'PCLZIP_ERR_FILENAME_TOO_LONG', PCLZIP_ERR_INVALID_ZIP => 'PCLZIP_ERR_INVALID_ZIP', PCLZIP_ERR_BAD_EXTRACTED_FILE => 'PCLZIP_ERR_BAD_EXTRACTED_FILE', PCLZIP_ERR_DIR_CREATE_FAIL => 'PCLZIP_ERR_DIR_CREATE_FAIL', PCLZIP_ERR_BAD_EXTENSION => 'PCLZIP_ERR_BAD_EXTENSION', PCLZIP_ERR_BAD_FORMAT => 'PCLZIP_ERR_BAD_FORMAT', PCLZIP_ERR_DELETE_FILE_FAIL => 'PCLZIP_ERR_DELETE_FILE_FAIL', PCLZIP_ERR_RENAME_FILE_FAIL => 'PCLZIP_ERR_RENAME_FILE_FAIL', PCLZIP_ERR_BAD_CHECKSUM => 'PCLZIP_ERR_BAD_CHECKSUM', PCLZIP_ERR_INVALID_ARCHIVE_ZIP => 'PCLZIP_ERR_INVALID_ARCHIVE_ZIP', PCLZIP_ERR_MISSING_OPTION_VALUE => 'PCLZIP_ERR_MISSING_OPTION_VALUE', PCLZIP_ERR_INVALID_OPTION_VALUE => 'PCLZIP_ERR_INVALID_OPTION_VALUE', PCLZIP_ERR_UNSUPPORTED_COMPRESSION => 'PCLZIP_ERR_UNSUPPORTED_COMPRESSION', PCLZIP_ERR_UNSUPPORTED_ENCRYPTION => 'PCLZIP_ERR_UNSUPPORTED_ENCRYPTION' ,PCLZIP_ERR_INVALID_ATTRIBUTE_VALUE => 'PCLZIP_ERR_INVALID_ATTRIBUTE_VALUE' ,PCLZIP_ERR_DIRECTORY_RESTRICTION => 'PCLZIP_ERR_DIRECTORY_RESTRICTION' ); if (isset($v_name[$this->error_code])) { $v_value = $v_name[$this->error_code]; } else { $v_value = 'NoName'; } if ($p_with_code) { return($v_value.' ('.$this->error_code.')'); } else { return($v_value); } } // -------------------------------------------------------------------------------- // -------------------------------------------------------------------------------- // Function : errorInfo() // Description : // Parameters : // -------------------------------------------------------------------------------- function errorInfo($p_full=false) { if (PCLZIP_ERROR_EXTERNAL == 1) { return(PclErrorString()); } else { if ($p_full) { return($this->errorName(true)." : ".$this->error_string); } else { return($this->error_string." [code ".$this->error_code."]"); } } } // -------------------------------------------------------------------------------- // -------------------------------------------------------------------------------- // ***** UNDER THIS LINE ARE DEFINED PRIVATE INTERNAL FUNCTIONS ***** // ***** ***** // ***** THESES FUNCTIONS MUST NOT BE USED DIRECTLY ***** // -------------------------------------------------------------------------------- // -------------------------------------------------------------------------------- // Function : privCheckFormat() // Description : // This method check that the archive exists and is a valid zip archive. // Several level of check exists. (futur) // Parameters : // $p_level : Level of check. Default 0. // 0 : Check the first bytes (magic codes) (default value)) // 1 : 0 + Check the central directory (futur) // 2 : 1 + Check each file header (futur) // Return Values : // true on success, // false on error, the error code is set. // -------------------------------------------------------------------------------- function privCheckFormat($p_level=0) { $v_result = true; // ----- Reset the file system cache clearstatcache(); // ----- Reset the error handler $this->privErrorReset(); // ----- Look if the file exits if (!is_file($this->zipname)) { // ----- Error log PclZip::privErrorLog(PCLZIP_ERR_MISSING_FILE, "Missing archive file '".$this->zipname."'"); return(false); } // ----- Check that the file is readeable if (!is_readable($this->zipname)) { // ----- Error log PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, "Unable to read archive '".$this->zipname."'"); return(false); } // ----- Check the magic code // TBC // ----- Check the central header // TBC // ----- Check each file header // TBC // ----- Return return $v_result; } // -------------------------------------------------------------------------------- // -------------------------------------------------------------------------------- // Function : privParseOptions() // Description : // This internal methods reads the variable list of arguments ($p_options_list, // $p_size) and generate an array with the options and values ($v_result_list). // $v_requested_options contains the options that can be present and those that // must be present. // $v_requested_options is an array, with the option value as key, and 'optional', // or 'mandatory' as value. // Parameters : // See above. // Return Values : // 1 on success. // 0 on failure. // -------------------------------------------------------------------------------- function privParseOptions(&$p_options_list, $p_size, &$v_result_list, $v_requested_options=false) { $v_result=1; // ----- Read the options $i=0; while ($i<$p_size) { // ----- Check if the option is supported if (!isset($v_requested_options[$p_options_list[$i]])) { // ----- Error log PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Invalid optional parameter '".$p_options_list[$i]."' for this method"); // ----- Return return PclZip::errorCode(); } // ----- Look for next option switch ($p_options_list[$i]) { // ----- Look for options that request a path value case PCLZIP_OPT_PATH : case PCLZIP_OPT_REMOVE_PATH : case PCLZIP_OPT_ADD_PATH : // ----- Check the number of parameters if (($i+1) >= $p_size) { // ----- Error log PclZip::privErrorLog(PCLZIP_ERR_MISSING_OPTION_VALUE, "Missing parameter value for option '".PclZipUtilOptionText($p_options_list[$i])."'"); // ----- Return return PclZip::errorCode(); } // ----- Get the value $v_result_list[$p_options_list[$i]] = PclZipUtilTranslateWinPath($p_options_list[$i+1], FALSE); $i++; break; case PCLZIP_OPT_TEMP_FILE_THRESHOLD : // ----- Check the number of parameters if (($i+1) >= $p_size) { PclZip::privErrorLog(PCLZIP_ERR_MISSING_OPTION_VALUE, "Missing parameter value for option '".PclZipUtilOptionText($p_options_list[$i])."'"); return PclZip::errorCode(); } // ----- Check for incompatible options if (isset($v_result_list[PCLZIP_OPT_TEMP_FILE_OFF])) { PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Option '".PclZipUtilOptionText($p_options_list[$i])."' can not be used with option 'PCLZIP_OPT_TEMP_FILE_OFF'"); return PclZip::errorCode(); } // ----- Check the value $v_value = $p_options_list[$i+1]; if ((!is_integer($v_value)) || ($v_value<0)) { PclZip::privErrorLog(PCLZIP_ERR_INVALID_OPTION_VALUE, "Integer expected for option '".PclZipUtilOptionText($p_options_list[$i])."'"); return PclZip::errorCode(); } // ----- Get the value (and convert it in bytes) $v_result_list[$p_options_list[$i]] = $v_value*1048576; $i++; break; case PCLZIP_OPT_TEMP_FILE_ON : // ----- Check for incompatible options if (isset($v_result_list[PCLZIP_OPT_TEMP_FILE_OFF])) { PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Option '".PclZipUtilOptionText($p_options_list[$i])."' can not be used with option 'PCLZIP_OPT_TEMP_FILE_OFF'"); return PclZip::errorCode(); } $v_result_list[$p_options_list[$i]] = true; break; case PCLZIP_OPT_TEMP_FILE_OFF : // ----- Check for incompatible options if (isset($v_result_list[PCLZIP_OPT_TEMP_FILE_ON])) { PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Option '".PclZipUtilOptionText($p_options_list[$i])."' can not be used with option 'PCLZIP_OPT_TEMP_FILE_ON'"); return PclZip::errorCode(); } // ----- Check for incompatible options if (isset($v_result_list[PCLZIP_OPT_TEMP_FILE_THRESHOLD])) { PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Option '".PclZipUtilOptionText($p_options_list[$i])."' can not be used with option 'PCLZIP_OPT_TEMP_FILE_THRESHOLD'"); return PclZip::errorCode(); } $v_result_list[$p_options_list[$i]] = true; break; case PCLZIP_OPT_EXTRACT_DIR_RESTRICTION : // ----- Check the number of parameters if (($i+1) >= $p_size) { // ----- Error log PclZip::privErrorLog(PCLZIP_ERR_MISSING_OPTION_VALUE, "Missing parameter value for option '".PclZipUtilOptionText($p_options_list[$i])."'"); // ----- Return return PclZip::errorCode(); } // ----- Get the value if ( is_string($p_options_list[$i+1]) && ($p_options_list[$i+1] != '')) { $v_result_list[$p_options_list[$i]] = PclZipUtilTranslateWinPath($p_options_list[$i+1], FALSE); $i++; } else { } break; // ----- Look for options that request an array of string for value case PCLZIP_OPT_BY_NAME : // ----- Check the number of parameters if (($i+1) >= $p_size) { // ----- Error log PclZip::privErrorLog(PCLZIP_ERR_MISSING_OPTION_VALUE, "Missing parameter value for option '".PclZipUtilOptionText($p_options_list[$i])."'"); // ----- Return return PclZip::errorCode(); } // ----- Get the value if (is_string($p_options_list[$i+1])) { $v_result_list[$p_options_list[$i]][0] = $p_options_list[$i+1]; } else if (is_array($p_options_list[$i+1])) { $v_result_list[$p_options_list[$i]] = $p_options_list[$i+1]; } else { // ----- Error log PclZip::privErrorLog(PCLZIP_ERR_INVALID_OPTION_VALUE, "Wrong parameter value for option '".PclZipUtilOptionText($p_options_list[$i])."'"); // ----- Return return PclZip::errorCode(); } $i++; break; // ----- Look for options that request an EREG or PREG expression case PCLZIP_OPT_BY_EREG : // ereg() is deprecated starting with PHP 5.3. Move PCLZIP_OPT_BY_EREG // to PCLZIP_OPT_BY_PREG $p_options_list[$i] = PCLZIP_OPT_BY_PREG; case PCLZIP_OPT_BY_PREG : //case PCLZIP_OPT_CRYPT : // ----- Check the number of parameters if (($i+1) >= $p_size) { // ----- Error log PclZip::privErrorLog(PCLZIP_ERR_MISSING_OPTION_VALUE, "Missing parameter value for option '".PclZipUtilOptionText($p_options_list[$i])."'"); // ----- Return return PclZip::errorCode(); } // ----- Get the value if (is_string($p_options_list[$i+1])) { $v_result_list[$p_options_list[$i]] = $p_options_list[$i+1]; } else { // ----- Error log PclZip::privErrorLog(PCLZIP_ERR_INVALID_OPTION_VALUE, "Wrong parameter value for option '".PclZipUtilOptionText($p_options_list[$i])."'"); // ----- Return return PclZip::errorCode(); } $i++; break; // ----- Look for options that takes a string case PCLZIP_OPT_COMMENT : case PCLZIP_OPT_ADD_COMMENT : case PCLZIP_OPT_PREPEND_COMMENT : // ----- Check the number of parameters if (($i+1) >= $p_size) { // ----- Error log PclZip::privErrorLog(PCLZIP_ERR_MISSING_OPTION_VALUE, "Missing parameter value for option '" .PclZipUtilOptionText($p_options_list[$i]) ."'"); // ----- Return return PclZip::errorCode(); } // ----- Get the value if (is_string($p_options_list[$i+1])) { $v_result_list[$p_options_list[$i]] = $p_options_list[$i+1]; } else { // ----- Error log PclZip::privErrorLog(PCLZIP_ERR_INVALID_OPTION_VALUE, "Wrong parameter value for option '" .PclZipUtilOptionText($p_options_list[$i]) ."'"); // ----- Return return PclZip::errorCode(); } $i++; break; // ----- Look for options that request an array of index case PCLZIP_OPT_BY_INDEX : // ----- Check the number of parameters if (($i+1) >= $p_size) { // ----- Error log PclZip::privErrorLog(PCLZIP_ERR_MISSING_OPTION_VALUE, "Missing parameter value for option '".PclZipUtilOptionText($p_options_list[$i])."'"); // ----- Return return PclZip::errorCode(); } // ----- Get the value $v_work_list = array(); if (is_string($p_options_list[$i+1])) { // ----- Remove spaces $p_options_list[$i+1] = strtr($p_options_list[$i+1], ' ', ''); // ----- Parse items $v_work_list = explode(",", $p_options_list[$i+1]); } else if (is_integer($p_options_list[$i+1])) { $v_work_list[0] = $p_options_list[$i+1].'-'.$p_options_list[$i+1]; } else if (is_array($p_options_list[$i+1])) { $v_work_list = $p_options_list[$i+1]; } else { // ----- Error log PclZip::privErrorLog(PCLZIP_ERR_INVALID_OPTION_VALUE, "Value must be integer, string or array for option '".PclZipUtilOptionText($p_options_list[$i])."'"); // ----- Return return PclZip::errorCode(); } // ----- Reduce the index list // each index item in the list must be a couple with a start and // an end value : [0,3], [5-5], [8-10], ... // ----- Check the format of each item $v_sort_flag=false; $v_sort_value=0; for ($j=0; $j<sizeof($v_work_list); $j++) { // ----- Explode the item $v_item_list = explode("-", $v_work_list[$j]); $v_size_item_list = sizeof($v_item_list); // ----- TBC : Here we might check that each item is a // real integer ... // ----- Look for single value if ($v_size_item_list == 1) { // ----- Set the option value $v_result_list[$p_options_list[$i]][$j]['start'] = $v_item_list[0]; $v_result_list[$p_options_list[$i]][$j]['end'] = $v_item_list[0]; } elseif ($v_size_item_list == 2) { // ----- Set the option value $v_result_list[$p_options_list[$i]][$j]['start'] = $v_item_list[0]; $v_result_list[$p_options_list[$i]][$j]['end'] = $v_item_list[1]; } else { // ----- Error log PclZip::privErrorLog(PCLZIP_ERR_INVALID_OPTION_VALUE, "Too many values in index range for option '".PclZipUtilOptionText($p_options_list[$i])."'"); // ----- Return return PclZip::errorCode(); } // ----- Look for list sort if ($v_result_list[$p_options_list[$i]][$j]['start'] < $v_sort_value) { $v_sort_flag=true; // ----- TBC : An automatic sort should be writen ... // ----- Error log PclZip::privErrorLog(PCLZIP_ERR_INVALID_OPTION_VALUE, "Invalid order of index range for option '".PclZipUtilOptionText($p_options_list[$i])."'"); // ----- Return return PclZip::errorCode(); } $v_sort_value = $v_result_list[$p_options_list[$i]][$j]['start']; } // ----- Sort the items if ($v_sort_flag) { // TBC : To Be Completed } // ----- Next option $i++; break; // ----- Look for options that request no value case PCLZIP_OPT_REMOVE_ALL_PATH : case PCLZIP_OPT_EXTRACT_AS_STRING : case PCLZIP_OPT_NO_COMPRESSION : case PCLZIP_OPT_EXTRACT_IN_OUTPUT : case PCLZIP_OPT_REPLACE_NEWER : case PCLZIP_OPT_STOP_ON_ERROR : $v_result_list[$p_options_list[$i]] = true; break; // ----- Look for options that request an octal value case PCLZIP_OPT_SET_CHMOD : // ----- Check the number of parameters if (($i+1) >= $p_size) { // ----- Error log PclZip::privErrorLog(PCLZIP_ERR_MISSING_OPTION_VALUE, "Missing parameter value for option '".PclZipUtilOptionText($p_options_list[$i])."'"); // ----- Return return PclZip::errorCode(); } // ----- Get the value $v_result_list[$p_options_list[$i]] = $p_options_list[$i+1]; $i++; break; // ----- Look for options that request a call-back case PCLZIP_CB_PRE_EXTRACT : case PCLZIP_CB_POST_EXTRACT : case PCLZIP_CB_PRE_ADD : case PCLZIP_CB_POST_ADD : /* for futur use case PCLZIP_CB_PRE_DELETE : case PCLZIP_CB_POST_DELETE : case PCLZIP_CB_PRE_LIST : case PCLZIP_CB_POST_LIST : */ // ----- Check the number of parameters if (($i+1) >= $p_size) { // ----- Error log PclZip::privErrorLog(PCLZIP_ERR_MISSING_OPTION_VALUE, "Missing parameter value for option '".PclZipUtilOptionText($p_options_list[$i])."'"); // ----- Return return PclZip::errorCode(); } // ----- Get the value $v_function_name = $p_options_list[$i+1]; // ----- Check that the value is a valid existing function if (!function_exists($v_function_name)) { // ----- Error log PclZip::privErrorLog(PCLZIP_ERR_INVALID_OPTION_VALUE, "Function '".$v_function_name."()' is not an existing function for option '".PclZipUtilOptionText($p_options_list[$i])."'"); // ----- Return return PclZip::errorCode(); } // ----- Set the attribute $v_result_list[$p_options_list[$i]] = $v_function_name; $i++; break; default : // ----- Error log PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Unknown parameter '" .$p_options_list[$i]."'"); // ----- Return return PclZip::errorCode(); } // ----- Next options $i++; } // ----- Look for mandatory options if ($v_requested_options !== false) { for ($key=reset($v_requested_options); $key=key($v_requested_options); $key=next($v_requested_options)) { // ----- Look for mandatory option if ($v_requested_options[$key] == 'mandatory') { // ----- Look if present if (!isset($v_result_list[$key])) { // ----- Error log PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Missing mandatory parameter ".PclZipUtilOptionText($key)."(".$key.")"); // ----- Return return PclZip::errorCode(); } } } } // ----- Look for default values if (!isset($v_result_list[PCLZIP_OPT_TEMP_FILE_THRESHOLD])) { } // ----- Return return $v_result; } // -------------------------------------------------------------------------------- // -------------------------------------------------------------------------------- // Function : privOptionDefaultThreshold() // Description : // Parameters : // Return Values : // -------------------------------------------------------------------------------- function privOptionDefaultThreshold(&$p_options) { $v_result=1; if (isset($p_options[PCLZIP_OPT_TEMP_FILE_THRESHOLD]) || isset($p_options[PCLZIP_OPT_TEMP_FILE_OFF])) { return $v_result; } // ----- Get 'memory_limit' configuration value $v_memory_limit = ini_get('memory_limit'); $v_memory_limit = trim($v_memory_limit); $last = strtolower(substr($v_memory_limit, -1)); if($last == 'g') //$v_memory_limit = $v_memory_limit*1024*1024*1024; $v_memory_limit = $v_memory_limit*1073741824; if($last == 'm') //$v_memory_limit = $v_memory_limit*1024*1024; $v_memory_limit = $v_memory_limit*1048576; if($last == 'k') $v_memory_limit = $v_memory_limit*1024; $p_options[PCLZIP_OPT_TEMP_FILE_THRESHOLD] = floor($v_memory_limit*PCLZIP_TEMPORARY_FILE_RATIO); // ----- Sanity check : No threshold if value lower than 1M if ($p_options[PCLZIP_OPT_TEMP_FILE_THRESHOLD] < 1048576) { unset($p_options[PCLZIP_OPT_TEMP_FILE_THRESHOLD]); } // ----- Return return $v_result; } // -------------------------------------------------------------------------------- // -------------------------------------------------------------------------------- // Function : privFileDescrParseAtt() // Description : // Parameters : // Return Values : // 1 on success. // 0 on failure. // -------------------------------------------------------------------------------- function privFileDescrParseAtt(&$p_file_list, &$p_filedescr, $v_options, $v_requested_options=false) { $v_result=1; // ----- For each file in the list check the attributes foreach ($p_file_list as $v_key => $v_value) { // ----- Check if the option is supported if (!isset($v_requested_options[$v_key])) { // ----- Error log PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Invalid file attribute '".$v_key."' for this file"); // ----- Return return PclZip::errorCode(); } // ----- Look for attribute switch ($v_key) { case PCLZIP_ATT_FILE_NAME : if (!is_string($v_value)) { PclZip::privErrorLog(PCLZIP_ERR_INVALID_ATTRIBUTE_VALUE, "Invalid type ".gettype($v_value).". String expected for attribute '".PclZipUtilOptionText($v_key)."'"); return PclZip::errorCode(); } $p_filedescr['filename'] = PclZipUtilPathReduction($v_value); if ($p_filedescr['filename'] == '') { PclZip::privErrorLog(PCLZIP_ERR_INVALID_ATTRIBUTE_VALUE, "Invalid empty filename for attribute '".PclZipUtilOptionText($v_key)."'"); return PclZip::errorCode(); } break; case PCLZIP_ATT_FILE_NEW_SHORT_NAME : if (!is_string($v_value)) { PclZip::privErrorLog(PCLZIP_ERR_INVALID_ATTRIBUTE_VALUE, "Invalid type ".gettype($v_value).". String expected for attribute '".PclZipUtilOptionText($v_key)."'"); return PclZip::errorCode(); } $p_filedescr['new_short_name'] = PclZipUtilPathReduction($v_value); if ($p_filedescr['new_short_name'] == '') { PclZip::privErrorLog(PCLZIP_ERR_INVALID_ATTRIBUTE_VALUE, "Invalid empty short filename for attribute '".PclZipUtilOptionText($v_key)."'"); return PclZip::errorCode(); } break; case PCLZIP_ATT_FILE_NEW_FULL_NAME : if (!is_string($v_value)) { PclZip::privErrorLog(PCLZIP_ERR_INVALID_ATTRIBUTE_VALUE, "Invalid type ".gettype($v_value).". String expected for attribute '".PclZipUtilOptionText($v_key)."'"); return PclZip::errorCode(); } $p_filedescr['new_full_name'] = PclZipUtilPathReduction($v_value); if ($p_filedescr['new_full_name'] == '') { PclZip::privErrorLog(PCLZIP_ERR_INVALID_ATTRIBUTE_VALUE, "Invalid empty full filename for attribute '".PclZipUtilOptionText($v_key)."'"); return PclZip::errorCode(); } break; // ----- Look for options that takes a string case PCLZIP_ATT_FILE_COMMENT : if (!is_string($v_value)) { PclZip::privErrorLog(PCLZIP_ERR_INVALID_ATTRIBUTE_VALUE, "Invalid type ".gettype($v_value).". String expected for attribute '".PclZipUtilOptionText($v_key)."'"); return PclZip::errorCode(); } $p_filedescr['comment'] = $v_value; break; case PCLZIP_ATT_FILE_MTIME : if (!is_integer($v_value)) { PclZip::privErrorLog(PCLZIP_ERR_INVALID_ATTRIBUTE_VALUE, "Invalid type ".gettype($v_value).". Integer expected for attribute '".PclZipUtilOptionText($v_key)."'"); return PclZip::errorCode(); } $p_filedescr['mtime'] = $v_value; break; case PCLZIP_ATT_FILE_CONTENT : $p_filedescr['content'] = $v_value; break; default : // ----- Error log PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Unknown parameter '".$v_key."'"); // ----- Return return PclZip::errorCode(); } // ----- Look for mandatory options if ($v_requested_options !== false) { for ($key=reset($v_requested_options); $key=key($v_requested_options); $key=next($v_requested_options)) { // ----- Look for mandatory option if ($v_requested_options[$key] == 'mandatory') { // ----- Look if present if (!isset($p_file_list[$key])) { PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Missing mandatory parameter ".PclZipUtilOptionText($key)."(".$key.")"); return PclZip::errorCode(); } } } } // end foreach } // ----- Return return $v_result; } // -------------------------------------------------------------------------------- // -------------------------------------------------------------------------------- // Function : privFileDescrExpand() // Description : // This method look for each item of the list to see if its a file, a folder // or a string to be added as file. For any other type of files (link, other) // just ignore the item. // Then prepare the information that will be stored for that file. // When its a folder, expand the folder with all the files that are in that // folder (recursively). // Parameters : // Return Values : // 1 on success. // 0 on failure. // -------------------------------------------------------------------------------- function privFileDescrExpand(&$p_filedescr_list, &$p_options) { $v_result=1; // ----- Create a result list $v_result_list = array(); // ----- Look each entry for ($i=0; $i<sizeof($p_filedescr_list); $i++) { // ----- Get filedescr $v_descr = $p_filedescr_list[$i]; // ----- Reduce the filename $v_descr['filename'] = PclZipUtilTranslateWinPath($v_descr['filename'], false); $v_descr['filename'] = PclZipUtilPathReduction($v_descr['filename']); // ----- Look for real file or folder if (file_exists($v_descr['filename'])) { if (@is_file($v_descr['filename'])) { $v_descr['type'] = 'file'; } else if (@is_dir($v_descr['filename'])) { $v_descr['type'] = 'folder'; } else if (@is_link($v_descr['filename'])) { // skip continue; } else { // skip continue; } } // ----- Look for string added as file else if (isset($v_descr['content'])) { $v_descr['type'] = 'virtual_file'; } // ----- Missing file else { // ----- Error log PclZip::privErrorLog(PCLZIP_ERR_MISSING_FILE, "File '".$v_descr['filename']."' does not exist"); // ----- Return return PclZip::errorCode(); } // ----- Calculate the stored filename $this->privCalculateStoredFilename($v_descr, $p_options); // ----- Add the descriptor in result list $v_result_list[sizeof($v_result_list)] = $v_descr; // ----- Look for folder if ($v_descr['type'] == 'folder') { // ----- List of items in folder $v_dirlist_descr = array(); $v_dirlist_nb = 0; if ($v_folder_handler = @opendir($v_descr['filename'])) { while (($v_item_handler = @readdir($v_folder_handler)) !== false) { // ----- Skip '.' and '..' if (($v_item_handler == '.') || ($v_item_handler == '..')) { continue; } // ----- Compose the full filename $v_dirlist_descr[$v_dirlist_nb]['filename'] = $v_descr['filename'].'/'.$v_item_handler; // ----- Look for different stored filename // Because the name of the folder was changed, the name of the // files/sub-folders also change if (($v_descr['stored_filename'] != $v_descr['filename']) && (!isset($p_options[PCLZIP_OPT_REMOVE_ALL_PATH]))) { if ($v_descr['stored_filename'] != '') { $v_dirlist_descr[$v_dirlist_nb]['new_full_name'] = $v_descr['stored_filename'].'/'.$v_item_handler; } else { $v_dirlist_descr[$v_dirlist_nb]['new_full_name'] = $v_item_handler; } } $v_dirlist_nb++; } @closedir($v_folder_handler); } else { // TBC : unable to open folder in read mode } // ----- Expand each element of the list if ($v_dirlist_nb != 0) { // ----- Expand if (($v_result = $this->privFileDescrExpand($v_dirlist_descr, $p_options)) != 1) { return $v_result; } // ----- Concat the resulting list $v_result_list = array_merge($v_result_list, $v_dirlist_descr); } else { } // ----- Free local array unset($v_dirlist_descr); } } // ----- Get the result list $p_filedescr_list = $v_result_list; // ----- Return return $v_result; } // -------------------------------------------------------------------------------- // -------------------------------------------------------------------------------- // Function : privCreate() // Description : // Parameters : // Return Values : // -------------------------------------------------------------------------------- function privCreate($p_filedescr_list, &$p_result_list, &$p_options) { $v_result=1; $v_list_detail = array(); // ----- Magic quotes trick $this->privDisableMagicQuotes(); // ----- Open the file in write mode if (($v_result = $this->privOpenFd('wb')) != 1) { // ----- Return return $v_result; } // ----- Add the list of files $v_result = $this->privAddList($p_filedescr_list, $p_result_list, $p_options); // ----- Close $this->privCloseFd(); // ----- Magic quotes trick $this->privSwapBackMagicQuotes(); // ----- Return return $v_result; } // -------------------------------------------------------------------------------- // -------------------------------------------------------------------------------- // Function : privAdd() // Description : // Parameters : // Return Values : // -------------------------------------------------------------------------------- function privAdd($p_filedescr_list, &$p_result_list, &$p_options) { $v_result=1; $v_list_detail = array(); // ----- Look if the archive exists or is empty if ((!is_file($this->zipname)) || (filesize($this->zipname) == 0)) { // ----- Do a create $v_result = $this->privCreate($p_filedescr_list, $p_result_list, $p_options); // ----- Return return $v_result; } // ----- Magic quotes trick $this->privDisableMagicQuotes(); // ----- Open the zip file if (($v_result=$this->privOpenFd('rb')) != 1) { // ----- Magic quotes trick $this->privSwapBackMagicQuotes(); // ----- Return return $v_result; } // ----- Read the central directory informations $v_central_dir = array(); if (($v_result = $this->privReadEndCentralDir($v_central_dir)) != 1) { $this->privCloseFd(); $this->privSwapBackMagicQuotes(); return $v_result; } // ----- Go to beginning of File @rewind($this->zip_fd); // ----- Creates a temporay file $v_zip_temp_name = PCLZIP_TEMPORARY_DIR.uniqid('pclzip-').'.tmp'; // ----- Open the temporary file in write mode if (($v_zip_temp_fd = @fopen($v_zip_temp_name, 'wb')) == 0) { $this->privCloseFd(); $this->privSwapBackMagicQuotes(); PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, 'Unable to open temporary file \''.$v_zip_temp_name.'\' in binary write mode'); // ----- Return return PclZip::errorCode(); } // ----- Copy the files from the archive to the temporary file // TBC : Here I should better append the file and go back to erase the central dir $v_size = $v_central_dir['offset']; while ($v_size != 0) { $v_read_size = ($v_size < PCLZIP_READ_BLOCK_SIZE ? $v_size : PCLZIP_READ_BLOCK_SIZE); $v_buffer = fread($this->zip_fd, $v_read_size); @fwrite($v_zip_temp_fd, $v_buffer, $v_read_size); $v_size -= $v_read_size; } // ----- Swap the file descriptor // Here is a trick : I swap the temporary fd with the zip fd, in order to use // the following methods on the temporary fil and not the real archive $v_swap = $this->zip_fd; $this->zip_fd = $v_zip_temp_fd; $v_zip_temp_fd = $v_swap; // ----- Add the files $v_header_list = array(); if (($v_result = $this->privAddFileList($p_filedescr_list, $v_header_list, $p_options)) != 1) { fclose($v_zip_temp_fd); $this->privCloseFd(); @unlink($v_zip_temp_name); $this->privSwapBackMagicQuotes(); // ----- Return return $v_result; } // ----- Store the offset of the central dir $v_offset = @ftell($this->zip_fd); // ----- Copy the block of file headers from the old archive $v_size = $v_central_dir['size']; while ($v_size != 0) { $v_read_size = ($v_size < PCLZIP_READ_BLOCK_SIZE ? $v_size : PCLZIP_READ_BLOCK_SIZE); $v_buffer = @fread($v_zip_temp_fd, $v_read_size); @fwrite($this->zip_fd, $v_buffer, $v_read_size); $v_size -= $v_read_size; } // ----- Create the Central Dir files header for ($i=0, $v_count=0; $i<sizeof($v_header_list); $i++) { // ----- Create the file header if ($v_header_list[$i]['status'] == 'ok') { if (($v_result = $this->privWriteCentralFileHeader($v_header_list[$i])) != 1) { fclose($v_zip_temp_fd); $this->privCloseFd(); @unlink($v_zip_temp_name); $this->privSwapBackMagicQuotes(); // ----- Return return $v_result; } $v_count++; } // ----- Transform the header to a 'usable' info $this->privConvertHeader2FileInfo($v_header_list[$i], $p_result_list[$i]); } // ----- Zip file comment $v_comment = $v_central_dir['comment']; if (isset($p_options[PCLZIP_OPT_COMMENT])) { $v_comment = $p_options[PCLZIP_OPT_COMMENT]; } if (isset($p_options[PCLZIP_OPT_ADD_COMMENT])) { $v_comment = $v_comment.$p_options[PCLZIP_OPT_ADD_COMMENT]; } if (isset($p_options[PCLZIP_OPT_PREPEND_COMMENT])) { $v_comment = $p_options[PCLZIP_OPT_PREPEND_COMMENT].$v_comment; } // ----- Calculate the size of the central header $v_size = @ftell($this->zip_fd)-$v_offset; // ----- Create the central dir footer if (($v_result = $this->privWriteCentralHeader($v_count+$v_central_dir['entries'], $v_size, $v_offset, $v_comment)) != 1) { // ----- Reset the file list unset($v_header_list); $this->privSwapBackMagicQuotes(); // ----- Return return $v_result; } // ----- Swap back the file descriptor $v_swap = $this->zip_fd; $this->zip_fd = $v_zip_temp_fd; $v_zip_temp_fd = $v_swap; // ----- Close $this->privCloseFd(); // ----- Close the temporary file @fclose($v_zip_temp_fd); // ----- Magic quotes trick $this->privSwapBackMagicQuotes(); // ----- Delete the zip file // TBC : I should test the result ... @unlink($this->zipname); // ----- Rename the temporary file // TBC : I should test the result ... //@rename($v_zip_temp_name, $this->zipname); PclZipUtilRename($v_zip_temp_name, $this->zipname); // ----- Return return $v_result; } // -------------------------------------------------------------------------------- // -------------------------------------------------------------------------------- // Function : privOpenFd() // Description : // Parameters : // -------------------------------------------------------------------------------- function privOpenFd($p_mode) { $v_result=1; // ----- Look if already open if ($this->zip_fd != 0) { // ----- Error log PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, 'Zip file \''.$this->zipname.'\' already open'); // ----- Return return PclZip::errorCode(); } // ----- Open the zip file if (($this->zip_fd = @fopen($this->zipname, $p_mode)) == 0) { // ----- Error log PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, 'Unable to open archive \''.$this->zipname.'\' in '.$p_mode.' mode'); // ----- Return return PclZip::errorCode(); } // ----- Return return $v_result; } // -------------------------------------------------------------------------------- // -------------------------------------------------------------------------------- // Function : privCloseFd() // Description : // Parameters : // -------------------------------------------------------------------------------- function privCloseFd() { $v_result=1; if ($this->zip_fd != 0) @fclose($this->zip_fd); $this->zip_fd = 0; // ----- Return return $v_result; } // -------------------------------------------------------------------------------- // -------------------------------------------------------------------------------- // Function : privAddList() // Description : // $p_add_dir and $p_remove_dir will give the ability to memorize a path which is // different from the real path of the file. This is usefull if you want to have PclTar // running in any directory, and memorize relative path from an other directory. // Parameters : // $p_list : An array containing the file or directory names to add in the tar // $p_result_list : list of added files with their properties (specially the status field) // $p_add_dir : Path to add in the filename path archived // $p_remove_dir : Path to remove in the filename path archived // Return Values : // -------------------------------------------------------------------------------- // function privAddList($p_list, &$p_result_list, $p_add_dir, $p_remove_dir, $p_remove_all_dir, &$p_options) function privAddList($p_filedescr_list, &$p_result_list, &$p_options) { $v_result=1; // ----- Add the files $v_header_list = array(); if (($v_result = $this->privAddFileList($p_filedescr_list, $v_header_list, $p_options)) != 1) { // ----- Return return $v_result; } // ----- Store the offset of the central dir $v_offset = @ftell($this->zip_fd); // ----- Create the Central Dir files header for ($i=0,$v_count=0; $i<sizeof($v_header_list); $i++) { // ----- Create the file header if ($v_header_list[$i]['status'] == 'ok') { if (($v_result = $this->privWriteCentralFileHeader($v_header_list[$i])) != 1) { // ----- Return return $v_result; } $v_count++; } // ----- Transform the header to a 'usable' info $this->privConvertHeader2FileInfo($v_header_list[$i], $p_result_list[$i]); } // ----- Zip file comment $v_comment = ''; if (isset($p_options[PCLZIP_OPT_COMMENT])) { $v_comment = $p_options[PCLZIP_OPT_COMMENT]; } // ----- Calculate the size of the central header $v_size = @ftell($this->zip_fd)-$v_offset; // ----- Create the central dir footer if (($v_result = $this->privWriteCentralHeader($v_count, $v_size, $v_offset, $v_comment)) != 1) { // ----- Reset the file list unset($v_header_list); // ----- Return return $v_result; } // ----- Return return $v_result; } // -------------------------------------------------------------------------------- // -------------------------------------------------------------------------------- // Function : privAddFileList() // Description : // Parameters : // $p_filedescr_list : An array containing the file description // or directory names to add in the zip // $p_result_list : list of added files with their properties (specially the status field) // Return Values : // -------------------------------------------------------------------------------- function privAddFileList($p_filedescr_list, &$p_result_list, &$p_options) { $v_result=1; $v_header = array(); // ----- Recuperate the current number of elt in list $v_nb = sizeof($p_result_list); // ----- Loop on the files for ($j=0; ($j<sizeof($p_filedescr_list)) && ($v_result==1); $j++) { // ----- Format the filename $p_filedescr_list[$j]['filename'] = PclZipUtilTranslateWinPath($p_filedescr_list[$j]['filename'], false); // ----- Skip empty file names // TBC : Can this be possible ? not checked in DescrParseAtt ? if ($p_filedescr_list[$j]['filename'] == "") { continue; } // ----- Check the filename if ( ($p_filedescr_list[$j]['type'] != 'virtual_file') && (!file_exists($p_filedescr_list[$j]['filename']))) { PclZip::privErrorLog(PCLZIP_ERR_MISSING_FILE, "File '".$p_filedescr_list[$j]['filename']."' does not exist"); return PclZip::errorCode(); } // ----- Look if it is a file or a dir with no all path remove option // or a dir with all its path removed // if ( (is_file($p_filedescr_list[$j]['filename'])) // || ( is_dir($p_filedescr_list[$j]['filename']) if ( ($p_filedescr_list[$j]['type'] == 'file') || ($p_filedescr_list[$j]['type'] == 'virtual_file') || ( ($p_filedescr_list[$j]['type'] == 'folder') && ( !isset($p_options[PCLZIP_OPT_REMOVE_ALL_PATH]) || !$p_options[PCLZIP_OPT_REMOVE_ALL_PATH])) ) { // ----- Add the file $v_result = $this->privAddFile($p_filedescr_list[$j], $v_header, $p_options); if ($v_result != 1) { return $v_result; } // ----- Store the file infos $p_result_list[$v_nb++] = $v_header; } } // ----- Return return $v_result; } // -------------------------------------------------------------------------------- // -------------------------------------------------------------------------------- // Function : privAddFile() // Description : // Parameters : // Return Values : // -------------------------------------------------------------------------------- function privAddFile($p_filedescr, &$p_header, &$p_options) { $v_result=1; // ----- Working variable $p_filename = $p_filedescr['filename']; // TBC : Already done in the fileAtt check ... ? if ($p_filename == "") { // ----- Error log PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Invalid file list parameter (invalid or empty list)"); // ----- Return return PclZip::errorCode(); } // ----- Look for a stored different filename /* TBC : Removed if (isset($p_filedescr['stored_filename'])) { $v_stored_filename = $p_filedescr['stored_filename']; } else { $v_stored_filename = $p_filedescr['stored_filename']; } */ // ----- Set the file properties clearstatcache(); $p_header['version'] = 20; $p_header['version_extracted'] = 10; $p_header['flag'] = 0; $p_header['compression'] = 0; $p_header['crc'] = 0; $p_header['compressed_size'] = 0; $p_header['filename_len'] = strlen($p_filename); $p_header['extra_len'] = 0; $p_header['disk'] = 0; $p_header['internal'] = 0; $p_header['offset'] = 0; $p_header['filename'] = $p_filename; // TBC : Removed $p_header['stored_filename'] = $v_stored_filename; $p_header['stored_filename'] = $p_filedescr['stored_filename']; $p_header['extra'] = ''; $p_header['status'] = 'ok'; $p_header['index'] = -1; // ----- Look for regular file if ($p_filedescr['type']=='file') { $p_header['external'] = 0x00000000; $p_header['size'] = filesize($p_filename); } // ----- Look for regular folder else if ($p_filedescr['type']=='folder') { $p_header['external'] = 0x00000010; $p_header['mtime'] = filemtime($p_filename); $p_header['size'] = filesize($p_filename); } // ----- Look for virtual file else if ($p_filedescr['type'] == 'virtual_file') { $p_header['external'] = 0x00000000; $p_header['size'] = strlen($p_filedescr['content']); } // ----- Look for filetime if (isset($p_filedescr['mtime'])) { $p_header['mtime'] = $p_filedescr['mtime']; } else if ($p_filedescr['type'] == 'virtual_file') { $p_header['mtime'] = time(); } else { $p_header['mtime'] = filemtime($p_filename); } // ------ Look for file comment if (isset($p_filedescr['comment'])) { $p_header['comment_len'] = strlen($p_filedescr['comment']); $p_header['comment'] = $p_filedescr['comment']; } else { $p_header['comment_len'] = 0; $p_header['comment'] = ''; } // ----- Look for pre-add callback if (isset($p_options[PCLZIP_CB_PRE_ADD])) { // ----- Generate a local information $v_local_header = array(); $this->privConvertHeader2FileInfo($p_header, $v_local_header); // ----- Call the callback // Here I do not use call_user_func() because I need to send a reference to the // header. // eval('$v_result = '.$p_options[PCLZIP_CB_PRE_ADD].'(PCLZIP_CB_PRE_ADD, $v_local_header);'); $v_result = $p_options[PCLZIP_CB_PRE_ADD](PCLZIP_CB_PRE_ADD, $v_local_header); if ($v_result == 0) { // ----- Change the file status $p_header['status'] = "skipped"; $v_result = 1; } // ----- Update the informations // Only some fields can be modified if ($p_header['stored_filename'] != $v_local_header['stored_filename']) { $p_header['stored_filename'] = PclZipUtilPathReduction($v_local_header['stored_filename']); } } // ----- Look for empty stored filename if ($p_header['stored_filename'] == "") { $p_header['status'] = "filtered"; } // ----- Check the path length if (strlen($p_header['stored_filename']) > 0xFF) { $p_header['status'] = 'filename_too_long'; } // ----- Look if no error, or file not skipped if ($p_header['status'] == 'ok') { // ----- Look for a file if ($p_filedescr['type'] == 'file') { // ----- Look for using temporary file to zip if ( (!isset($p_options[PCLZIP_OPT_TEMP_FILE_OFF])) && (isset($p_options[PCLZIP_OPT_TEMP_FILE_ON]) || (isset($p_options[PCLZIP_OPT_TEMP_FILE_THRESHOLD]) && ($p_options[PCLZIP_OPT_TEMP_FILE_THRESHOLD] <= $p_header['size'])) ) ) { $v_result = $this->privAddFileUsingTempFile($p_filedescr, $p_header, $p_options); if ($v_result < PCLZIP_ERR_NO_ERROR) { return $v_result; } } // ----- Use "in memory" zip algo else { // ----- Open the source file if (($v_file = @fopen($p_filename, "rb")) == 0) { PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, "Unable to open file '$p_filename' in binary read mode"); return PclZip::errorCode(); } // ----- Read the file content $v_content = @fread($v_file, $p_header['size']); // ----- Close the file @fclose($v_file); // ----- Calculate the CRC $p_header['crc'] = @crc32($v_content); // ----- Look for no compression if ($p_options[PCLZIP_OPT_NO_COMPRESSION]) { // ----- Set header parameters $p_header['compressed_size'] = $p_header['size']; $p_header['compression'] = 0; } // ----- Look for normal compression else { // ----- Compress the content $v_content = @gzdeflate($v_content); // ----- Set header parameters $p_header['compressed_size'] = strlen($v_content); $p_header['compression'] = 8; } // ----- Call the header generation if (($v_result = $this->privWriteFileHeader($p_header)) != 1) { @fclose($v_file); return $v_result; } // ----- Write the compressed (or not) content @fwrite($this->zip_fd, $v_content, $p_header['compressed_size']); } } // ----- Look for a virtual file (a file from string) else if ($p_filedescr['type'] == 'virtual_file') { $v_content = $p_filedescr['content']; // ----- Calculate the CRC $p_header['crc'] = @crc32($v_content); // ----- Look for no compression if ($p_options[PCLZIP_OPT_NO_COMPRESSION]) { // ----- Set header parameters $p_header['compressed_size'] = $p_header['size']; $p_header['compression'] = 0; } // ----- Look for normal compression else { // ----- Compress the content $v_content = @gzdeflate($v_content); // ----- Set header parameters $p_header['compressed_size'] = strlen($v_content); $p_header['compression'] = 8; } // ----- Call the header generation if (($v_result = $this->privWriteFileHeader($p_header)) != 1) { @fclose($v_file); return $v_result; } // ----- Write the compressed (or not) content @fwrite($this->zip_fd, $v_content, $p_header['compressed_size']); } // ----- Look for a directory else if ($p_filedescr['type'] == 'folder') { // ----- Look for directory last '/' if (@substr($p_header['stored_filename'], -1) != '/') { $p_header['stored_filename'] .= '/'; } // ----- Set the file properties $p_header['size'] = 0; //$p_header['external'] = 0x41FF0010; // Value for a folder : to be checked $p_header['external'] = 0x00000010; // Value for a folder : to be checked // ----- Call the header generation if (($v_result = $this->privWriteFileHeader($p_header)) != 1) { return $v_result; } } } // ----- Look for post-add callback if (isset($p_options[PCLZIP_CB_POST_ADD])) { // ----- Generate a local information $v_local_header = array(); $this->privConvertHeader2FileInfo($p_header, $v_local_header); // ----- Call the callback // Here I do not use call_user_func() because I need to send a reference to the // header. // eval('$v_result = '.$p_options[PCLZIP_CB_POST_ADD].'(PCLZIP_CB_POST_ADD, $v_local_header);'); $v_result = $p_options[PCLZIP_CB_POST_ADD](PCLZIP_CB_POST_ADD, $v_local_header); if ($v_result == 0) { // ----- Ignored $v_result = 1; } // ----- Update the informations // Nothing can be modified } // ----- Return return $v_result; } // -------------------------------------------------------------------------------- // -------------------------------------------------------------------------------- // Function : privAddFileUsingTempFile() // Description : // Parameters : // Return Values : // -------------------------------------------------------------------------------- function privAddFileUsingTempFile($p_filedescr, &$p_header, &$p_options) { $v_result=PCLZIP_ERR_NO_ERROR; // ----- Working variable $p_filename = $p_filedescr['filename']; // ----- Open the source file if (($v_file = @fopen($p_filename, "rb")) == 0) { PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, "Unable to open file '$p_filename' in binary read mode"); return PclZip::errorCode(); } // ----- Creates a compressed temporary file $v_gzip_temp_name = PCLZIP_TEMPORARY_DIR.uniqid('pclzip-').'.gz'; if (($v_file_compressed = @gzopen($v_gzip_temp_name, "wb")) == 0) { fclose($v_file); PclZip::privErrorLog(PCLZIP_ERR_WRITE_OPEN_FAIL, 'Unable to open temporary file \''.$v_gzip_temp_name.'\' in binary write mode'); return PclZip::errorCode(); } // ----- Read the file by PCLZIP_READ_BLOCK_SIZE octets blocks $v_size = filesize($p_filename); while ($v_size != 0) { $v_read_size = ($v_size < PCLZIP_READ_BLOCK_SIZE ? $v_size : PCLZIP_READ_BLOCK_SIZE); $v_buffer = @fread($v_file, $v_read_size); //$v_binary_data = pack('a'.$v_read_size, $v_buffer); @gzputs($v_file_compressed, $v_buffer, $v_read_size); $v_size -= $v_read_size; } // ----- Close the file @fclose($v_file); @gzclose($v_file_compressed); // ----- Check the minimum file size if (filesize($v_gzip_temp_name) < 18) { PclZip::privErrorLog(PCLZIP_ERR_BAD_FORMAT, 'gzip temporary file \''.$v_gzip_temp_name.'\' has invalid filesize - should be minimum 18 bytes'); return PclZip::errorCode(); } // ----- Extract the compressed attributes if (($v_file_compressed = @fopen($v_gzip_temp_name, "rb")) == 0) { PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, 'Unable to open temporary file \''.$v_gzip_temp_name.'\' in binary read mode'); return PclZip::errorCode(); } // ----- Read the gzip file header $v_binary_data = @fread($v_file_compressed, 10); $v_data_header = unpack('a1id1/a1id2/a1cm/a1flag/Vmtime/a1xfl/a1os', $v_binary_data); // ----- Check some parameters $v_data_header['os'] = bin2hex($v_data_header['os']); // ----- Read the gzip file footer @fseek($v_file_compressed, filesize($v_gzip_temp_name)-8); $v_binary_data = @fread($v_file_compressed, 8); $v_data_footer = unpack('Vcrc/Vcompressed_size', $v_binary_data); // ----- Set the attributes $p_header['compression'] = ord($v_data_header['cm']); //$p_header['mtime'] = $v_data_header['mtime']; $p_header['crc'] = $v_data_footer['crc']; $p_header['compressed_size'] = filesize($v_gzip_temp_name)-18; // ----- Close the file @fclose($v_file_compressed); // ----- Call the header generation if (($v_result = $this->privWriteFileHeader($p_header)) != 1) { return $v_result; } // ----- Add the compressed data if (($v_file_compressed = @fopen($v_gzip_temp_name, "rb")) == 0) { PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, 'Unable to open temporary file \''.$v_gzip_temp_name.'\' in binary read mode'); return PclZip::errorCode(); } // ----- Read the file by PCLZIP_READ_BLOCK_SIZE octets blocks fseek($v_file_compressed, 10); $v_size = $p_header['compressed_size']; while ($v_size != 0) { $v_read_size = ($v_size < PCLZIP_READ_BLOCK_SIZE ? $v_size : PCLZIP_READ_BLOCK_SIZE); $v_buffer = @fread($v_file_compressed, $v_read_size); //$v_binary_data = pack('a'.$v_read_size, $v_buffer); @fwrite($this->zip_fd, $v_buffer, $v_read_size); $v_size -= $v_read_size; } // ----- Close the file @fclose($v_file_compressed); // ----- Unlink the temporary file @unlink($v_gzip_temp_name); // ----- Return return $v_result; } // -------------------------------------------------------------------------------- // -------------------------------------------------------------------------------- // Function : privCalculateStoredFilename() // Description : // Based on file descriptor properties and global options, this method // calculate the filename that will be stored in the archive. // Parameters : // Return Values : // -------------------------------------------------------------------------------- function privCalculateStoredFilename(&$p_filedescr, &$p_options) { $v_result=1; // ----- Working variables $p_filename = $p_filedescr['filename']; if (isset($p_options[PCLZIP_OPT_ADD_PATH])) { $p_add_dir = $p_options[PCLZIP_OPT_ADD_PATH]; } else { $p_add_dir = ''; } if (isset($p_options[PCLZIP_OPT_REMOVE_PATH])) { $p_remove_dir = $p_options[PCLZIP_OPT_REMOVE_PATH]; } else { $p_remove_dir = ''; } if (isset($p_options[PCLZIP_OPT_REMOVE_ALL_PATH])) { $p_remove_all_dir = $p_options[PCLZIP_OPT_REMOVE_ALL_PATH]; } else { $p_remove_all_dir = 0; } // ----- Look for full name change if (isset($p_filedescr['new_full_name'])) { // ----- Remove drive letter if any $v_stored_filename = PclZipUtilTranslateWinPath($p_filedescr['new_full_name']); } // ----- Look for path and/or short name change else { // ----- Look for short name change // Its when we cahnge just the filename but not the path if (isset($p_filedescr['new_short_name'])) { $v_path_info = pathinfo($p_filename); $v_dir = ''; if ($v_path_info['dirname'] != '') { $v_dir = $v_path_info['dirname'].'/'; } $v_stored_filename = $v_dir.$p_filedescr['new_short_name']; } else { // ----- Calculate the stored filename $v_stored_filename = $p_filename; } // ----- Look for all path to remove if ($p_remove_all_dir) { $v_stored_filename = basename($p_filename); } // ----- Look for partial path remove else if ($p_remove_dir != "") { if (substr($p_remove_dir, -1) != '/') $p_remove_dir .= "/"; if ( (substr($p_filename, 0, 2) == "./") || (substr($p_remove_dir, 0, 2) == "./")) { if ( (substr($p_filename, 0, 2) == "./") && (substr($p_remove_dir, 0, 2) != "./")) { $p_remove_dir = "./".$p_remove_dir; } if ( (substr($p_filename, 0, 2) != "./") && (substr($p_remove_dir, 0, 2) == "./")) { $p_remove_dir = substr($p_remove_dir, 2); } } $v_compare = PclZipUtilPathInclusion($p_remove_dir, $v_stored_filename); if ($v_compare > 0) { if ($v_compare == 2) { $v_stored_filename = ""; } else { $v_stored_filename = substr($v_stored_filename, strlen($p_remove_dir)); } } } // ----- Remove drive letter if any $v_stored_filename = PclZipUtilTranslateWinPath($v_stored_filename); // ----- Look for path to add if ($p_add_dir != "") { if (substr($p_add_dir, -1) == "/") $v_stored_filename = $p_add_dir.$v_stored_filename; else $v_stored_filename = $p_add_dir."/".$v_stored_filename; } } // ----- Filename (reduce the path of stored name) $v_stored_filename = PclZipUtilPathReduction($v_stored_filename); $p_filedescr['stored_filename'] = $v_stored_filename; // ----- Return return $v_result; } // -------------------------------------------------------------------------------- // -------------------------------------------------------------------------------- // Function : privWriteFileHeader() // Description : // Parameters : // Return Values : // -------------------------------------------------------------------------------- function privWriteFileHeader(&$p_header) { $v_result=1; // ----- Store the offset position of the file $p_header['offset'] = ftell($this->zip_fd); // ----- Transform UNIX mtime to DOS format mdate/mtime $v_date = getdate($p_header['mtime']); $v_mtime = ($v_date['hours']<<11) + ($v_date['minutes']<<5) + $v_date['seconds']/2; $v_mdate = (($v_date['year']-1980)<<9) + ($v_date['mon']<<5) + $v_date['mday']; // ----- Packed data $v_binary_data = pack("VvvvvvVVVvv", 0x04034b50, $p_header['version_extracted'], $p_header['flag'], $p_header['compression'], $v_mtime, $v_mdate, $p_header['crc'], $p_header['compressed_size'], $p_header['size'], strlen($p_header['stored_filename']), $p_header['extra_len']); // ----- Write the first 148 bytes of the header in the archive fputs($this->zip_fd, $v_binary_data, 30); // ----- Write the variable fields if (strlen($p_header['stored_filename']) != 0) { fputs($this->zip_fd, $p_header['stored_filename'], strlen($p_header['stored_filename'])); } if ($p_header['extra_len'] != 0) { fputs($this->zip_fd, $p_header['extra'], $p_header['extra_len']); } // ----- Return return $v_result; } // -------------------------------------------------------------------------------- // -------------------------------------------------------------------------------- // Function : privWriteCentralFileHeader() // Description : // Parameters : // Return Values : // -------------------------------------------------------------------------------- function privWriteCentralFileHeader(&$p_header) { $v_result=1; // TBC //for(reset($p_header); $key = key($p_header); next($p_header)) { //} // ----- Transform UNIX mtime to DOS format mdate/mtime $v_date = getdate($p_header['mtime']); $v_mtime = ($v_date['hours']<<11) + ($v_date['minutes']<<5) + $v_date['seconds']/2; $v_mdate = (($v_date['year']-1980)<<9) + ($v_date['mon']<<5) + $v_date['mday']; // ----- Packed data $v_binary_data = pack("VvvvvvvVVVvvvvvVV", 0x02014b50, $p_header['version'], $p_header['version_extracted'], $p_header['flag'], $p_header['compression'], $v_mtime, $v_mdate, $p_header['crc'], $p_header['compressed_size'], $p_header['size'], strlen($p_header['stored_filename']), $p_header['extra_len'], $p_header['comment_len'], $p_header['disk'], $p_header['internal'], $p_header['external'], $p_header['offset']); // ----- Write the 42 bytes of the header in the zip file fputs($this->zip_fd, $v_binary_data, 46); // ----- Write the variable fields if (strlen($p_header['stored_filename']) != 0) { fputs($this->zip_fd, $p_header['stored_filename'], strlen($p_header['stored_filename'])); } if ($p_header['extra_len'] != 0) { fputs($this->zip_fd, $p_header['extra'], $p_header['extra_len']); } if ($p_header['comment_len'] != 0) { fputs($this->zip_fd, $p_header['comment'], $p_header['comment_len']); } // ----- Return return $v_result; } // -------------------------------------------------------------------------------- // -------------------------------------------------------------------------------- // Function : privWriteCentralHeader() // Description : // Parameters : // Return Values : // -------------------------------------------------------------------------------- function privWriteCentralHeader($p_nb_entries, $p_size, $p_offset, $p_comment) { $v_result=1; // ----- Packed data $v_binary_data = pack("VvvvvVVv", 0x06054b50, 0, 0, $p_nb_entries, $p_nb_entries, $p_size, $p_offset, strlen($p_comment)); // ----- Write the 22 bytes of the header in the zip file fputs($this->zip_fd, $v_binary_data, 22); // ----- Write the variable fields if (strlen($p_comment) != 0) { fputs($this->zip_fd, $p_comment, strlen($p_comment)); } // ----- Return return $v_result; } // -------------------------------------------------------------------------------- // -------------------------------------------------------------------------------- // Function : privList() // Description : // Parameters : // Return Values : // -------------------------------------------------------------------------------- function privList(&$p_list) { $v_result=1; // ----- Magic quotes trick $this->privDisableMagicQuotes(); // ----- Open the zip file if (($this->zip_fd = @fopen($this->zipname, 'rb')) == 0) { // ----- Magic quotes trick $this->privSwapBackMagicQuotes(); // ----- Error log PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, 'Unable to open archive \''.$this->zipname.'\' in binary read mode'); // ----- Return return PclZip::errorCode(); } // ----- Read the central directory informations $v_central_dir = array(); if (($v_result = $this->privReadEndCentralDir($v_central_dir)) != 1) { $this->privSwapBackMagicQuotes(); return $v_result; } // ----- Go to beginning of Central Dir @rewind($this->zip_fd); if (@fseek($this->zip_fd, $v_central_dir['offset'])) { $this->privSwapBackMagicQuotes(); // ----- Error log PclZip::privErrorLog(PCLZIP_ERR_INVALID_ARCHIVE_ZIP, 'Invalid archive size'); // ----- Return return PclZip::errorCode(); } // ----- Read each entry for ($i=0; $i<$v_central_dir['entries']; $i++) { // ----- Read the file header if (($v_result = $this->privReadCentralFileHeader($v_header)) != 1) { $this->privSwapBackMagicQuotes(); return $v_result; } $v_header['index'] = $i; // ----- Get the only interesting attributes $this->privConvertHeader2FileInfo($v_header, $p_list[$i]); unset($v_header); } // ----- Close the zip file $this->privCloseFd(); // ----- Magic quotes trick $this->privSwapBackMagicQuotes(); // ----- Return return $v_result; } // -------------------------------------------------------------------------------- // -------------------------------------------------------------------------------- // Function : privConvertHeader2FileInfo() // Description : // This function takes the file informations from the central directory // entries and extract the interesting parameters that will be given back. // The resulting file infos are set in the array $p_info // $p_info['filename'] : Filename with full path. Given by user (add), // extracted in the filesystem (extract). // $p_info['stored_filename'] : Stored filename in the archive. // $p_info['size'] = Size of the file. // $p_info['compressed_size'] = Compressed size of the file. // $p_info['mtime'] = Last modification date of the file. // $p_info['comment'] = Comment associated with the file. // $p_info['folder'] = true/false : indicates if the entry is a folder or not. // $p_info['status'] = status of the action on the file. // $p_info['crc'] = CRC of the file content. // Parameters : // Return Values : // -------------------------------------------------------------------------------- function privConvertHeader2FileInfo($p_header, &$p_info) { $v_result=1; // ----- Get the interesting attributes $v_temp_path = PclZipUtilPathReduction($p_header['filename']); $p_info['filename'] = $v_temp_path; $v_temp_path = PclZipUtilPathReduction($p_header['stored_filename']); $p_info['stored_filename'] = $v_temp_path; $p_info['size'] = $p_header['size']; $p_info['compressed_size'] = $p_header['compressed_size']; $p_info['mtime'] = $p_header['mtime']; $p_info['comment'] = $p_header['comment']; $p_info['folder'] = (($p_header['external']&0x00000010)==0x00000010); $p_info['index'] = $p_header['index']; $p_info['status'] = $p_header['status']; $p_info['crc'] = $p_header['crc']; // ----- Return return $v_result; } // -------------------------------------------------------------------------------- // -------------------------------------------------------------------------------- // Function : privExtractByRule() // Description : // Extract a file or directory depending of rules (by index, by name, ...) // Parameters : // $p_file_list : An array where will be placed the properties of each // extracted file // $p_path : Path to add while writing the extracted files // $p_remove_path : Path to remove (from the file memorized path) while writing the // extracted files. If the path does not match the file path, // the file is extracted with its memorized path. // $p_remove_path does not apply to 'list' mode. // $p_path and $p_remove_path are commulative. // Return Values : // 1 on success,0 or less on error (see error code list) // -------------------------------------------------------------------------------- function privExtractByRule(&$p_file_list, $p_path, $p_remove_path, $p_remove_all_path, &$p_options) { $v_result=1; // ----- Magic quotes trick $this->privDisableMagicQuotes(); // ----- Check the path if ( ($p_path == "") || ( (substr($p_path, 0, 1) != "/") && (substr($p_path, 0, 3) != "../") && (substr($p_path,1,2)!=":/"))) $p_path = "./".$p_path; // ----- Reduce the path last (and duplicated) '/' if (($p_path != "./") && ($p_path != "/")) { // ----- Look for the path end '/' while (substr($p_path, -1) == "/") { $p_path = substr($p_path, 0, strlen($p_path)-1); } } // ----- Look for path to remove format (should end by /) if (($p_remove_path != "") && (substr($p_remove_path, -1) != '/')) { $p_remove_path .= '/'; } $p_remove_path_size = strlen($p_remove_path); // ----- Open the zip file if (($v_result = $this->privOpenFd('rb')) != 1) { $this->privSwapBackMagicQuotes(); return $v_result; } // ----- Read the central directory informations $v_central_dir = array(); if (($v_result = $this->privReadEndCentralDir($v_central_dir)) != 1) { // ----- Close the zip file $this->privCloseFd(); $this->privSwapBackMagicQuotes(); return $v_result; } // ----- Start at beginning of Central Dir $v_pos_entry = $v_central_dir['offset']; // ----- Read each entry $j_start = 0; for ($i=0, $v_nb_extracted=0; $i<$v_central_dir['entries']; $i++) { // ----- Read next Central dir entry @rewind($this->zip_fd); if (@fseek($this->zip_fd, $v_pos_entry)) { // ----- Close the zip file $this->privCloseFd(); $this->privSwapBackMagicQuotes(); // ----- Error log PclZip::privErrorLog(PCLZIP_ERR_INVALID_ARCHIVE_ZIP, 'Invalid archive size'); // ----- Return return PclZip::errorCode(); } // ----- Read the file header $v_header = array(); if (($v_result = $this->privReadCentralFileHeader($v_header)) != 1) { // ----- Close the zip file $this->privCloseFd(); $this->privSwapBackMagicQuotes(); return $v_result; } // ----- Store the index $v_header['index'] = $i; // ----- Store the file position $v_pos_entry = ftell($this->zip_fd); // ----- Look for the specific extract rules $v_extract = false; // ----- Look for extract by name rule if ( (isset($p_options[PCLZIP_OPT_BY_NAME])) && ($p_options[PCLZIP_OPT_BY_NAME] != 0)) { // ----- Look if the filename is in the list for ($j=0; ($j<sizeof($p_options[PCLZIP_OPT_BY_NAME])) && (!$v_extract); $j++) { // ----- Look for a directory if (substr($p_options[PCLZIP_OPT_BY_NAME][$j], -1) == "/") { // ----- Look if the directory is in the filename path if ( (strlen($v_header['stored_filename']) > strlen($p_options[PCLZIP_OPT_BY_NAME][$j])) && (substr($v_header['stored_filename'], 0, strlen($p_options[PCLZIP_OPT_BY_NAME][$j])) == $p_options[PCLZIP_OPT_BY_NAME][$j])) { $v_extract = true; } } // ----- Look for a filename elseif ($v_header['stored_filename'] == $p_options[PCLZIP_OPT_BY_NAME][$j]) { $v_extract = true; } } } // ----- Look for extract by ereg rule // ereg() is deprecated with PHP 5.3 /* else if ( (isset($p_options[PCLZIP_OPT_BY_EREG])) && ($p_options[PCLZIP_OPT_BY_EREG] != "")) { if (ereg($p_options[PCLZIP_OPT_BY_EREG], $v_header['stored_filename'])) { $v_extract = true; } } */ // ----- Look for extract by preg rule else if ( (isset($p_options[PCLZIP_OPT_BY_PREG])) && ($p_options[PCLZIP_OPT_BY_PREG] != "")) { if (preg_match($p_options[PCLZIP_OPT_BY_PREG], $v_header['stored_filename'])) { $v_extract = true; } } // ----- Look for extract by index rule else if ( (isset($p_options[PCLZIP_OPT_BY_INDEX])) && ($p_options[PCLZIP_OPT_BY_INDEX] != 0)) { // ----- Look if the index is in the list for ($j=$j_start; ($j<sizeof($p_options[PCLZIP_OPT_BY_INDEX])) && (!$v_extract); $j++) { if (($i>=$p_options[PCLZIP_OPT_BY_INDEX][$j]['start']) && ($i<=$p_options[PCLZIP_OPT_BY_INDEX][$j]['end'])) { $v_extract = true; } if ($i>=$p_options[PCLZIP_OPT_BY_INDEX][$j]['end']) { $j_start = $j+1; } if ($p_options[PCLZIP_OPT_BY_INDEX][$j]['start']>$i) { break; } } } // ----- Look for no rule, which means extract all the archive else { $v_extract = true; } // ----- Check compression method if ( ($v_extract) && ( ($v_header['compression'] != 8) && ($v_header['compression'] != 0))) { $v_header['status'] = 'unsupported_compression'; // ----- Look for PCLZIP_OPT_STOP_ON_ERROR if ( (isset($p_options[PCLZIP_OPT_STOP_ON_ERROR])) && ($p_options[PCLZIP_OPT_STOP_ON_ERROR]===true)) { $this->privSwapBackMagicQuotes(); PclZip::privErrorLog(PCLZIP_ERR_UNSUPPORTED_COMPRESSION, "Filename '".$v_header['stored_filename']."' is " ."compressed by an unsupported compression " ."method (".$v_header['compression'].") "); return PclZip::errorCode(); } } // ----- Check encrypted files if (($v_extract) && (($v_header['flag'] & 1) == 1)) { $v_header['status'] = 'unsupported_encryption'; // ----- Look for PCLZIP_OPT_STOP_ON_ERROR if ( (isset($p_options[PCLZIP_OPT_STOP_ON_ERROR])) && ($p_options[PCLZIP_OPT_STOP_ON_ERROR]===true)) { $this->privSwapBackMagicQuotes(); PclZip::privErrorLog(PCLZIP_ERR_UNSUPPORTED_ENCRYPTION, "Unsupported encryption for " ." filename '".$v_header['stored_filename'] ."'"); return PclZip::errorCode(); } } // ----- Look for real extraction if (($v_extract) && ($v_header['status'] != 'ok')) { $v_result = $this->privConvertHeader2FileInfo($v_header, $p_file_list[$v_nb_extracted++]); if ($v_result != 1) { $this->privCloseFd(); $this->privSwapBackMagicQuotes(); return $v_result; } $v_extract = false; } // ----- Look for real extraction if ($v_extract) { // ----- Go to the file position @rewind($this->zip_fd); if (@fseek($this->zip_fd, $v_header['offset'])) { // ----- Close the zip file $this->privCloseFd(); $this->privSwapBackMagicQuotes(); // ----- Error log PclZip::privErrorLog(PCLZIP_ERR_INVALID_ARCHIVE_ZIP, 'Invalid archive size'); // ----- Return return PclZip::errorCode(); } // ----- Look for extraction as string if ($p_options[PCLZIP_OPT_EXTRACT_AS_STRING]) { $v_string = ''; // ----- Extracting the file $v_result1 = $this->privExtractFileAsString($v_header, $v_string, $p_options); if ($v_result1 < 1) { $this->privCloseFd(); $this->privSwapBackMagicQuotes(); return $v_result1; } // ----- Get the only interesting attributes if (($v_result = $this->privConvertHeader2FileInfo($v_header, $p_file_list[$v_nb_extracted])) != 1) { // ----- Close the zip file $this->privCloseFd(); $this->privSwapBackMagicQuotes(); return $v_result; } // ----- Set the file content $p_file_list[$v_nb_extracted]['content'] = $v_string; // ----- Next extracted file $v_nb_extracted++; // ----- Look for user callback abort if ($v_result1 == 2) { break; } } // ----- Look for extraction in standard output elseif ( (isset($p_options[PCLZIP_OPT_EXTRACT_IN_OUTPUT])) && ($p_options[PCLZIP_OPT_EXTRACT_IN_OUTPUT])) { // ----- Extracting the file in standard output $v_result1 = $this->privExtractFileInOutput($v_header, $p_options); if ($v_result1 < 1) { $this->privCloseFd(); $this->privSwapBackMagicQuotes(); return $v_result1; } // ----- Get the only interesting attributes if (($v_result = $this->privConvertHeader2FileInfo($v_header, $p_file_list[$v_nb_extracted++])) != 1) { $this->privCloseFd(); $this->privSwapBackMagicQuotes(); return $v_result; } // ----- Look for user callback abort if ($v_result1 == 2) { break; } } // ----- Look for normal extraction else { // ----- Extracting the file $v_result1 = $this->privExtractFile($v_header, $p_path, $p_remove_path, $p_remove_all_path, $p_options); if ($v_result1 < 1) { $this->privCloseFd(); $this->privSwapBackMagicQuotes(); return $v_result1; } // ----- Get the only interesting attributes if (($v_result = $this->privConvertHeader2FileInfo($v_header, $p_file_list[$v_nb_extracted++])) != 1) { // ----- Close the zip file $this->privCloseFd(); $this->privSwapBackMagicQuotes(); return $v_result; } // ----- Look for user callback abort if ($v_result1 == 2) { break; } } } } // ----- Close the zip file $this->privCloseFd(); $this->privSwapBackMagicQuotes(); // ----- Return return $v_result; } // -------------------------------------------------------------------------------- // -------------------------------------------------------------------------------- // Function : privExtractFile() // Description : // Parameters : // Return Values : // // 1 : ... ? // PCLZIP_ERR_USER_ABORTED(2) : User ask for extraction stop in callback // -------------------------------------------------------------------------------- function privExtractFile(&$p_entry, $p_path, $p_remove_path, $p_remove_all_path, &$p_options) { $v_result=1; // ----- Read the file header if (($v_result = $this->privReadFileHeader($v_header)) != 1) { // ----- Return return $v_result; } // ----- Check that the file header is coherent with $p_entry info if ($this->privCheckFileHeaders($v_header, $p_entry) != 1) { // TBC } // ----- Look for all path to remove if ($p_remove_all_path == true) { // ----- Look for folder entry that not need to be extracted if (($p_entry['external']&0x00000010)==0x00000010) { $p_entry['status'] = "filtered"; return $v_result; } // ----- Get the basename of the path $p_entry['filename'] = basename($p_entry['filename']); } // ----- Look for path to remove else if ($p_remove_path != "") { if (PclZipUtilPathInclusion($p_remove_path, $p_entry['filename']) == 2) { // ----- Change the file status $p_entry['status'] = "filtered"; // ----- Return return $v_result; } $p_remove_path_size = strlen($p_remove_path); if (substr($p_entry['filename'], 0, $p_remove_path_size) == $p_remove_path) { // ----- Remove the path $p_entry['filename'] = substr($p_entry['filename'], $p_remove_path_size); } } // ----- Add the path if ($p_path != '') { $p_entry['filename'] = $p_path."/".$p_entry['filename']; } // ----- Check a base_dir_restriction if (isset($p_options[PCLZIP_OPT_EXTRACT_DIR_RESTRICTION])) { $v_inclusion = PclZipUtilPathInclusion($p_options[PCLZIP_OPT_EXTRACT_DIR_RESTRICTION], $p_entry['filename']); if ($v_inclusion == 0) { PclZip::privErrorLog(PCLZIP_ERR_DIRECTORY_RESTRICTION, "Filename '".$p_entry['filename']."' is " ."outside PCLZIP_OPT_EXTRACT_DIR_RESTRICTION"); return PclZip::errorCode(); } } // ----- Look for pre-extract callback if (isset($p_options[PCLZIP_CB_PRE_EXTRACT])) { // ----- Generate a local information $v_local_header = array(); $this->privConvertHeader2FileInfo($p_entry, $v_local_header); // ----- Call the callback // Here I do not use call_user_func() because I need to send a reference to the // header. // eval('$v_result = '.$p_options[PCLZIP_CB_PRE_EXTRACT].'(PCLZIP_CB_PRE_EXTRACT, $v_local_header);'); $v_result = $p_options[PCLZIP_CB_PRE_EXTRACT](PCLZIP_CB_PRE_EXTRACT, $v_local_header); if ($v_result == 0) { // ----- Change the file status $p_entry['status'] = "skipped"; $v_result = 1; } // ----- Look for abort result if ($v_result == 2) { // ----- This status is internal and will be changed in 'skipped' $p_entry['status'] = "aborted"; $v_result = PCLZIP_ERR_USER_ABORTED; } // ----- Update the informations // Only some fields can be modified $p_entry['filename'] = $v_local_header['filename']; } // ----- Look if extraction should be done if ($p_entry['status'] == 'ok') { // ----- Look for specific actions while the file exist if (file_exists($p_entry['filename'])) { // ----- Look if file is a directory if (is_dir($p_entry['filename'])) { // ----- Change the file status $p_entry['status'] = "already_a_directory"; // ----- Look for PCLZIP_OPT_STOP_ON_ERROR // For historical reason first PclZip implementation does not stop // when this kind of error occurs. if ( (isset($p_options[PCLZIP_OPT_STOP_ON_ERROR])) && ($p_options[PCLZIP_OPT_STOP_ON_ERROR]===true)) { PclZip::privErrorLog(PCLZIP_ERR_ALREADY_A_DIRECTORY, "Filename '".$p_entry['filename']."' is " ."already used by an existing directory"); return PclZip::errorCode(); } } // ----- Look if file is write protected else if (!is_writeable($p_entry['filename'])) { // ----- Change the file status $p_entry['status'] = "write_protected"; // ----- Look for PCLZIP_OPT_STOP_ON_ERROR // For historical reason first PclZip implementation does not stop // when this kind of error occurs. if ( (isset($p_options[PCLZIP_OPT_STOP_ON_ERROR])) && ($p_options[PCLZIP_OPT_STOP_ON_ERROR]===true)) { PclZip::privErrorLog(PCLZIP_ERR_WRITE_OPEN_FAIL, "Filename '".$p_entry['filename']."' exists " ."and is write protected"); return PclZip::errorCode(); } } // ----- Look if the extracted file is older else if (filemtime($p_entry['filename']) > $p_entry['mtime']) { // ----- Change the file status if ( (isset($p_options[PCLZIP_OPT_REPLACE_NEWER])) && ($p_options[PCLZIP_OPT_REPLACE_NEWER]===true)) { } else { $p_entry['status'] = "newer_exist"; // ----- Look for PCLZIP_OPT_STOP_ON_ERROR // For historical reason first PclZip implementation does not stop // when this kind of error occurs. if ( (isset($p_options[PCLZIP_OPT_STOP_ON_ERROR])) && ($p_options[PCLZIP_OPT_STOP_ON_ERROR]===true)) { PclZip::privErrorLog(PCLZIP_ERR_WRITE_OPEN_FAIL, "Newer version of '".$p_entry['filename']."' exists " ."and option PCLZIP_OPT_REPLACE_NEWER is not selected"); return PclZip::errorCode(); } } } else { } } // ----- Check the directory availability and create it if necessary else { if ((($p_entry['external']&0x00000010)==0x00000010) || (substr($p_entry['filename'], -1) == '/')) $v_dir_to_check = $p_entry['filename']; else if (!strstr($p_entry['filename'], "/")) $v_dir_to_check = ""; else $v_dir_to_check = dirname($p_entry['filename']); if (($v_result = $this->privDirCheck($v_dir_to_check, (($p_entry['external']&0x00000010)==0x00000010))) != 1) { // ----- Change the file status $p_entry['status'] = "path_creation_fail"; // ----- Return //return $v_result; $v_result = 1; } } } // ----- Look if extraction should be done if ($p_entry['status'] == 'ok') { // ----- Do the extraction (if not a folder) if (!(($p_entry['external']&0x00000010)==0x00000010)) { // ----- Look for not compressed file if ($p_entry['compression'] == 0) { // ----- Opening destination file if (($v_dest_file = @fopen($p_entry['filename'], 'wb')) == 0) { // ----- Change the file status $p_entry['status'] = "write_error"; // ----- Return return $v_result; } // ----- Read the file by PCLZIP_READ_BLOCK_SIZE octets blocks $v_size = $p_entry['compressed_size']; while ($v_size != 0) { $v_read_size = ($v_size < PCLZIP_READ_BLOCK_SIZE ? $v_size : PCLZIP_READ_BLOCK_SIZE); $v_buffer = @fread($this->zip_fd, $v_read_size); /* Try to speed up the code $v_binary_data = pack('a'.$v_read_size, $v_buffer); @fwrite($v_dest_file, $v_binary_data, $v_read_size); */ @fwrite($v_dest_file, $v_buffer, $v_read_size); $v_size -= $v_read_size; } // ----- Closing the destination file fclose($v_dest_file); // ----- Change the file mtime touch($p_entry['filename'], $p_entry['mtime']); } else { // ----- TBC // Need to be finished if (($p_entry['flag'] & 1) == 1) { PclZip::privErrorLog(PCLZIP_ERR_UNSUPPORTED_ENCRYPTION, 'File \''.$p_entry['filename'].'\' is encrypted. Encrypted files are not supported.'); return PclZip::errorCode(); } // ----- Look for using temporary file to unzip if ( (!isset($p_options[PCLZIP_OPT_TEMP_FILE_OFF])) && (isset($p_options[PCLZIP_OPT_TEMP_FILE_ON]) || (isset($p_options[PCLZIP_OPT_TEMP_FILE_THRESHOLD]) && ($p_options[PCLZIP_OPT_TEMP_FILE_THRESHOLD] <= $p_entry['size'])) ) ) { $v_result = $this->privExtractFileUsingTempFile($p_entry, $p_options); if ($v_result < PCLZIP_ERR_NO_ERROR) { return $v_result; } } // ----- Look for extract in memory else { // ----- Read the compressed file in a buffer (one shot) $v_buffer = @fread($this->zip_fd, $p_entry['compressed_size']); // ----- Decompress the file $v_file_content = @gzinflate($v_buffer); unset($v_buffer); if ($v_file_content === FALSE) { // ----- Change the file status // TBC $p_entry['status'] = "error"; return $v_result; } // ----- Opening destination file if (($v_dest_file = @fopen($p_entry['filename'], 'wb')) == 0) { // ----- Change the file status $p_entry['status'] = "write_error"; return $v_result; } // ----- Write the uncompressed data @fwrite($v_dest_file, $v_file_content, $p_entry['size']); unset($v_file_content); // ----- Closing the destination file @fclose($v_dest_file); } // ----- Change the file mtime @touch($p_entry['filename'], $p_entry['mtime']); } // ----- Look for chmod option if (isset($p_options[PCLZIP_OPT_SET_CHMOD])) { // ----- Change the mode of the file @chmod($p_entry['filename'], $p_options[PCLZIP_OPT_SET_CHMOD]); } } } // ----- Change abort status if ($p_entry['status'] == "aborted") { $p_entry['status'] = "skipped"; } // ----- Look for post-extract callback elseif (isset($p_options[PCLZIP_CB_POST_EXTRACT])) { // ----- Generate a local information $v_local_header = array(); $this->privConvertHeader2FileInfo($p_entry, $v_local_header); // ----- Call the callback // Here I do not use call_user_func() because I need to send a reference to the // header. // eval('$v_result = '.$p_options[PCLZIP_CB_POST_EXTRACT].'(PCLZIP_CB_POST_EXTRACT, $v_local_header);'); $v_result = $p_options[PCLZIP_CB_POST_EXTRACT](PCLZIP_CB_POST_EXTRACT, $v_local_header); // ----- Look for abort result if ($v_result == 2) { $v_result = PCLZIP_ERR_USER_ABORTED; } } // ----- Return return $v_result; } // -------------------------------------------------------------------------------- // -------------------------------------------------------------------------------- // Function : privExtractFileUsingTempFile() // Description : // Parameters : // Return Values : // -------------------------------------------------------------------------------- function privExtractFileUsingTempFile(&$p_entry, &$p_options) { $v_result=1; // ----- Creates a temporary file $v_gzip_temp_name = PCLZIP_TEMPORARY_DIR.uniqid('pclzip-').'.gz'; if (($v_dest_file = @fopen($v_gzip_temp_name, "wb")) == 0) { fclose($v_file); PclZip::privErrorLog(PCLZIP_ERR_WRITE_OPEN_FAIL, 'Unable to open temporary file \''.$v_gzip_temp_name.'\' in binary write mode'); return PclZip::errorCode(); } // ----- Write gz file format header $v_binary_data = pack('va1a1Va1a1', 0x8b1f, Chr($p_entry['compression']), Chr(0x00), time(), Chr(0x00), Chr(3)); @fwrite($v_dest_file, $v_binary_data, 10); // ----- Read the file by PCLZIP_READ_BLOCK_SIZE octets blocks $v_size = $p_entry['compressed_size']; while ($v_size != 0) { $v_read_size = ($v_size < PCLZIP_READ_BLOCK_SIZE ? $v_size : PCLZIP_READ_BLOCK_SIZE); $v_buffer = @fread($this->zip_fd, $v_read_size); //$v_binary_data = pack('a'.$v_read_size, $v_buffer); @fwrite($v_dest_file, $v_buffer, $v_read_size); $v_size -= $v_read_size; } // ----- Write gz file format footer $v_binary_data = pack('VV', $p_entry['crc'], $p_entry['size']); @fwrite($v_dest_file, $v_binary_data, 8); // ----- Close the temporary file @fclose($v_dest_file); // ----- Opening destination file if (($v_dest_file = @fopen($p_entry['filename'], 'wb')) == 0) { $p_entry['status'] = "write_error"; return $v_result; } // ----- Open the temporary gz file if (($v_src_file = @gzopen($v_gzip_temp_name, 'rb')) == 0) { @fclose($v_dest_file); $p_entry['status'] = "read_error"; PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, 'Unable to open temporary file \''.$v_gzip_temp_name.'\' in binary read mode'); return PclZip::errorCode(); } // ----- Read the file by PCLZIP_READ_BLOCK_SIZE octets blocks $v_size = $p_entry['size']; while ($v_size != 0) { $v_read_size = ($v_size < PCLZIP_READ_BLOCK_SIZE ? $v_size : PCLZIP_READ_BLOCK_SIZE); $v_buffer = @gzread($v_src_file, $v_read_size); //$v_binary_data = pack('a'.$v_read_size, $v_buffer); @fwrite($v_dest_file, $v_buffer, $v_read_size); $v_size -= $v_read_size; } @fclose($v_dest_file); @gzclose($v_src_file); // ----- Delete the temporary file @unlink($v_gzip_temp_name); // ----- Return return $v_result; } // -------------------------------------------------------------------------------- // -------------------------------------------------------------------------------- // Function : privExtractFileInOutput() // Description : // Parameters : // Return Values : // -------------------------------------------------------------------------------- function privExtractFileInOutput(&$p_entry, &$p_options) { $v_result=1; // ----- Read the file header if (($v_result = $this->privReadFileHeader($v_header)) != 1) { return $v_result; } // ----- Check that the file header is coherent with $p_entry info if ($this->privCheckFileHeaders($v_header, $p_entry) != 1) { // TBC } // ----- Look for pre-extract callback if (isset($p_options[PCLZIP_CB_PRE_EXTRACT])) { // ----- Generate a local information $v_local_header = array(); $this->privConvertHeader2FileInfo($p_entry, $v_local_header); // ----- Call the callback // Here I do not use call_user_func() because I need to send a reference to the // header. // eval('$v_result = '.$p_options[PCLZIP_CB_PRE_EXTRACT].'(PCLZIP_CB_PRE_EXTRACT, $v_local_header);'); $v_result = $p_options[PCLZIP_CB_PRE_EXTRACT](PCLZIP_CB_PRE_EXTRACT, $v_local_header); if ($v_result == 0) { // ----- Change the file status $p_entry['status'] = "skipped"; $v_result = 1; } // ----- Look for abort result if ($v_result == 2) { // ----- This status is internal and will be changed in 'skipped' $p_entry['status'] = "aborted"; $v_result = PCLZIP_ERR_USER_ABORTED; } // ----- Update the informations // Only some fields can be modified $p_entry['filename'] = $v_local_header['filename']; } // ----- Trace // ----- Look if extraction should be done if ($p_entry['status'] == 'ok') { // ----- Do the extraction (if not a folder) if (!(($p_entry['external']&0x00000010)==0x00000010)) { // ----- Look for not compressed file if ($p_entry['compressed_size'] == $p_entry['size']) { // ----- Read the file in a buffer (one shot) $v_buffer = @fread($this->zip_fd, $p_entry['compressed_size']); // ----- Send the file to the output echo $v_buffer; unset($v_buffer); } else { // ----- Read the compressed file in a buffer (one shot) $v_buffer = @fread($this->zip_fd, $p_entry['compressed_size']); // ----- Decompress the file $v_file_content = gzinflate($v_buffer); unset($v_buffer); // ----- Send the file to the output echo $v_file_content; unset($v_file_content); } } } // ----- Change abort status if ($p_entry['status'] == "aborted") { $p_entry['status'] = "skipped"; } // ----- Look for post-extract callback elseif (isset($p_options[PCLZIP_CB_POST_EXTRACT])) { // ----- Generate a local information $v_local_header = array(); $this->privConvertHeader2FileInfo($p_entry, $v_local_header); // ----- Call the callback // Here I do not use call_user_func() because I need to send a reference to the // header. // eval('$v_result = '.$p_options[PCLZIP_CB_POST_EXTRACT].'(PCLZIP_CB_POST_EXTRACT, $v_local_header);'); $v_result = $p_options[PCLZIP_CB_POST_EXTRACT](PCLZIP_CB_POST_EXTRACT, $v_local_header); // ----- Look for abort result if ($v_result == 2) { $v_result = PCLZIP_ERR_USER_ABORTED; } } return $v_result; } // -------------------------------------------------------------------------------- // -------------------------------------------------------------------------------- // Function : privExtractFileAsString() // Description : // Parameters : // Return Values : // -------------------------------------------------------------------------------- function privExtractFileAsString(&$p_entry, &$p_string, &$p_options) { $v_result=1; // ----- Read the file header $v_header = array(); if (($v_result = $this->privReadFileHeader($v_header)) != 1) { // ----- Return return $v_result; } // ----- Check that the file header is coherent with $p_entry info if ($this->privCheckFileHeaders($v_header, $p_entry) != 1) { // TBC } // ----- Look for pre-extract callback if (isset($p_options[PCLZIP_CB_PRE_EXTRACT])) { // ----- Generate a local information $v_local_header = array(); $this->privConvertHeader2FileInfo($p_entry, $v_local_header); // ----- Call the callback // Here I do not use call_user_func() because I need to send a reference to the // header. // eval('$v_result = '.$p_options[PCLZIP_CB_PRE_EXTRACT].'(PCLZIP_CB_PRE_EXTRACT, $v_local_header);'); $v_result = $p_options[PCLZIP_CB_PRE_EXTRACT](PCLZIP_CB_PRE_EXTRACT, $v_local_header); if ($v_result == 0) { // ----- Change the file status $p_entry['status'] = "skipped"; $v_result = 1; } // ----- Look for abort result if ($v_result == 2) { // ----- This status is internal and will be changed in 'skipped' $p_entry['status'] = "aborted"; $v_result = PCLZIP_ERR_USER_ABORTED; } // ----- Update the informations // Only some fields can be modified $p_entry['filename'] = $v_local_header['filename']; } // ----- Look if extraction should be done if ($p_entry['status'] == 'ok') { // ----- Do the extraction (if not a folder) if (!(($p_entry['external']&0x00000010)==0x00000010)) { // ----- Look for not compressed file // if ($p_entry['compressed_size'] == $p_entry['size']) if ($p_entry['compression'] == 0) { // ----- Reading the file $p_string = @fread($this->zip_fd, $p_entry['compressed_size']); } else { // ----- Reading the file $v_data = @fread($this->zip_fd, $p_entry['compressed_size']); // ----- Decompress the file if (($p_string = @gzinflate($v_data)) === FALSE) { // TBC } } // ----- Trace } else { // TBC : error : can not extract a folder in a string } } // ----- Change abort status if ($p_entry['status'] == "aborted") { $p_entry['status'] = "skipped"; } // ----- Look for post-extract callback elseif (isset($p_options[PCLZIP_CB_POST_EXTRACT])) { // ----- Generate a local information $v_local_header = array(); $this->privConvertHeader2FileInfo($p_entry, $v_local_header); // ----- Swap the content to header $v_local_header['content'] = $p_string; $p_string = ''; // ----- Call the callback // Here I do not use call_user_func() because I need to send a reference to the // header. // eval('$v_result = '.$p_options[PCLZIP_CB_POST_EXTRACT].'(PCLZIP_CB_POST_EXTRACT, $v_local_header);'); $v_result = $p_options[PCLZIP_CB_POST_EXTRACT](PCLZIP_CB_POST_EXTRACT, $v_local_header); // ----- Swap back the content to header $p_string = $v_local_header['content']; unset($v_local_header['content']); // ----- Look for abort result if ($v_result == 2) { $v_result = PCLZIP_ERR_USER_ABORTED; } } // ----- Return return $v_result; } // -------------------------------------------------------------------------------- // -------------------------------------------------------------------------------- // Function : privReadFileHeader() // Description : // Parameters : // Return Values : // -------------------------------------------------------------------------------- function privReadFileHeader(&$p_header) { $v_result=1; // ----- Read the 4 bytes signature $v_binary_data = @fread($this->zip_fd, 4); $v_data = unpack('Vid', $v_binary_data); // ----- Check signature if ($v_data['id'] != 0x04034b50) { // ----- Error log PclZip::privErrorLog(PCLZIP_ERR_BAD_FORMAT, 'Invalid archive structure'); // ----- Return return PclZip::errorCode(); } // ----- Read the first 42 bytes of the header $v_binary_data = fread($this->zip_fd, 26); // ----- Look for invalid block size if (strlen($v_binary_data) != 26) { $p_header['filename'] = ""; $p_header['status'] = "invalid_header"; // ----- Error log PclZip::privErrorLog(PCLZIP_ERR_BAD_FORMAT, "Invalid block size : ".strlen($v_binary_data)); // ----- Return return PclZip::errorCode(); } // ----- Extract the values $v_data = unpack('vversion/vflag/vcompression/vmtime/vmdate/Vcrc/Vcompressed_size/Vsize/vfilename_len/vextra_len', $v_binary_data); // ----- Get filename $p_header['filename'] = fread($this->zip_fd, $v_data['filename_len']); // ----- Get extra_fields if ($v_data['extra_len'] != 0) { $p_header['extra'] = fread($this->zip_fd, $v_data['extra_len']); } else { $p_header['extra'] = ''; } // ----- Extract properties $p_header['version_extracted'] = $v_data['version']; $p_header['compression'] = $v_data['compression']; $p_header['size'] = $v_data['size']; $p_header['compressed_size'] = $v_data['compressed_size']; $p_header['crc'] = $v_data['crc']; $p_header['flag'] = $v_data['flag']; $p_header['filename_len'] = $v_data['filename_len']; // ----- Recuperate date in UNIX format $p_header['mdate'] = $v_data['mdate']; $p_header['mtime'] = $v_data['mtime']; if ($p_header['mdate'] && $p_header['mtime']) { // ----- Extract time $v_hour = ($p_header['mtime'] & 0xF800) >> 11; $v_minute = ($p_header['mtime'] & 0x07E0) >> 5; $v_seconde = ($p_header['mtime'] & 0x001F)*2; // ----- Extract date $v_year = (($p_header['mdate'] & 0xFE00) >> 9) + 1980; $v_month = ($p_header['mdate'] & 0x01E0) >> 5; $v_day = $p_header['mdate'] & 0x001F; // ----- Get UNIX date format $p_header['mtime'] = @mktime($v_hour, $v_minute, $v_seconde, $v_month, $v_day, $v_year); } else { $p_header['mtime'] = time(); } // TBC //for(reset($v_data); $key = key($v_data); next($v_data)) { //} // ----- Set the stored filename $p_header['stored_filename'] = $p_header['filename']; // ----- Set the status field $p_header['status'] = "ok"; // ----- Return return $v_result; } // -------------------------------------------------------------------------------- // -------------------------------------------------------------------------------- // Function : privReadCentralFileHeader() // Description : // Parameters : // Return Values : // -------------------------------------------------------------------------------- function privReadCentralFileHeader(&$p_header) { $v_result=1; // ----- Read the 4 bytes signature $v_binary_data = @fread($this->zip_fd, 4); $v_data = unpack('Vid', $v_binary_data); // ----- Check signature if ($v_data['id'] != 0x02014b50) { // ----- Error log PclZip::privErrorLog(PCLZIP_ERR_BAD_FORMAT, 'Invalid archive structure'); // ----- Return return PclZip::errorCode(); } // ----- Read the first 42 bytes of the header $v_binary_data = fread($this->zip_fd, 42); // ----- Look for invalid block size if (strlen($v_binary_data) != 42) { $p_header['filename'] = ""; $p_header['status'] = "invalid_header"; // ----- Error log PclZip::privErrorLog(PCLZIP_ERR_BAD_FORMAT, "Invalid block size : ".strlen($v_binary_data)); // ----- Return return PclZip::errorCode(); } // ----- Extract the values $p_header = unpack('vversion/vversion_extracted/vflag/vcompression/vmtime/vmdate/Vcrc/Vcompressed_size/Vsize/vfilename_len/vextra_len/vcomment_len/vdisk/vinternal/Vexternal/Voffset', $v_binary_data); // ----- Get filename if ($p_header['filename_len'] != 0) $p_header['filename'] = fread($this->zip_fd, $p_header['filename_len']); else $p_header['filename'] = ''; // ----- Get extra if ($p_header['extra_len'] != 0) $p_header['extra'] = fread($this->zip_fd, $p_header['extra_len']); else $p_header['extra'] = ''; // ----- Get comment if ($p_header['comment_len'] != 0) $p_header['comment'] = fread($this->zip_fd, $p_header['comment_len']); else $p_header['comment'] = ''; // ----- Extract properties // ----- Recuperate date in UNIX format //if ($p_header['mdate'] && $p_header['mtime']) // TBC : bug : this was ignoring time with 0/0/0 if (1) { // ----- Extract time $v_hour = ($p_header['mtime'] & 0xF800) >> 11; $v_minute = ($p_header['mtime'] & 0x07E0) >> 5; $v_seconde = ($p_header['mtime'] & 0x001F)*2; // ----- Extract date $v_year = (($p_header['mdate'] & 0xFE00) >> 9) + 1980; $v_month = ($p_header['mdate'] & 0x01E0) >> 5; $v_day = $p_header['mdate'] & 0x001F; // ----- Get UNIX date format $p_header['mtime'] = @mktime($v_hour, $v_minute, $v_seconde, $v_month, $v_day, $v_year); } else { $p_header['mtime'] = time(); } // ----- Set the stored filename $p_header['stored_filename'] = $p_header['filename']; // ----- Set default status to ok $p_header['status'] = 'ok'; // ----- Look if it is a directory if (substr($p_header['filename'], -1) == '/') { //$p_header['external'] = 0x41FF0010; $p_header['external'] = 0x00000010; } // ----- Return return $v_result; } // -------------------------------------------------------------------------------- // -------------------------------------------------------------------------------- // Function : privCheckFileHeaders() // Description : // Parameters : // Return Values : // 1 on success, // 0 on error; // -------------------------------------------------------------------------------- function privCheckFileHeaders(&$p_local_header, &$p_central_header) { $v_result=1; // ----- Check the static values // TBC if ($p_local_header['filename'] != $p_central_header['filename']) { } if ($p_local_header['version_extracted'] != $p_central_header['version_extracted']) { } if ($p_local_header['flag'] != $p_central_header['flag']) { } if ($p_local_header['compression'] != $p_central_header['compression']) { } if ($p_local_header['mtime'] != $p_central_header['mtime']) { } if ($p_local_header['filename_len'] != $p_central_header['filename_len']) { } // ----- Look for flag bit 3 if (($p_local_header['flag'] & 8) == 8) { $p_local_header['size'] = $p_central_header['size']; $p_local_header['compressed_size'] = $p_central_header['compressed_size']; $p_local_header['crc'] = $p_central_header['crc']; } // ----- Return return $v_result; } // -------------------------------------------------------------------------------- // -------------------------------------------------------------------------------- // Function : privReadEndCentralDir() // Description : // Parameters : // Return Values : // -------------------------------------------------------------------------------- function privReadEndCentralDir(&$p_central_dir) { $v_result=1; // ----- Go to the end of the zip file $v_size = filesize($this->zipname); @fseek($this->zip_fd, $v_size); if (@ftell($this->zip_fd) != $v_size) { // ----- Error log PclZip::privErrorLog(PCLZIP_ERR_BAD_FORMAT, 'Unable to go to the end of the archive \''.$this->zipname.'\''); // ----- Return return PclZip::errorCode(); } // ----- First try : look if this is an archive with no commentaries (most of the time) // in this case the end of central dir is at 22 bytes of the file end $v_found = 0; if ($v_size > 26) { @fseek($this->zip_fd, $v_size-22); if (($v_pos = @ftell($this->zip_fd)) != ($v_size-22)) { // ----- Error log PclZip::privErrorLog(PCLZIP_ERR_BAD_FORMAT, 'Unable to seek back to the middle of the archive \''.$this->zipname.'\''); // ----- Return return PclZip::errorCode(); } // ----- Read for bytes $v_binary_data = @fread($this->zip_fd, 4); $v_data = @unpack('Vid', $v_binary_data); // ----- Check signature if ($v_data['id'] == 0x06054b50) { $v_found = 1; } $v_pos = ftell($this->zip_fd); } // ----- Go back to the maximum possible size of the Central Dir End Record if (!$v_found) { $v_maximum_size = 65557; // 0xFFFF + 22; if ($v_maximum_size > $v_size) $v_maximum_size = $v_size; @fseek($this->zip_fd, $v_size-$v_maximum_size); if (@ftell($this->zip_fd) != ($v_size-$v_maximum_size)) { // ----- Error log PclZip::privErrorLog(PCLZIP_ERR_BAD_FORMAT, 'Unable to seek back to the middle of the archive \''.$this->zipname.'\''); // ----- Return return PclZip::errorCode(); } // ----- Read byte per byte in order to find the signature $v_pos = ftell($this->zip_fd); $v_bytes = 0x00000000; while ($v_pos < $v_size) { // ----- Read a byte $v_byte = @fread($this->zip_fd, 1); // ----- Add the byte //$v_bytes = ($v_bytes << 8) | Ord($v_byte); // Note we mask the old value down such that once shifted we can never end up with more than a 32bit number // Otherwise on systems where we have 64bit integers the check below for the magic number will fail. $v_bytes = ( ($v_bytes & 0xFFFFFF) << 8) | Ord($v_byte); // ----- Compare the bytes if ($v_bytes == 0x504b0506) { $v_pos++; break; } $v_pos++; } // ----- Look if not found end of central dir if ($v_pos == $v_size) { // ----- Error log PclZip::privErrorLog(PCLZIP_ERR_BAD_FORMAT, "Unable to find End of Central Dir Record signature"); // ----- Return return PclZip::errorCode(); } } // ----- Read the first 18 bytes of the header $v_binary_data = fread($this->zip_fd, 18); // ----- Look for invalid block size if (strlen($v_binary_data) != 18) { // ----- Error log PclZip::privErrorLog(PCLZIP_ERR_BAD_FORMAT, "Invalid End of Central Dir Record size : ".strlen($v_binary_data)); // ----- Return return PclZip::errorCode(); } // ----- Extract the values $v_data = unpack('vdisk/vdisk_start/vdisk_entries/ventries/Vsize/Voffset/vcomment_size', $v_binary_data); // ----- Check the global size if (($v_pos + $v_data['comment_size'] + 18) != $v_size) { // ----- Removed in release 2.2 see readme file // The check of the file size is a little too strict. // Some bugs where found when a zip is encrypted/decrypted with 'crypt'. // While decrypted, zip has training 0 bytes if (0) { // ----- Error log PclZip::privErrorLog(PCLZIP_ERR_BAD_FORMAT, 'The central dir is not at the end of the archive.' .' Some trailing bytes exists after the archive.'); // ----- Return return PclZip::errorCode(); } } // ----- Get comment if ($v_data['comment_size'] != 0) { $p_central_dir['comment'] = fread($this->zip_fd, $v_data['comment_size']); } else $p_central_dir['comment'] = ''; $p_central_dir['entries'] = $v_data['entries']; $p_central_dir['disk_entries'] = $v_data['disk_entries']; $p_central_dir['offset'] = $v_data['offset']; $p_central_dir['size'] = $v_data['size']; $p_central_dir['disk'] = $v_data['disk']; $p_central_dir['disk_start'] = $v_data['disk_start']; // TBC //for(reset($p_central_dir); $key = key($p_central_dir); next($p_central_dir)) { //} // ----- Return return $v_result; } // -------------------------------------------------------------------------------- // -------------------------------------------------------------------------------- // Function : privDeleteByRule() // Description : // Parameters : // Return Values : // -------------------------------------------------------------------------------- function privDeleteByRule(&$p_result_list, &$p_options) { $v_result=1; $v_list_detail = array(); // ----- Open the zip file if (($v_result=$this->privOpenFd('rb')) != 1) { // ----- Return return $v_result; } // ----- Read the central directory informations $v_central_dir = array(); if (($v_result = $this->privReadEndCentralDir($v_central_dir)) != 1) { $this->privCloseFd(); return $v_result; } // ----- Go to beginning of File @rewind($this->zip_fd); // ----- Scan all the files // ----- Start at beginning of Central Dir $v_pos_entry = $v_central_dir['offset']; @rewind($this->zip_fd); if (@fseek($this->zip_fd, $v_pos_entry)) { // ----- Close the zip file $this->privCloseFd(); // ----- Error log PclZip::privErrorLog(PCLZIP_ERR_INVALID_ARCHIVE_ZIP, 'Invalid archive size'); // ----- Return return PclZip::errorCode(); } // ----- Read each entry $v_header_list = array(); $j_start = 0; for ($i=0, $v_nb_extracted=0; $i<$v_central_dir['entries']; $i++) { // ----- Read the file header $v_header_list[$v_nb_extracted] = array(); if (($v_result = $this->privReadCentralFileHeader($v_header_list[$v_nb_extracted])) != 1) { // ----- Close the zip file $this->privCloseFd(); return $v_result; } // ----- Store the index $v_header_list[$v_nb_extracted]['index'] = $i; // ----- Look for the specific extract rules $v_found = false; // ----- Look for extract by name rule if ( (isset($p_options[PCLZIP_OPT_BY_NAME])) && ($p_options[PCLZIP_OPT_BY_NAME] != 0)) { // ----- Look if the filename is in the list for ($j=0; ($j<sizeof($p_options[PCLZIP_OPT_BY_NAME])) && (!$v_found); $j++) { // ----- Look for a directory if (substr($p_options[PCLZIP_OPT_BY_NAME][$j], -1) == "/") { // ----- Look if the directory is in the filename path if ( (strlen($v_header_list[$v_nb_extracted]['stored_filename']) > strlen($p_options[PCLZIP_OPT_BY_NAME][$j])) && (substr($v_header_list[$v_nb_extracted]['stored_filename'], 0, strlen($p_options[PCLZIP_OPT_BY_NAME][$j])) == $p_options[PCLZIP_OPT_BY_NAME][$j])) { $v_found = true; } elseif ( (($v_header_list[$v_nb_extracted]['external']&0x00000010)==0x00000010) /* Indicates a folder */ && ($v_header_list[$v_nb_extracted]['stored_filename'].'/' == $p_options[PCLZIP_OPT_BY_NAME][$j])) { $v_found = true; } } // ----- Look for a filename elseif ($v_header_list[$v_nb_extracted]['stored_filename'] == $p_options[PCLZIP_OPT_BY_NAME][$j]) { $v_found = true; } } } // ----- Look for extract by ereg rule // ereg() is deprecated with PHP 5.3 /* else if ( (isset($p_options[PCLZIP_OPT_BY_EREG])) && ($p_options[PCLZIP_OPT_BY_EREG] != "")) { if (ereg($p_options[PCLZIP_OPT_BY_EREG], $v_header_list[$v_nb_extracted]['stored_filename'])) { $v_found = true; } } */ // ----- Look for extract by preg rule else if ( (isset($p_options[PCLZIP_OPT_BY_PREG])) && ($p_options[PCLZIP_OPT_BY_PREG] != "")) { if (preg_match($p_options[PCLZIP_OPT_BY_PREG], $v_header_list[$v_nb_extracted]['stored_filename'])) { $v_found = true; } } // ----- Look for extract by index rule else if ( (isset($p_options[PCLZIP_OPT_BY_INDEX])) && ($p_options[PCLZIP_OPT_BY_INDEX] != 0)) { // ----- Look if the index is in the list for ($j=$j_start; ($j<sizeof($p_options[PCLZIP_OPT_BY_INDEX])) && (!$v_found); $j++) { if (($i>=$p_options[PCLZIP_OPT_BY_INDEX][$j]['start']) && ($i<=$p_options[PCLZIP_OPT_BY_INDEX][$j]['end'])) { $v_found = true; } if ($i>=$p_options[PCLZIP_OPT_BY_INDEX][$j]['end']) { $j_start = $j+1; } if ($p_options[PCLZIP_OPT_BY_INDEX][$j]['start']>$i) { break; } } } else { $v_found = true; } // ----- Look for deletion if ($v_found) { unset($v_header_list[$v_nb_extracted]); } else { $v_nb_extracted++; } } // ----- Look if something need to be deleted if ($v_nb_extracted > 0) { // ----- Creates a temporay file $v_zip_temp_name = PCLZIP_TEMPORARY_DIR.uniqid('pclzip-').'.tmp'; // ----- Creates a temporary zip archive $v_temp_zip = new PclZip($v_zip_temp_name); // ----- Open the temporary zip file in write mode if (($v_result = $v_temp_zip->privOpenFd('wb')) != 1) { $this->privCloseFd(); // ----- Return return $v_result; } // ----- Look which file need to be kept for ($i=0; $i<sizeof($v_header_list); $i++) { // ----- Calculate the position of the header @rewind($this->zip_fd); if (@fseek($this->zip_fd, $v_header_list[$i]['offset'])) { // ----- Close the zip file $this->privCloseFd(); $v_temp_zip->privCloseFd(); @unlink($v_zip_temp_name); // ----- Error log PclZip::privErrorLog(PCLZIP_ERR_INVALID_ARCHIVE_ZIP, 'Invalid archive size'); // ----- Return return PclZip::errorCode(); } // ----- Read the file header $v_local_header = array(); if (($v_result = $this->privReadFileHeader($v_local_header)) != 1) { // ----- Close the zip file $this->privCloseFd(); $v_temp_zip->privCloseFd(); @unlink($v_zip_temp_name); // ----- Return return $v_result; } // ----- Check that local file header is same as central file header if ($this->privCheckFileHeaders($v_local_header, $v_header_list[$i]) != 1) { // TBC } unset($v_local_header); // ----- Write the file header if (($v_result = $v_temp_zip->privWriteFileHeader($v_header_list[$i])) != 1) { // ----- Close the zip file $this->privCloseFd(); $v_temp_zip->privCloseFd(); @unlink($v_zip_temp_name); // ----- Return return $v_result; } // ----- Read/write the data block if (($v_result = PclZipUtilCopyBlock($this->zip_fd, $v_temp_zip->zip_fd, $v_header_list[$i]['compressed_size'])) != 1) { // ----- Close the zip file $this->privCloseFd(); $v_temp_zip->privCloseFd(); @unlink($v_zip_temp_name); // ----- Return return $v_result; } } // ----- Store the offset of the central dir $v_offset = @ftell($v_temp_zip->zip_fd); // ----- Re-Create the Central Dir files header for ($i=0; $i<sizeof($v_header_list); $i++) { // ----- Create the file header if (($v_result = $v_temp_zip->privWriteCentralFileHeader($v_header_list[$i])) != 1) { $v_temp_zip->privCloseFd(); $this->privCloseFd(); @unlink($v_zip_temp_name); // ----- Return return $v_result; } // ----- Transform the header to a 'usable' info $v_temp_zip->privConvertHeader2FileInfo($v_header_list[$i], $p_result_list[$i]); } // ----- Zip file comment $v_comment = ''; if (isset($p_options[PCLZIP_OPT_COMMENT])) { $v_comment = $p_options[PCLZIP_OPT_COMMENT]; } // ----- Calculate the size of the central header $v_size = @ftell($v_temp_zip->zip_fd)-$v_offset; // ----- Create the central dir footer if (($v_result = $v_temp_zip->privWriteCentralHeader(sizeof($v_header_list), $v_size, $v_offset, $v_comment)) != 1) { // ----- Reset the file list unset($v_header_list); $v_temp_zip->privCloseFd(); $this->privCloseFd(); @unlink($v_zip_temp_name); // ----- Return return $v_result; } // ----- Close $v_temp_zip->privCloseFd(); $this->privCloseFd(); // ----- Delete the zip file // TBC : I should test the result ... @unlink($this->zipname); // ----- Rename the temporary file // TBC : I should test the result ... //@rename($v_zip_temp_name, $this->zipname); PclZipUtilRename($v_zip_temp_name, $this->zipname); // ----- Destroy the temporary archive unset($v_temp_zip); } // ----- Remove every files : reset the file else if ($v_central_dir['entries'] != 0) { $this->privCloseFd(); if (($v_result = $this->privOpenFd('wb')) != 1) { return $v_result; } if (($v_result = $this->privWriteCentralHeader(0, 0, 0, '')) != 1) { return $v_result; } $this->privCloseFd(); } // ----- Return return $v_result; } // -------------------------------------------------------------------------------- // -------------------------------------------------------------------------------- // Function : privDirCheck() // Description : // Check if a directory exists, if not it creates it and all the parents directory // which may be useful. // Parameters : // $p_dir : Directory path to check. // Return Values : // 1 : OK // -1 : Unable to create directory // -------------------------------------------------------------------------------- function privDirCheck($p_dir, $p_is_dir=false) { $v_result = 1; // ----- Remove the final '/' if (($p_is_dir) && (substr($p_dir, -1)=='/')) { $p_dir = substr($p_dir, 0, strlen($p_dir)-1); } // ----- Check the directory availability if ((is_dir($p_dir)) || ($p_dir == "")) { return 1; } // ----- Extract parent directory $p_parent_dir = dirname($p_dir); // ----- Just a check if ($p_parent_dir != $p_dir) { // ----- Look for parent directory if ($p_parent_dir != "") { if (($v_result = $this->privDirCheck($p_parent_dir)) != 1) { return $v_result; } } } // ----- Create the directory if (!@mkdir($p_dir, 0777)) { // ----- Error log PclZip::privErrorLog(PCLZIP_ERR_DIR_CREATE_FAIL, "Unable to create directory '$p_dir'"); // ----- Return return PclZip::errorCode(); } // ----- Return return $v_result; } // -------------------------------------------------------------------------------- // -------------------------------------------------------------------------------- // Function : privMerge() // Description : // If $p_archive_to_add does not exist, the function exit with a success result. // Parameters : // Return Values : // -------------------------------------------------------------------------------- function privMerge(&$p_archive_to_add) { $v_result=1; // ----- Look if the archive_to_add exists if (!is_file($p_archive_to_add->zipname)) { // ----- Nothing to merge, so merge is a success $v_result = 1; // ----- Return return $v_result; } // ----- Look if the archive exists if (!is_file($this->zipname)) { // ----- Do a duplicate $v_result = $this->privDuplicate($p_archive_to_add->zipname); // ----- Return return $v_result; } // ----- Open the zip file if (($v_result=$this->privOpenFd('rb')) != 1) { // ----- Return return $v_result; } // ----- Read the central directory informations $v_central_dir = array(); if (($v_result = $this->privReadEndCentralDir($v_central_dir)) != 1) { $this->privCloseFd(); return $v_result; } // ----- Go to beginning of File @rewind($this->zip_fd); // ----- Open the archive_to_add file if (($v_result=$p_archive_to_add->privOpenFd('rb')) != 1) { $this->privCloseFd(); // ----- Return return $v_result; } // ----- Read the central directory informations $v_central_dir_to_add = array(); if (($v_result = $p_archive_to_add->privReadEndCentralDir($v_central_dir_to_add)) != 1) { $this->privCloseFd(); $p_archive_to_add->privCloseFd(); return $v_result; } // ----- Go to beginning of File @rewind($p_archive_to_add->zip_fd); // ----- Creates a temporay file $v_zip_temp_name = PCLZIP_TEMPORARY_DIR.uniqid('pclzip-').'.tmp'; // ----- Open the temporary file in write mode if (($v_zip_temp_fd = @fopen($v_zip_temp_name, 'wb')) == 0) { $this->privCloseFd(); $p_archive_to_add->privCloseFd(); PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, 'Unable to open temporary file \''.$v_zip_temp_name.'\' in binary write mode'); // ----- Return return PclZip::errorCode(); } // ----- Copy the files from the archive to the temporary file // TBC : Here I should better append the file and go back to erase the central dir $v_size = $v_central_dir['offset']; while ($v_size != 0) { $v_read_size = ($v_size < PCLZIP_READ_BLOCK_SIZE ? $v_size : PCLZIP_READ_BLOCK_SIZE); $v_buffer = fread($this->zip_fd, $v_read_size); @fwrite($v_zip_temp_fd, $v_buffer, $v_read_size); $v_size -= $v_read_size; } // ----- Copy the files from the archive_to_add into the temporary file $v_size = $v_central_dir_to_add['offset']; while ($v_size != 0) { $v_read_size = ($v_size < PCLZIP_READ_BLOCK_SIZE ? $v_size : PCLZIP_READ_BLOCK_SIZE); $v_buffer = fread($p_archive_to_add->zip_fd, $v_read_size); @fwrite($v_zip_temp_fd, $v_buffer, $v_read_size); $v_size -= $v_read_size; } // ----- Store the offset of the central dir $v_offset = @ftell($v_zip_temp_fd); // ----- Copy the block of file headers from the old archive $v_size = $v_central_dir['size']; while ($v_size != 0) { $v_read_size = ($v_size < PCLZIP_READ_BLOCK_SIZE ? $v_size : PCLZIP_READ_BLOCK_SIZE); $v_buffer = @fread($this->zip_fd, $v_read_size); @fwrite($v_zip_temp_fd, $v_buffer, $v_read_size); $v_size -= $v_read_size; } // ----- Copy the block of file headers from the archive_to_add $v_size = $v_central_dir_to_add['size']; while ($v_size != 0) { $v_read_size = ($v_size < PCLZIP_READ_BLOCK_SIZE ? $v_size : PCLZIP_READ_BLOCK_SIZE); $v_buffer = @fread($p_archive_to_add->zip_fd, $v_read_size); @fwrite($v_zip_temp_fd, $v_buffer, $v_read_size); $v_size -= $v_read_size; } // ----- Merge the file comments $v_comment = $v_central_dir['comment'].' '.$v_central_dir_to_add['comment']; // ----- Calculate the size of the (new) central header $v_size = @ftell($v_zip_temp_fd)-$v_offset; // ----- Swap the file descriptor // Here is a trick : I swap the temporary fd with the zip fd, in order to use // the following methods on the temporary fil and not the real archive fd $v_swap = $this->zip_fd; $this->zip_fd = $v_zip_temp_fd; $v_zip_temp_fd = $v_swap; // ----- Create the central dir footer if (($v_result = $this->privWriteCentralHeader($v_central_dir['entries']+$v_central_dir_to_add['entries'], $v_size, $v_offset, $v_comment)) != 1) { $this->privCloseFd(); $p_archive_to_add->privCloseFd(); @fclose($v_zip_temp_fd); $this->zip_fd = null; // ----- Reset the file list unset($v_header_list); // ----- Return return $v_result; } // ----- Swap back the file descriptor $v_swap = $this->zip_fd; $this->zip_fd = $v_zip_temp_fd; $v_zip_temp_fd = $v_swap; // ----- Close $this->privCloseFd(); $p_archive_to_add->privCloseFd(); // ----- Close the temporary file @fclose($v_zip_temp_fd); // ----- Delete the zip file // TBC : I should test the result ... @unlink($this->zipname); // ----- Rename the temporary file // TBC : I should test the result ... //@rename($v_zip_temp_name, $this->zipname); PclZipUtilRename($v_zip_temp_name, $this->zipname); // ----- Return return $v_result; } // -------------------------------------------------------------------------------- // -------------------------------------------------------------------------------- // Function : privDuplicate() // Description : // Parameters : // Return Values : // -------------------------------------------------------------------------------- function privDuplicate($p_archive_filename) { $v_result=1; // ----- Look if the $p_archive_filename exists if (!is_file($p_archive_filename)) { // ----- Nothing to duplicate, so duplicate is a success. $v_result = 1; // ----- Return return $v_result; } // ----- Open the zip file if (($v_result=$this->privOpenFd('wb')) != 1) { // ----- Return return $v_result; } // ----- Open the temporary file in write mode if (($v_zip_temp_fd = @fopen($p_archive_filename, 'rb')) == 0) { $this->privCloseFd(); PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, 'Unable to open archive file \''.$p_archive_filename.'\' in binary write mode'); // ----- Return return PclZip::errorCode(); } // ----- Copy the files from the archive to the temporary file // TBC : Here I should better append the file and go back to erase the central dir $v_size = filesize($p_archive_filename); while ($v_size != 0) { $v_read_size = ($v_size < PCLZIP_READ_BLOCK_SIZE ? $v_size : PCLZIP_READ_BLOCK_SIZE); $v_buffer = fread($v_zip_temp_fd, $v_read_size); @fwrite($this->zip_fd, $v_buffer, $v_read_size); $v_size -= $v_read_size; } // ----- Close $this->privCloseFd(); // ----- Close the temporary file @fclose($v_zip_temp_fd); // ----- Return return $v_result; } // -------------------------------------------------------------------------------- // -------------------------------------------------------------------------------- // Function : privErrorLog() // Description : // Parameters : // -------------------------------------------------------------------------------- function privErrorLog($p_error_code=0, $p_error_string='') { if (PCLZIP_ERROR_EXTERNAL == 1) { PclError($p_error_code, $p_error_string); } else { $this->error_code = $p_error_code; $this->error_string = $p_error_string; } } // -------------------------------------------------------------------------------- // -------------------------------------------------------------------------------- // Function : privErrorReset() // Description : // Parameters : // -------------------------------------------------------------------------------- function privErrorReset() { if (PCLZIP_ERROR_EXTERNAL == 1) { PclErrorReset(); } else { $this->error_code = 0; $this->error_string = ''; } } // -------------------------------------------------------------------------------- // -------------------------------------------------------------------------------- // Function : privDisableMagicQuotes() // Description : // Parameters : // Return Values : // -------------------------------------------------------------------------------- function privDisableMagicQuotes() { $v_result=1; // ----- Look if function exists if ( (!function_exists("get_magic_quotes_runtime")) || (!function_exists("set_magic_quotes_runtime"))) { return $v_result; } // ----- Look if already done if ($this->magic_quotes_status != -1) { return $v_result; } // ----- Get and memorize the magic_quote value $this->magic_quotes_status = @get_magic_quotes_runtime(); // ----- Disable magic_quotes if ($this->magic_quotes_status == 1) { @set_magic_quotes_runtime(0); } // ----- Return return $v_result; } // -------------------------------------------------------------------------------- // -------------------------------------------------------------------------------- // Function : privSwapBackMagicQuotes() // Description : // Parameters : // Return Values : // -------------------------------------------------------------------------------- function privSwapBackMagicQuotes() { $v_result=1; // ----- Look if function exists if ( (!function_exists("get_magic_quotes_runtime")) || (!function_exists("set_magic_quotes_runtime"))) { return $v_result; } // ----- Look if something to do if ($this->magic_quotes_status != -1) { return $v_result; } // ----- Swap back magic_quotes if ($this->magic_quotes_status == 1) { @set_magic_quotes_runtime($this->magic_quotes_status); } // ----- Return return $v_result; } // -------------------------------------------------------------------------------- } // End of class // -------------------------------------------------------------------------------- // -------------------------------------------------------------------------------- // Function : PclZipUtilPathReduction() // Description : // Parameters : // Return Values : // -------------------------------------------------------------------------------- function PclZipUtilPathReduction($p_dir) { $v_result = ""; // ----- Look for not empty path if ($p_dir != "") { // ----- Explode path by directory names $v_list = explode("/", $p_dir); // ----- Study directories from last to first $v_skip = 0; for ($i=sizeof($v_list)-1; $i>=0; $i--) { // ----- Look for current path if ($v_list[$i] == ".") { // ----- Ignore this directory // Should be the first $i=0, but no check is done } else if ($v_list[$i] == "..") { $v_skip++; } else if ($v_list[$i] == "") { // ----- First '/' i.e. root slash if ($i == 0) { $v_result = "/".$v_result; if ($v_skip > 0) { // ----- It is an invalid path, so the path is not modified // TBC $v_result = $p_dir; $v_skip = 0; } } // ----- Last '/' i.e. indicates a directory else if ($i == (sizeof($v_list)-1)) { $v_result = $v_list[$i]; } // ----- Double '/' inside the path else { // ----- Ignore only the double '//' in path, // but not the first and last '/' } } else { // ----- Look for item to skip if ($v_skip > 0) { $v_skip--; } else { $v_result = $v_list[$i].($i!=(sizeof($v_list)-1)?"/".$v_result:""); } } } // ----- Look for skip if ($v_skip > 0) { while ($v_skip > 0) { $v_result = '../'.$v_result; $v_skip--; } } } // ----- Return return $v_result; } // -------------------------------------------------------------------------------- // -------------------------------------------------------------------------------- // Function : PclZipUtilPathInclusion() // Description : // This function indicates if the path $p_path is under the $p_dir tree. Or, // said in an other way, if the file or sub-dir $p_path is inside the dir // $p_dir. // The function indicates also if the path is exactly the same as the dir. // This function supports path with duplicated '/' like '//', but does not // support '.' or '..' statements. // Parameters : // Return Values : // 0 if $p_path is not inside directory $p_dir // 1 if $p_path is inside directory $p_dir // 2 if $p_path is exactly the same as $p_dir // -------------------------------------------------------------------------------- function PclZipUtilPathInclusion($p_dir, $p_path) { $v_result = 1; // ----- Look for path beginning by ./ if ( ($p_dir == '.') || ((strlen($p_dir) >=2) && (substr($p_dir, 0, 2) == './'))) { $p_dir = PclZipUtilTranslateWinPath(getcwd(), FALSE).'/'.substr($p_dir, 1); } if ( ($p_path == '.') || ((strlen($p_path) >=2) && (substr($p_path, 0, 2) == './'))) { $p_path = PclZipUtilTranslateWinPath(getcwd(), FALSE).'/'.substr($p_path, 1); } // ----- Explode dir and path by directory separator $v_list_dir = explode("/", $p_dir); $v_list_dir_size = sizeof($v_list_dir); $v_list_path = explode("/", $p_path); $v_list_path_size = sizeof($v_list_path); // ----- Study directories paths $i = 0; $j = 0; while (($i < $v_list_dir_size) && ($j < $v_list_path_size) && ($v_result)) { // ----- Look for empty dir (path reduction) if ($v_list_dir[$i] == '') { $i++; continue; } if ($v_list_path[$j] == '') { $j++; continue; } // ----- Compare the items if (($v_list_dir[$i] != $v_list_path[$j]) && ($v_list_dir[$i] != '') && ( $v_list_path[$j] != '')) { $v_result = 0; } // ----- Next items $i++; $j++; } // ----- Look if everything seems to be the same if ($v_result) { // ----- Skip all the empty items while (($j < $v_list_path_size) && ($v_list_path[$j] == '')) $j++; while (($i < $v_list_dir_size) && ($v_list_dir[$i] == '')) $i++; if (($i >= $v_list_dir_size) && ($j >= $v_list_path_size)) { // ----- There are exactly the same $v_result = 2; } else if ($i < $v_list_dir_size) { // ----- The path is shorter than the dir $v_result = 0; } } // ----- Return return $v_result; } // -------------------------------------------------------------------------------- // -------------------------------------------------------------------------------- // Function : PclZipUtilCopyBlock() // Description : // Parameters : // $p_mode : read/write compression mode // 0 : src & dest normal // 1 : src gzip, dest normal // 2 : src normal, dest gzip // 3 : src & dest gzip // Return Values : // -------------------------------------------------------------------------------- function PclZipUtilCopyBlock($p_src, $p_dest, $p_size, $p_mode=0) { $v_result = 1; if ($p_mode==0) { while ($p_size != 0) { $v_read_size = ($p_size < PCLZIP_READ_BLOCK_SIZE ? $p_size : PCLZIP_READ_BLOCK_SIZE); $v_buffer = @fread($p_src, $v_read_size); @fwrite($p_dest, $v_buffer, $v_read_size); $p_size -= $v_read_size; } } else if ($p_mode==1) { while ($p_size != 0) { $v_read_size = ($p_size < PCLZIP_READ_BLOCK_SIZE ? $p_size : PCLZIP_READ_BLOCK_SIZE); $v_buffer = @gzread($p_src, $v_read_size); @fwrite($p_dest, $v_buffer, $v_read_size); $p_size -= $v_read_size; } } else if ($p_mode==2) { while ($p_size != 0) { $v_read_size = ($p_size < PCLZIP_READ_BLOCK_SIZE ? $p_size : PCLZIP_READ_BLOCK_SIZE); $v_buffer = @fread($p_src, $v_read_size); @gzwrite($p_dest, $v_buffer, $v_read_size); $p_size -= $v_read_size; } } else if ($p_mode==3) { while ($p_size != 0) { $v_read_size = ($p_size < PCLZIP_READ_BLOCK_SIZE ? $p_size : PCLZIP_READ_BLOCK_SIZE); $v_buffer = @gzread($p_src, $v_read_size); @gzwrite($p_dest, $v_buffer, $v_read_size); $p_size -= $v_read_size; } } // ----- Return return $v_result; } // -------------------------------------------------------------------------------- // -------------------------------------------------------------------------------- // Function : PclZipUtilRename() // Description : // This function tries to do a simple rename() function. If it fails, it // tries to copy the $p_src file in a new $p_dest file and then unlink the // first one. // Parameters : // $p_src : Old filename // $p_dest : New filename // Return Values : // 1 on success, 0 on failure. // -------------------------------------------------------------------------------- function PclZipUtilRename($p_src, $p_dest) { $v_result = 1; // ----- Try to rename the files if (!@rename($p_src, $p_dest)) { // ----- Try to copy & unlink the src if (!@copy($p_src, $p_dest)) { $v_result = 0; } else if (!@unlink($p_src)) { $v_result = 0; } } // ----- Return return $v_result; } // -------------------------------------------------------------------------------- // -------------------------------------------------------------------------------- // Function : PclZipUtilOptionText() // Description : // Translate option value in text. Mainly for debug purpose. // Parameters : // $p_option : the option value. // Return Values : // The option text value. // -------------------------------------------------------------------------------- function PclZipUtilOptionText($p_option) { $v_list = get_defined_constants(); for (reset($v_list); $v_key = key($v_list); next($v_list)) { $v_prefix = substr($v_key, 0, 10); if (( ($v_prefix == 'PCLZIP_OPT') || ($v_prefix == 'PCLZIP_CB_') || ($v_prefix == 'PCLZIP_ATT')) && ($v_list[$v_key] == $p_option)) { return $v_key; } } $v_result = 'Unknown'; return $v_result; } // -------------------------------------------------------------------------------- // -------------------------------------------------------------------------------- // Function : PclZipUtilTranslateWinPath() // Description : // Translate windows path by replacing '\' by '/' and optionally removing // drive letter. // Parameters : // $p_path : path to translate. // $p_remove_disk_letter : true | false // Return Values : // The path translated. // -------------------------------------------------------------------------------- function PclZipUtilTranslateWinPath($p_path, $p_remove_disk_letter=true) { if (stristr(php_uname(), 'windows')) { // ----- Look for potential disk letter if (($p_remove_disk_letter) && (($v_position = strpos($p_path, ':')) != false)) { $p_path = substr($p_path, $v_position+1); } // ----- Change potential windows directory separator if ((strpos($p_path, '\\') > 0) || (substr($p_path, 0,1) == '\\')) { $p_path = strtr($p_path, '\\', '/'); } } return $p_path; } // -------------------------------------------------------------------------------- ?>
PHP
<?php defined('IN_PHPCMS') or exit('Access Denied'); defined('INSTALL') or exit('Access Denied'); return ''; ?>
PHP
<?php defined('IN_PHPCMS') or exit('Access Denied'); defined('INSTALL') or exit('Access Denied'); $parentid = $menu_db->insert(array('name'=>'upgrade', 'parentid'=>977, 'm'=>'upgrade', 'c'=>'index', 'a'=>'init', 'data'=>'', 'listorder'=>0, 'display'=>'1'), true); $menu_db->insert(array('name'=>'checkfile', 'parentid'=>$parentid, 'm'=>'upgrade', 'c'=>'index', 'a'=>'checkfile', 'data'=>'', 'listorder'=>0, 'display'=>'1')); $language = array('upgrade'=>'在线升级', 'checkfile'=>'文件校验'); ?>
PHP
<?php defined('IN_PHPCMS') or exit('Access Denied'); defined('INSTALL') or exit('Access Denied'); $module = 'upgrade'; $modulename = '在线升级'; $introduce = '在线升级'; $author = 'phpcms Team'; $authorsite = 'http://www.phpcms.cn'; $authoremail = 'admin@phpcms.cn'; ?>
PHP
<?php $LANG['operation'] = '操作'; $LANG['view'] = '查看'; $LANG['access'] = '访问'; $LANG['upgrade'] = '在线升级'; $LANG['checkfile'] = '文件校验'; $LANG['updatetime'] = '更新日期'; $LANG['updatelist'] = '可升级版本列表'; $LANG['currentversion'] = '当前版本'; $LANG['lastversion'] = '为最新版'; $LANG['covertemplate'] = '覆盖模版?'; $LANG['view_code'] = '查看代码'; $LANG['modifyfile'] = '修改过的文件'; $LANG['lastmodifytime'] = '最后修改时间'; $LANG['modifyedfile'] = '被修改文件'; $LANG['lostfile'] = '丢失文件'; $LANG['unknowfile'] = '未知文件'; $LANG['filesize'] = '文件大小'; $LANG['begin_checkfile'] = '开始校验文件,请稍候'; $LANG['begin_upgrade'] = '开始升级'; $LANG['upgradeing'] = '正在升级'; $LANG['upgrade_success'] = '升级成功!'; $LANG['lost'] = '丢失'; $LANG['file_address'] = '文件地址'; $LANG['please_check_filepri'] = '复制文件失败,请检查目录权限'; $LANG['check_file_notice'] = '注意:文件校验为根目录下所有文件以及phpcms、api、statics三个文件夹下所有目录和文件与默认程序同名文件md5值对比的结果,如果异常请用木马扫描工具扫描该文件是否包含木马'; $LANG['upgrade_notice'] = '注意:升级程序有可能覆盖模版文件,请注意备份!linux服务器需检查文件所有者权限和组权限,确保WEB SERVER用户有文件写入权限';
PHP
<?php defined('IN_PHPCMS') or exit('No permission resources.'); //模型缓存路径 define('CACHE_MODEL_PATH',PHPCMS_PATH.'caches'.DIRECTORY_SEPARATOR.'caches_model'.DIRECTORY_SEPARATOR.'caches_data'.DIRECTORY_SEPARATOR); pc_base::load_app_class('admin', 'admin', 0); pc_base::load_sys_class('form', '', 0); class node extends admin { private $db,$siteid; //HTML标签 private static $html_tag = array("<p([^>]*)>(.*)</p>[|]"=>'<p>', "<a([^>]*)>(.*)</a>[|]"=>'<a>',"<script([^>]*)>(.*)</script>[|]"=>'<script>', "<iframe([^>]*)>(.*)</iframe>[|]"=>'<iframe>', "<table([^>]*)>(.*)</table>[|]"=>'<table>', "<span([^>]*)>(.*)</span>[|]"=>'<span>', "<b([^>]*)>(.*)</b>[|]"=>'<b>', "<img([^>]*)>[|]"=>'<img>', "<object([^>]*)>(.*)</object>[|]"=>'<object>', "<embed([^>]*)>(.*)</embed>[|]"=>'<embed>', "<param([^>]*)>(.*)</param>[|]"=>'<param>', '<div([^>]*)>[|]'=>'<div>', '</div>[|]'=>'</div>', '<!--([^>]*)-->[|]'=>'<!-- -->'); //网址类型 private $url_list_type = array(); function __construct() { parent::__construct(); $this->db = pc_base::load_model('collection_node_model'); $this->siteid = get_siteid(); $this->url_list_type = array('1'=>L('sequence'), '2'=>L('multiple_pages'), '3'=>L('single_page'), '4'=>'RSS'); } /** * node list */ public function manage() { $page = isset($_GET['page']) ? intval($_GET['page']) : 1; $nodelist = $this->db->listinfo(array('siteid'=>$this->get_siteid()), 'nodeid DESC', $page, 15); $pages = $this->db->pages; pc_base::load_sys_class('format', '', 0); include $this->admin_tpl('node_list'); } /** * add node */ public function add() { header("Cache-control: private"); if(isset($_POST['dosubmit'])) { $data = isset($_POST['data']) ? $_POST['data'] : showmessage(L('illegal_parameters'), HTTP_REFERER); $customize_config = isset($_POST['customize_config']) ? $_POST['customize_config'] : ''; if (!$data['name'] = trim($data['name'])) { showmessage(L('nodename').L('empty'), HTTP_REFERER); } if ($this->db->get_one(array('name'=>$data['name']))) { showmessage(L('nodename').L('exists'), HTTP_REFERER); } $data['urlpage'] = isset($_POST['urlpage'.$data['sourcetype']]) ? $_POST['urlpage'.$data['sourcetype']] : showmessage(L('illegal_parameters'), HTTP_REFERER); $data['siteid']= $this->get_siteid(); $data['customize_config'] = array(); if (is_array($customize_config)) foreach ($customize_config['en_name'] as $k => $v) { if (empty($v) || empty($customize_config['name'][$k])) continue; $data['customize_config'][] = array('name'=>$customize_config['name'][$k], 'en_name'=>$v, 'rule'=>$customize_config['rule'][$k], 'html_rule'=>$customize_config['html_rule'][$k]); } $data['customize_config'] = array2string($data['customize_config']); if ($this->db->insert($data)) { showmessage(L('operation_success'), '?m=collection&c=node&a=manage'); } else { showmessage(L('operation_failure'), HTTP_REFERER); } } else { $show_dialog = $show_validator = true; include $this->admin_tpl('node_form'); } } //修改采集配置 public function edit() { $nodeid = isset($_GET['nodeid']) ? intval($_GET['nodeid']) : showmessage(L('illegal_parameters'), HTTP_REFERER); $data = $this->db->get_one(array('nodeid'=>$nodeid)); if(isset($_POST['dosubmit'])) { $datas = $data; unset($data); $data = isset($_POST['data']) ? $_POST['data'] : showmessage(L('illegal_parameters'), HTTP_REFERER); $customize_config = isset($_POST['customize_config']) ? $_POST['customize_config'] : ''; if (!$data['name'] = trim($data['name'])) { showmessage(L('nodename').L('empty'), HTTP_REFERER); } if ($datas['name'] != $data['name']) { if ($this->db->get_one(array('name'=>$data['name']))) { showmessage(L('nodename').L('exists'), HTTP_REFERER); } } $data['urlpage'] = isset($_POST['urlpage'.$data['sourcetype']]) ? $_POST['urlpage'.$data['sourcetype']] : showmessage(L('illegal_parameters'), HTTP_REFERER); $data['customize_config'] = array(); if (is_array($customize_config)) foreach ($customize_config['en_name'] as $k => $v) { if (empty($v) || empty($customize_config['name'][$k])) continue; $data['customize_config'][] = array('name'=>$customize_config['name'][$k], 'en_name'=>$v, 'rule'=>$customize_config['rule'][$k], 'html_rule'=>$customize_config['html_rule'][$k]); } $data['customize_config'] = array2string($data['customize_config']); if ($this->db->update($data, array('nodeid'=>$nodeid))) { showmessage(L('operation_success'), '?m=collection&c=node&a=manage'); } else { showmessage(L('operation_failure'), HTTP_REFERER); } } else { $model_cache = getcache('model', 'commons'); $siteid = get_siteid(); foreach($model_cache as $k=>$v) { $modellist[0] = L('select_model'); if($v['siteid'] == $siteid) { $modellist[$k] = $v['name']; } } if (isset($data['customize_config'])) { $data['customize_config'] = string2array($data['customize_config']); } $show_dialog = $show_validator = true; //print_r($nodeinfo);exit; include $this->admin_tpl('node_form'); } } //复制采集 public function copy() { $nodeid = isset($_GET['nodeid']) ? intval($_GET['nodeid']) : showmessage(L('illegal_parameters'), HTTP_REFERER); if ($data = $this->db->get_one(array('nodeid'=>$nodeid))) { if (isset($_POST['dosubmit'])) { unset($data['nodeid']); $name = isset($_POST['name']) && trim($_POST['name']) ? trim($_POST['name']) : showmessage(L('illegal_parameters'), HTTP_REFERER); if ($this->db->get_one(array('name'=>$name), 'nodeid')) { showmessage(L('nodename').L('exists'), HTTP_REFERER); } $data['name'] = $name; $data = new_addslashes($data); if ($this->db->insert($data)) { showmessage(L('operation_success'), '', '', 'test'); } else { showmessage(L('operation_failure')); } } else { $show_validator = $show_header = true; include $this->admin_tpl('node_copy'); } } else { showmessage(L('notfound')); } } //导入采集点 public function node_import() { if (isset($_POST['dosubmit'])) { $filename = $_FILES['file']['tmp_name']; if (strtolower(substr($_FILES['file']['name'], -3, 3)) != 'txt') { showmessage(L('only_allowed_to_upload_txt_files'), HTTP_REFERER); } $data = json_decode(base64_decode(file_get_contents($filename)), true); if (pc_base::load_config('system', 'charset') == 'gbk') { $data = array_iconv($data, 'utf-8', 'gbk'); } @unlink($filename); $name = isset($_POST['name']) && trim($_POST['name']) ? trim($_POST['name']) : showmessage(L('illegal_parameters'), HTTP_REFERER); if ($this->db->get_one(array('name'=>$name), 'nodeid')) { showmessage(L('nodename').L('exists'), HTTP_REFERER); } $data['name'] = $name; $data['siteid'] = $this->get_siteid(); $data = new_addslashes($data); if ($this->db->insert($data)) { showmessage(L('operation_success'), '', '', 'test'); } else { showmessage(L('operation_failure')); } } else { $show_header = $show_validator = true; include $this->admin_tpl('node_import'); } } //导出采集配置 public function export() { $nodeid = isset($_GET['nodeid']) ? intval($_GET['nodeid']) : showmessage(L('illegal_parameters'), HTTP_REFERER); if ($data = $this->db->get_one(array('nodeid'=>$nodeid))) { unset($data['nodeid'], $data['name'], $data['siteid']); if (pc_base::load_config('system', 'charset') == 'gbk') { $data = array_iconv($data); } header("Content-type: application/octet-stream"); header("Content-Disposition: attachment; filename=pc_collection_".$nodeid.'.txt'); echo base64_encode(json_encode($data)); } else { showmessage(L('notfound')); } } //URL配置显示结果 public function public_url() { $sourcetype = isset($_GET['sourcetype']) && intval($_GET['sourcetype']) ? intval($_GET['sourcetype']) : showmessage(L('illegal_parameters')); $pagesize_start = isset($_GET['pagesize_start']) && intval($_GET['pagesize_start']) ? intval($_GET['pagesize_start']) : 1; $pagesize_end = isset($_GET['pagesize_end']) && intval($_GET['pagesize_end']) ? intval($_GET['pagesize_end']) : 10; $par_num = isset($_GET['par_num']) && intval($_GET['par_num']) ? intval($_GET['par_num']) : 1; $urlpage = isset($_GET['urlpage']) && trim($_GET['urlpage']) ? trim($_GET['urlpage']) : showmessage(L('illegal_parameters')); $show_header = true; include $this->admin_tpl('node_public_url'); } //删除采集节点 public function del() { if (isset($_POST['dosubmit'])) { $nodeid = isset($_POST['nodeid']) ? $_POST['nodeid'] : showmessage(L('illegal_parameters'), HTTP_REFERER); foreach ($nodeid as $k=>$v) { if(intval($v)) { $nodeid[$k] = intval($v); } else { unset($nodeid[$k]); } } $nodeid = implode('\',\'', $nodeid); $this->db->delete("nodeid in ('$nodeid')"); $content_db = pc_base::load_model('collection_content_model'); $content_db->delete("nodeid in ('$nodeid')"); showmessage(L('operation_success'), '?m=collection&c=node&a=manage'); } else { showmessage(L('illegal_parameters'), HTTP_REFERER); } } //测试文章URL采集 public function public_test() { $nodeid = isset($_GET['nodeid']) ? intval($_GET['nodeid']) : showmessage(L('illegal_parameters'), HTTP_REFERER); pc_base::load_app_class('collection', '', 0); if ($data = $this->db->get_one(array('nodeid'=>$nodeid))) { $urls = collection::url_list($data, 1); if (!empty($urls)) foreach ($urls as $v) { $url = collection::get_url_lists($v, $data); } $show_header = $show_dialog = true; include $this->admin_tpl('public_test'); } else { showmessage(L('notfound')); } } //测试文章内容采集 public function public_test_content() { $url = isset($_GET['url']) ? urldecode($_GET['url']) : exit('0'); $nodeid = isset($_GET['nodeid']) ? intval($_GET['nodeid']) : showmessage(L('illegal_parameters'), HTTP_REFERER); pc_base::load_app_class('collection', '', 0); if ($data = $this->db->get_one(array('nodeid'=>$nodeid))) { print_r(collection::get_content($url, $data)); } else { showmessage(L('notfound')); } } //采集节点名验证 public function public_name() { $name = isset($_GET['name']) && trim($_GET['name']) ? (pc_base::load_config('system', 'charset') == 'gbk' ? iconv('utf-8', 'gbk', trim($_GET['name'])) : trim($_GET['name'])) : exit('0'); $nodeid = isset($_GET['nodeid']) && intval($_GET['nodeid']) ? intval($_GET['nodeid']) : ''; $data = array(); if ($nodeid) { $data = $this->db->get_one(array('nodeid'=>$nodeid), 'name'); if (!empty($data) && $data['name'] == $name) { exit('1'); } } if ($this->db->get_one(array('name'=>$name), 'nodeid')) { exit('0'); } else { exit('1'); } } //采集网址 public function col_url_list() { $nodeid = isset($_GET['nodeid']) ? intval($_GET['nodeid']) : showmessage(L('illegal_parameters'), HTTP_REFERER); if ($data = $this->db->get_one(array('nodeid'=>$nodeid))) { pc_base::load_app_class('collection', '', 0); $urls = collection::url_list($data); $total_page = count($urls); if ($total_page > 0) { $page = isset($_GET['page']) ? intval($_GET['page']) : 0; $url_list = $urls[$page]; $url = collection::get_url_lists($url_list, $data); $history_db = pc_base::load_model('collection_history_model'); $content_db = pc_base::load_model('collection_content_model'); $total = count($url); $re = 0; if (is_array($url) && !empty($url)) foreach ($url as $v) { if (empty($v['url']) || empty($v['title'])) continue; $v = new_addslashes($v); $v['title'] = strip_tags($v['title']); $md5 = md5($v['url']); if (!$history_db->get_one(array('md5'=>$md5, 'siteid'=>$this->get_siteid()))) { $history_db->insert(array('md5'=>$md5, 'siteid'=>$this->get_siteid())); $content_db->insert(array('nodeid'=>$nodeid, 'status'=>0, 'url'=>$v['url'], 'title'=>$v['title'], 'siteid'=>$this->get_siteid())); } else { $re++; } } $show_header = $show_dialog = true; if ($total_page <= $page) { $this->db->update(array('lastdate'=>SYS_TIME), array('nodeid'=>$nodeid)); } include $this->admin_tpl('col_url_list'); } else { showmessage(L('not_to_collect')); } } else { showmessage(L('notfound')); } } //采集文章 public function col_content() { $nodeid = isset($_GET['nodeid']) ? intval($_GET['nodeid']) : showmessage(L('illegal_parameters'), HTTP_REFERER); if ($data = $this->db->get_one(array('nodeid'=>$nodeid))) { $content_db = pc_base::load_model('collection_content_model'); //更新附件状态 $attach_status = false; if(pc_base::load_config('system','attachment_stat')) { $this->attachment_db = pc_base::load_model('attachment_model'); $attach_status = true; } pc_base::load_app_class('collection', '', 0); $page = isset($_GET['page']) ? intval($_GET['page']) : 1; $total = isset($_GET['total']) ? intval($_GET['total']) : 0; if (empty($total)) $total = $content_db->count(array('nodeid'=>$nodeid, 'siteid'=>$this->get_siteid(), 'status'=>0)); $total_page = ceil($total/2); $list = $content_db->select(array('nodeid'=>$nodeid, 'siteid'=>$this->get_siteid(), 'status'=>0), 'id,url', '2', 'id desc'); $i = 0; if (!empty($list) && is_array($list)) { foreach ($list as $v) { $GLOBALS['downloadfiles'] = array(); $html = collection::get_content($v['url'], $data); //更新附件状态 if($attach_status) { $this->attachment_db->api_update($GLOBALS['downloadfiles'],'cj-'.$v['id'],1); } $content_db->update(array('status'=>1, 'data'=>array2string($html)), array('id'=>$v['id'])); $i++; } } else { showmessage(L('url_collect_msg'), '?m=collection&c=node&a=manage'); } if ($total_page > $page) { showmessage(L('collectioning').($i+($page-1)*2).'/'.$total.'<script type="text/javascript">location.href="?m=collection&c=node&a=col_content&page='.($page+1).'&nodeid='.$nodeid.'&total='.$total.'&pc_hash='.$_SESSION['pc_hash'].'"</script>', '?m=collection&c=node&a=col_content&page='.($page+1).'&nodeid='.$nodeid.'&total='.$total); } else { $this->db->update(array('lastdate'=>SYS_TIME), array('nodeid'=>$nodeid)); showmessage(L('collection_success'), '?m=collection&c=node&a=manage'); } } } //文章列表 public function publist() { $nodeid = isset($_GET['nodeid']) ? intval($_GET['nodeid']) : showmessage(L('illegal_parameters'), HTTP_REFERER); $node = $this->db->get_one(array('nodeid'=>$nodeid), 'name'); $content_db = pc_base::load_model('collection_content_model'); $status = isset($_GET['status']) ? intval($_GET['status']) : ''; $page = isset($_GET['page']) ? intval($_GET['page']) : 1; $sql = array('nodeid'=>$nodeid, 'siteid'=>$this->get_siteid()); if ($status) { $sql['status'] = $status - 1; } $data = $content_db->listinfo($sql, 'id desc', $page); $pages = $content_db->pages; $show_header = true; include $this->admin_tpl('publist'); } //导入文章 public function import() { $nodeid = isset($_GET['nodeid']) ? intval($_GET['nodeid']) : showmessage(L('illegal_parameters'), HTTP_REFERER); $id = isset($_GET['id']) ? $_GET['id'] : ''; $type = isset($_GET['type']) ? trim($_GET['type']) : ''; if ($type == 'all') { } else { $ids = implode(',', $id); } $program_db = pc_base::load_model('collection_program_model'); $program_list = $program_db->select(array('nodeid'=>$nodeid, 'siteid'=>$this->get_siteid()), 'id, catid'); $cat = getcache('category_content_'.$this->siteid, 'commons'); include $this->admin_tpl('import_program'); } //删除文章 public function content_del() { $id = isset($_GET['id']) ? $_GET['id'] : ''; $history = isset($_GET['history']) ? $_GET['history'] : ''; if (is_array($id)) { $collection_content_db = pc_base::load_model('collection_content_model'); $history_db = pc_base::load_model('collection_history_model'); $del_array = $id; $ids = implode('\',\'', $id); if ($history) { $data = $collection_content_db->select("id in ('$ids')", 'url'); foreach ($data as $v) { $list[] = md5($v['url']); } $md5 = implode('\',\'', $list); $history_db->delete("md5 in ('$md5')"); } $collection_content_db->delete("id in ('$ids')"); //同时删除关联附件 if(!empty($del_array)) { $attachment = pc_base::load_model('attachment_model'); foreach ($del_array as $id) { $attachment->api_delete('cj-'.$id); } } showmessage(L('operation_success'), HTTP_REFERER); } } //添加导入方案 public function import_program_add() { $nodeid = isset($_GET['nodeid']) ? intval($_GET['nodeid']) : showmessage(L('illegal_parameters'), HTTP_REFERER); $ids = isset($_GET['ids']) ? $_GET['ids'] : ''; $catid = isset($_GET['catid']) && intval($_GET['catid']) ? intval($_GET['catid']) : showmessage(L('please_select_cat'), HTTP_REFERER); $type = isset($_GET['type']) ? trim($_GET['type']) : ''; include dirname(__FILE__).DIRECTORY_SEPARATOR.'spider_funs'.DIRECTORY_SEPARATOR.'config.php'; //读取栏目缓存 $catlist = getcache('category_content_'.$this->siteid, 'commons'); $cat = $catlist[$catid]; $cat['setting'] = string2array($cat['setting']); if ($cat['siteid'] != $this->get_siteid() || $cat['type'] != 0) showmessage(L('illegal_section_parameter'), HTTP_REFERER); if (isset($_POST['dosubmit'])) { $config = array(); $model_field = isset($_POST['model_field']) ? $_POST['model_field'] : showmessage(L('illegal_parameters'), HTTP_REFERER); $node_field = isset($_POST['node_field']) ? $_POST['node_field'] : showmessage(L('illegal_parameters'), HTTP_REFERER); $funcs = isset($_POST['funcs']) ? $_POST['funcs'] : array(); $config['add_introduce'] = isset($_POST['add_introduce']) && intval($_POST['add_introduce']) ? intval($_POST['add_introduce']) : 0; $config['auto_thumb'] = isset($_POST['auto_thumb']) && intval($_POST['auto_thumb']) ? intval($_POST['auto_thumb']) : 0; $config['introcude_length'] = isset($_POST['introcude_length']) && intval($_POST['introcude_length']) ? intval($_POST['introcude_length']) : 0; $config['auto_thumb_no'] = isset($_POST['auto_thumb_no']) && intval($_POST['auto_thumb_no']) ? intval($_POST['auto_thumb_no']) : 0; $config['content_status'] = isset($_POST['content_status']) && intval($_POST['content_status']) ? intval($_POST['content_status']) : 1; foreach ($node_field as $k => $v) { if (empty($v)) continue; $config['map'][$model_field[$k]] = $v; } foreach ($funcs as $k=>$v) { if (empty($v)) continue; $config['funcs'][$model_field[$k]] = $v; } $data = array('config'=>array2string($config), 'siteid'=>$this->get_siteid(), 'nodeid'=>$nodeid, 'modelid'=>$cat['modelid'], 'catid'=>$catid); $program_db = pc_base::load_model('collection_program_model'); if ($id = $program_db->insert($data, true)) { showmessage(L('program_add_operation_success'), '?m=collection&c=node&a=import_content&programid='.$id.'&nodeid='.$nodeid.'&ids='.$ids.'&type='.$type); } else { showmessage(L('illegal_parameters')); } } //读取数据模型缓存 $model = getcache('model_field_'.$cat['modelid'], 'model'); if (empty($model)) showmessage(L('model_does_not_exist_please_update_the_cache_model')); $node_data = $this->db->get_one(array('nodeid'=>$nodeid), "customize_config"); $node_data['customize_config'] = string2array($node_data['customize_config']); $node_field = array(''=>L('please_choose'),'title'=>L('title'), 'author'=>L('author'), 'comeform'=>L('comeform'), 'time'=>L('time'), 'content'=>L('content')); if (is_array($node_data['customize_config'])) foreach ($node_data['customize_config'] as $k=>$v) { if (empty($v['en_name']) || empty($v['name'])) continue; $node_field[$v['en_name']] = $v['name']; } $show_header = true; include $this->admin_tpl('import_program_add'); } public function import_program_del() { $id = isset($_GET['id']) ? intval($_GET['id']) : showmessage(L('illegal_parameters'), HTTP_REFERER); $program_db = pc_base::load_model('collection_program_model'); if ($program_db->delete(array('id'=>$id))) { showmessage(L('operation_success'), HTTP_REFERER); } else { showmessage(L('illegal_parameters')); } } //导入文章到模型 public function import_content() { $nodeid = isset($_GET['nodeid']) ? intval($_GET['nodeid']) : showmessage(L('illegal_parameters'), HTTP_REFERER); $programid = isset($_GET['programid']) ? intval($_GET['programid']) : showmessage(L('illegal_parameters'), HTTP_REFERER); $ids = isset($_GET['ids']) ? $_GET['ids'] : ''; $type = isset($_GET['type']) ? trim($_GET['type']) : ''; if (!$node = $this->db->get_one(array('nodeid'=>$nodeid), 'coll_order,content_page')) { showmessage(L('node_not_found'), '?m=collection&c=node&a=manage'); } $program_db = pc_base::load_model('collection_program_model'); $collection_content_db = pc_base::load_model('collection_content_model'); $content_db = pc_base::load_model('content_model'); //更新附件状态 $attach_status = false; if(pc_base::load_config('system','attachment_stat')) { $attachment_db = pc_base::load_model('attachment_model'); $att_index_db = pc_base::load_model('attachment_index_model'); $attach_status = true; } $order = $node['coll_order'] == 1 ? 'id desc' : ''; $str = L('operation_success'); $url = '?m=collection&c=node&a=publist&nodeid='.$nodeid.'&status=2&pc_hash='.$_SESSION['pc_hash']; if ($type == 'all') { $total = isset($_GET['total']) && intval($_GET['total']) ? intval($_GET['total']) : ''; if (empty($total)) $total = $collection_content_db->count(array('siteid'=>$this->get_siteid(), 'nodeid'=>$nodeid, 'status'=>1)); $total_page = ceil($total/20); $page = isset($_GET['page']) && intval($_GET['page']) ? intval($_GET['page']) : 1; $total_page = ceil($total/20); $data = $collection_content_db->select(array('siteid'=>$this->get_siteid(), 'nodeid'=>$nodeid, 'status'=>1), 'id, data', '20', $order); } else { $ids = explode(',', $ids); $ids = implode('\',\'', $ids); $data = $collection_content_db->select("siteid='".$this->get_siteid()."' AND id in ('$ids') AND nodeid = '$nodeid' AND status = '1'", 'id, data', '', $order); $total = count($data); $str = L('operation_success').$total.L('article_was_imported'); } $program = $program_db->get_one(array('id'=>$programid)); $program['config'] = string2array($program['config']); $_POST['add_introduce'] = $program['config']['add_introduce']; $_POST['introcude_length'] = $program['config']['introcude_length']; $_POST['auto_thumb'] = $program['config']['auto_thumb']; $_POST['auto_thumb_no'] = $program['config']['auto_thumb_no']; $_POST['spider_img'] = 0; $i = 0; $content_db->set_model($program['modelid']); $coll_contentid = array(); //加载所有的处理函数 $funcs_file_list = glob(dirname(__FILE__).DIRECTORY_SEPARATOR.'spider_funs'.DIRECTORY_SEPARATOR.'*.php'); foreach ($funcs_file_list as $v) { include $v; } foreach ($data as $k=>$v) { $sql = array('catid'=>$program['catid'], 'status'=>$program['config']['content_status']); $v['data'] = string2array($v['data']); foreach ($program['config']['map'] as $a=>$b) { if (isset($program['config']['funcs'][$a]) && function_exists($program['config']['funcs'][$a])) { $GLOBALS['field'] = $a; $sql[$a] = $program['config']['funcs'][$a]($v['data'][$b]); } else { $sql[$a] = $v['data'][$b]; } } if ($node['content_page'] == 1) $sql['paginationtype'] = 2; $contentid = $content_db->add_content($sql, 1); if ($contentid) { $coll_contentid[] = $v['id']; $i++; //更新附件状态,将采集关联重置到内容关联 if($attach_status) { $datas = $att_index_db->select(array('keyid'=>'cj-'.$v['id']),'*',100,'','','aid'); if(!empty($datas)) { $datas = array_keys($datas); $datas = implode(',',$datas); $att_index_db->update(array('keyid'=>'c-'.$program['catid'].'-'.$contentid),array('keyid'=>'cj-'.$v['id'])); $attachment_db->update(array('module'=>'content')," aid IN ($datas)"); } } } else { $collection_content_db->delete(array('id'=>$v['id'])); } } $sql_id = implode('\',\'', $coll_contentid); $collection_content_db->update(array('status'=>2), " id IN ('$sql_id')"); if ($type == 'all' && $total_page > $page) { $str = L('are_imported_the_import_process').(($page-1)*20+$i).'/'.$total.'<script type="text/javascript">location.href="?m=collection&c=node&a=import_content&nodeid='.$nodeid.'&programid='.$programid.'&type=all&page='.($page+1).'&total='.$total.'&pc_hash='.$_SESSION['pc_hash'].'"</script>'; $url = ''; } showmessage($str, $url); } } ?>
PHP
<?php defined('IN_ADMIN') or exit('No permission resources.');?> <?php include $this->admin_tpl('header', 'admin');?> <script type="text/javascript"> $(document).ready(function() { $.formValidator.initConfig({formid:"myform",autotip:true,onerror:function(msg,obj){window.top.art.dialog({content:msg,lock:true,width:'200',height:'50'})}}); $("#name").formValidator({onshow:"<?php echo L('input').L('nodename')?>",onfocus:"<?php echo L('input').L('nodename')?>"}).inputValidator({min:1,onerror:"<?php echo L('input').L('nodename')?>"}).ajaxValidator({type : "get",url : "",data :"m=collection&c=node&a=public_name<?php if(ROUTE_A=='edit')echo "&nodeid=$data[nodeid]"?>",datatype : "html",async:'false',success : function(data){ if( data == "1" ){return true;}else{return false;}},buttons: $("#dosubmit"),onerror : "<?php echo L('nodename').L('exists')?>",onwait : "<?php echo L('connecting')?>"})<?php if(ROUTE_A=='edit')echo ".defaultPassed()"?>; }); </script> <div class="pad-10"> <div class="col-tab"> <ul class="tabBut cu-li"> <li class="on" id="tab_1"><a href="javascript:show_div('1')"><?php echo L('url_rewrites')?></a></li> <li id="tab_2"><a href="javascript:show_div('2')"><?php echo L('content_rules')?></a></li> <li id="tab_3"><a href="javascript:show_div('3')"><?php echo L('custom_rule')?></a></li> <li id="tab_4"><a href="javascript:show_div('4')"><?php echo L('eigrp')?></a></li> </ul> <form name="myform" action="?m=collection&c=node&a=<?php echo ROUTE_A?>&nodeid=<?php if(isset($nodeid)) echo $nodeid?>" method="post" id="myform"> <div class="content pad-10" id="show_div_1" style="height:auto"> <div class="common-form"> <fieldset> <legend><?php echo L('basic_configuration')?></legend> <table width="100%" class="table_form"> <tr> <td width="120"><?php echo L('collection_items_of')?>:</td> <td> <input type="text" name="data[name]" id="name" class="input-text" value="<?php if(isset($data['name'])) echo $data['name']?>"></input> </td> </tr> <tr> <td width="120"><?php echo L('encode_varchar')?>:</td> <td> <?php echo form::radio(array('gbk'=>'GBK', 'utf-8'=>'UTF-8', 'big5'=>'BIG5'), (isset($data['sourcecharset']) ? $data['sourcecharset'] : 'gbk'), 'name="data[sourcecharset]"')?> </td> </tr> </table> </fieldset> <fieldset> <legend><?php echo L('web_sites_to_collect')?></legend> <table width="100%" class="table_form"> <tr> <td width="120"><?php echo L('url_type')?>:</td> <td> <?php echo form::radio($this->url_list_type, (isset($data['sourcetype']) ? $data['sourcetype'] : '1'), 'name="data[sourcetype]" onclick="show_url_type(this.value)"')?> </td> </tr> <tbody id="url_type_1" <?php if (isset($data['sourcetype']) && $data['sourcetype'] != 1){echo ' style="display:none"';}?>> <tr> <td width="120"><?php echo L('url_configuration')?>:</td> <td> <input type="text" name="urlpage1" id="urlpage_1" size="100" value="<?php if(isset($data['sourcetype']) && $data['sourcetype'] == 1 && isset($data['urlpage'])) echo $data['urlpage'];?>"> <input type="button" class="button" onclick="show_url()" value="<?php echo L('test')?>"><br /> <?php echo L('url_msg')?><br /> <?php echo L('page_from')?>: <input type="text" name="data[pagesize_start]" value="<?php if(isset($data['sourcetype']) && $data['sourcetype'] == 1 && isset($data['pagesize_start'])) { echo $data['pagesize_start'];} else { echo '1';}?>" size="4"> <?php echo L('to')?> <input type="text" name="data[pagesize_end]" value="<?php if(isset($data['sourcetype']) && $data['sourcetype'] == 1 && isset($data['pagesize_end'])) { echo $data['pagesize_end'];} else { echo '10';}?>" size="4"> <?php echo L('increment_by')?><input type="text" name="data[par_num]" size="4" value="<?php if(isset($data['sourcetype']) && $data['sourcetype'] == 1 && isset($data['par_num'])) { echo $data['par_num'];} else { echo '1';}?>"> </td> </tr> </tbody> <tbody id="url_type_2" <?php if (!isset($data['sourcetype']) || $data['sourcetype'] != 2){echo ' style="display:none"';}?>> <tr> <td width="120"><?php echo L('url_configuration')?>:</td> <td> <textarea rows="10" cols="80" name="urlpage2" id="urlpage_2" ><?php if(isset($data['sourcetype']) && $data['sourcetype'] == 2 && isset($data['urlpage'])) { echo $data['urlpage'];}?></textarea> <br><?php echo L('one_per_line')?> </td> </tr> </tbody> <tbody id="url_type_3" <?php if (!isset($data['sourcetype']) || $data['sourcetype'] != 3){echo ' style="display:none"';}?>> <tr> <td width="120"><?php echo L('url_configuration')?>:</td> <td> <input type="text" name="urlpage3" id="urlpage_3" size="100" value="<?php if(isset($data['sourcetype']) && $data['sourcetype'] == 3 && isset($data['urlpage'])) { echo $data['urlpage'];}?>"> </td> </tr> </tbody> <tbody id="url_type_4" <?php if (!isset($data['sourcetype']) || $data['sourcetype'] != 4){echo ' style="display:none"';}?>> <tr> <td width="120"><?php echo L('url_configuration')?>:</td> <td> <input type="text" name="urlpage4" id="urlpage_4" size="100" value="<?php if(isset($data['sourcetype']) && $data['sourcetype'] == 4 && isset($data['urlpage'])) { echo $data['urlpage'];}?>"> </td> </tr> </tbody> <tr> <td width="120"><?php echo L('url_configuration')?>:</td> <td> <?php echo L('site_must_contain')?><input type="text" name="data[url_contain]" value="<?php if(isset($data['url_contain'])) echo $data['url_contain']?>"> <?php echo L('the_web_site_does_not_contain')?><input type="text" name="data[url_except]" value="<?php if(isset($data['url_except'])) echo $data['url_except']?>"> </td> </tr> <tr> <td width="120"><?php echo L('base_configuration')?>:</td> <td> <input type="text" name="data[page_base]" value="<?php if(isset($data['page_base'])) echo $data['page_base']?>" size="100" ><br> <?php echo L('base_msg')?> </td> </tr> <tr> <td width="120"><?php echo L('get_url')?>:</td> <td> <?php echo L('from')?> <textarea rows="10" cols="40" name="data[url_start]"><?php if(isset($data['url_start'])) echo $data['url_start']?></textarea> <?php echo L('to')?> <textarea rows="10" name="data[url_end]" cols="40"><?php if(isset($data['url_end'])) echo $data['url_end']?></textarea> <?php echo L('finish')?> </td> </tr> </table> </fieldset> </div> </div> <div class="content pad-10" id="show_div_2" style="height:auto;display:none"> <div class="explain-col"> <?php echo L('rule_msg')?> </div> <div class="bk15"></div> <input type="button" class="button" value="<?php echo L('expand_all')?>" onclick="$('#show_div_2').children('fieldset').children('.table_form').show()"> <input type="button" class="button" value="<?php echo L('all_the')?>" onclick="$('#show_div_2').children('fieldset').children('.table_form').hide()"> <fieldset> <legend><a href="javascript:void(0)" onclick="$(this).parent().parent().children('table').toggle()"><?php echo L('title').L('rule')?></a></legend> <table width="100%" class="table_form"> <tr> <td width="120"><?php echo L('matching_rule')?>:</td> <td> <textarea rows="5" cols="40" name="data[title_rule]" id="title_rule"><?php if(isset($data['title_rule'])) {echo $data['title_rule'];}else{echo '<title>'.L('[content]').'</title>';}?></textarea> <br><?php echo L('use')?>"<a href="javascript:insertText('title_rule', '<?php echo L('[content]')?>')"><?php echo L('[content]')?></a>"<?php echo L('w_wildmenu')?> </td> <td width="120"><?php echo L('filtering')?>:</td> <td> <textarea rows="5" cols="50" name="data[title_html_rule]" id="title_html_rule"><?php if(isset($data['title_html_rule'])) echo $data['title_html_rule']?></textarea> <input type="button" value="<?php echo L('select')?>" class="button" onclick="html_role('data[title_html_rule]')"> </td> </tr> </table> </fieldset> <fieldset> <legend><a href="javascript:void(0)" onclick="$(this).parent().parent().children('table').toggle()"><?php echo L('author').L('rule')?></a></legend> <table width="100%" class="table_form" style="display:none"> <tr> <td width="120"><?php echo L('matching_rule')?>:</td> <td> <textarea rows="5" cols="40" name="data[author_rule]" id="author_rule"><?php if(isset($data['author_rule'])) echo $data['author_rule']?></textarea> <br><?php echo L('use')?>"<a href="javascript:insertText('author_rule', '<?php echo L('[content]')?>')"><?php echo L('[content]')?></a>"<?php echo L('w_wildmenu')?> </td> <td width="120"><?php echo L('filtering')?>:</td> <td> <textarea rows="5" cols="50" name="data[author_html_rule]" id="author_html_rule"><?php if(isset($data['author_html_rule'])) echo $data['author_html_rule']?></textarea> <input type="button" value="<?php echo L('select')?>" class="button" onclick="html_role('data[author_html_rule]')"> </td> </tr> </table> </fieldset> <fieldset> <legend><a href="javascript:void(0)" onclick="$(this).parent().parent().children('table').toggle()"><?php echo L('comeform').L('rule')?></a></legend> <table width="100%" class="table_form" style="display:none"> <tr> <td width="120"><?php echo L('matching_rule')?>:</td> <td> <textarea rows="5" cols="40" name="data[comeform_rule]" id="comeform_rule"><?php if(isset($data['comeform_rule'])) echo $data['comeform_rule']?></textarea> <br><?php echo L('use')?>"<a href="javascript:insertText('comeform_rule', '<?php echo L('[content]')?>')"><?php echo L('[content]')?></a>"<?php echo L('w_wildmenu')?> </td> <td width="120"><?php echo L('filtering')?>:</td> <td> <textarea rows="5" cols="50" name="data[comeform_html_rule]" id="comeform_html_rule"><?php if(isset($data['comeform_html_rule'])) echo $data['comeform_html_rule']?></textarea> <input type="button" value="<?php echo L('select')?>" class="button" onclick="html_role('data[comeform_html_rule]')"> </td> </tr> </table> </fieldset> <fieldset> <legend><a href="javascript:void(0)" onclick="$(this).parent().parent().children('table').toggle()"><?php echo L('time').L('rule')?></a></legend> <table width="100%" class="table_form" style="display:none"> <tr> <td width="120"><?php echo L('matching_rule')?>:</td> <td> <textarea rows="5" cols="40" name="data[time_rule]" id="time_rule"><?php if(isset($data['time_rule'])) echo $data['time_rule']?></textarea> <br><?php echo L('use')?>"<a href="javascript:insertText('time_rule', '<?php echo L('[content]')?>')"><?php echo L('[content]')?></a>"<?php echo L('w_wildmenu')?> </td> <td width="120"><?php echo L('filtering')?>:</td> <td> <textarea rows="5" cols="50" name="data[time_html_rule]" id="time_html_rule"><?php if(isset($data['time_html_rule'])) echo $data['time_html_rule']?></textarea> <input type="button" value="<?php echo L('select')?>" class="button" onclick="html_role('data[time_html_rule]')"> </td> </tr> </table> </fieldset> <fieldset> <legend><a href="javascript:void(0)" onclick="$(this).parent().parent().children('table').toggle()"><?php echo L('content').L('rule')?></a></legend> <table width="100%" class="table_form" style="display:none"> <tr> <td width="120"><?php echo L('matching_rule')?>:</td> <td> <textarea rows="5" cols="40" name="data[content_rule]" id="content_rule"><?php if(isset($data['content_rule'])) echo $data['content_rule']?></textarea> <br><?php echo L('use')?>"<a href="javascript:insertText('content_rule', '<?php echo L('[content]')?>')"><?php echo L('[content]')?></a>"<?php echo L('w_wildmenu')?> </td> <td width="120"><?php echo L('filtering')?>:</td> <td> <textarea rows="5" cols="50" name="data[content_html_rule]" id="content_html_rule"><?php if(isset($data['content_html_rule'])) echo $data['content_html_rule']?></textarea> <input type="button" value="<?php echo L('select')?>" class="button" onclick="html_role('data[content_html_rule]')"> </td> </tr> </table> </fieldset> <fieldset> <legend><a href="javascript:void(0)" onclick="$(this).parent().parent().children('table').toggle()"><?php echo L('content_page').L('rule')?></a></legend> <table width="100%" class="table_form" style="display:none"> <tr> <td width="120"><?php echo L('page_mode')?>:</td> <td> <?php echo form::radio(array('1'=>L('all_are_models'), '2'=>L('down_the_pages_mode')), (isset($data['content_page_rule']) ? $data['content_page_rule'] : 1), 'name="data[content_page_rule]" onclick="show_nextpage(this.value)"')?> </td> </tr> <tbody id="nextpage" <?php if(!isset($data['content_page_rule']) || $data['content_page_rule']!=2) echo 'style="display:none"'?>> <tr> <td width="120"><?php echo L('nextpage_rule')?>:</td> <td> <input type="text" name="data[content_nextpage]" size="100" value="<?php if(isset($data['content_nextpage'])) echo $data['content_nextpage']?>"><br> <?php echo L('nextpage_rule_msg')?> </td> </tr> </tbody> <tr> <td width="120"><?php echo L('matching_rule')?>:</td> <td> <?php echo L('from')?> <textarea rows="5" cols="40" name="data[content_page_start]" id="content_page_start"><?php if(isset($data['content_page_start'])) echo $data['content_page_start']?></textarea> <?php echo L('to')?> <textarea rows="5" cols="40" name="data[content_page_end]" id="content_page_end"><?php if(isset($data['content_page_end'])) echo $data['content_page_end']?></textarea> </td> </tr> </table> </fieldset> </div> <div class="content pad-10" id="show_div_3" style="height:auto;display:none"> <input type="button" class="button" value="<?php echo L('add_item')?>" onclick="add_caiji()"> <div class="bk10"></div> <table width="100%" class="table_form" id="customize_config"> <?php if(isset($data['customize_config']) && is_array($data['customize_config'])) foreach ($data['customize_config'] as $k=>$v):?> <tbody id="customize_config_<?php echo $k?>"><tr style="background-color:#FBFFE4"><td><?php echo L('rulename')?>:</td><td><input type="text" name="customize_config[name][<?php echo $k?>]" value="<?php echo $v['name']?>" class="input-text" /></td><td><?php echo L('rules_in_english')?>:</td><td><input type="text" name="customize_config[en_name][<?php echo $k?>]" value="<?php echo $v['en_name']?>" class="input-text" /></td></tr><tr><td width="120"><?php echo L('matching_rule')?>:</td><td><textarea rows="5" cols="40" name="customize_config[rule][<?php echo $k?>]" id="rule_<?php echo $k?>"><?php echo $v['rule']?></textarea> <br><?php echo L('use')?>"<a href="javascript:insertText('rule_<?php echo $k?>', '<?php echo L('[content]')?>')"><?php echo L('[content]')?></a>"<?php echo L('w_wildmenu')?></td><td width="120"><?php echo L('filtering')?>:</td><td><textarea rows="5" cols="50" name="customize_config[html_rule][<?php echo $k?>]"><?php echo $v['html_rule']?></textarea><input type="button" value="<?php echo L('select')?>" class="button" onclick="html_role('customize_config[html_rule][<?php echo $k?>]')"></td></tr></tbody> <?php endforeach;?> </table> </div> <div class="content pad-10" id="show_div_4" style="height:auto;display:none"> <table width="100%" class="table_form" > <tr> <td width="120"><?php echo L('download_pic')?>:</td> <td> <?php echo form::radio(array('1'=>L('download_pic'), '0'=>L('no_download')), (isset($data['down_attachment']) ? $data['down_attachment'] : '0'), 'name="data[down_attachment]"')?> </td> </tr> <tr> <td width="120"><?php echo L('watermark')?>:</td> <td> <?php echo form::radio(array('1'=>L('gfl_sdk'), '0'=>L('no_gfl_sdk')), (isset($data['watermark']) ? $data['watermark'] : '0'), 'name="data[watermark]"')?> </td> </tr> <tr> <td width="120"><?php echo L('content_page_models')?>:</td> <td> <?php echo form::radio(array('0'=>L('no_page'), '1'=>L('by_the_paging')), (isset($data['content_page']) ? $data['content_page'] : '1'), 'name="data[content_page]"')?> </td> </tr> <tr> <td width="120"><?php echo L('sort_order')?>:</td> <td> <?php echo form::radio(array('1'=>L('with_goals_from_the_same'), '2'=>L('and_objectives_of_the_standing_opposite')), (isset($data['coll_order']) ? $data['coll_order'] : '1'), 'name="data[coll_order]"')?> </td> </tr> </table> </div> </div> <div class="bk15"></div> <input name="dosubmit" type="submit" id="dosubmit" value="<?php echo L('submit')?>" class="button"> </div> </form> <script type="text/javascript"> <!-- function insertText(id, text) { $('#'+id).focus(); var str = document.selection.createRange(); str.text = text; } function show_url_type(obj) { var num = <?php echo count($this->url_list_type);?>; for (var i=1; i<=num; i++){ if (obj==i){ $('#url_type_'+i).show(); } else { $('#url_type_'+i).hide(); } } } function show_div(id) { for (var i=1;i<=4;i++) { if (id==i) { $('#tab_'+i).addClass('on'); $('#show_div_'+i).show(); } else { $('#tab_'+i).removeClass('on'); $('#show_div_'+i).hide(); } } } function show_url() { var type = $("input[type='radio'][name='data[sourcetype]']:checked").val(); window.top.art.dialog({id:'test_url',iframe:'?m=collection&c=node&a=public_url&sourcetype='+type+'&urlpage='+$('#urlpage_'+type).val()+'&pagesize_start='+$("input[name='data[pagesize_start]']").val()+'&pagesize_end='+$("input[name='data[pagesize_end]']").val()+'&par_num='+$("input[name='data[par_num]']").val(), title:'<?php echo L('testpageurl')?>', width:'700', height:'450'}, '', function(){window.top.art.dialog({id:'test_url'}).close()}); } function anti_selectall(obj) { $("input[name='"+obj+"']").each(function(i,n){ if (this.checked) { this.checked = false; } else { this.checked = true; }}); } function show_nextpage(value) { if (value == 2) { $('#nextpage').show(); } else { $('#nextpage').hide(); } } var i =<?php echo isset($data['customize_config']) ? count($data['customize_config']) : 0?>; function add_caiji() { var html = '<tbody id="customize_config_'+i+'"><tr style="background-color:#FBFFE4"><td><?php echo L('rulename')?>:</td><td><input type="text" name="customize_config[name][]" class="input-text" /></td><td><?php echo L('rules_in_english')?>:</td><td><input type="text" name="customize_config[en_name][]" class="input-text" /></td></tr><tr><td width="120"><?php echo L('matching_rule')?>:</td><td><textarea rows="5" cols="40" name="customize_config[rule][]" id="rule_'+i+'"></textarea> <br><?php echo L('use')?>"<a href="javascript:insertText(\'rule_'+i+'\', \'<?php echo L('[content]')?>\')"><?php echo L('[content]')?></a>"<?php echo L('w_wildmenu')?></td><td width="120"><?php echo L('filtering')?>:</td><td><textarea rows="5" cols="50" name="customize_config[html_rule][]" id="content_html_rule_'+i+'"></textarea><input type="button" value="<?php echo L('select')?>" class="button" onclick="html_role(\'content_html_rule_'+i+'\', 1)"></td></tr></tbody>'; $('#customize_config').append(html); i++; } function html_role(id, type) { art.dialog({id:'test_url',content:'<?php echo form::checkbox(self::$html_tag, '', 'name="html_rule"', '', '120')?><br><div class="bk15"></div><center><input type="button" value="<?php echo L('select_all')?>" class="button" onclick="selectall(\'html_rule\')"> <input type="button" class="button" value="<?php echo L('invert')?>" onclick="anti_selectall(\'html_rule\')"></center>', width:'500', height:'150', lock: false}, function(){var old = $("textarea[name='"+id+"']").val();var str = '';$("input[name='html_rule']:checked").each(function(){str+=$(this).val()+"\n";});$((type == 1 ? "#"+id :"textarea[name='"+id+"']")).val((old ? old+"\n" : '')+str);}, function(){art.dialog({id:'test_url'}).close()}); } <?php if (ROUTE_A == 'edit') echo '$(\'#show_div_2\').children(\'fieldset\').children(\'.table_form\').show();';?> //--> </script> </body> </html>
PHP
<?php defined('IN_ADMIN') or exit('No permission resources.');?> <?php include $this->admin_tpl('header', 'admin');?> <div class="pad-10"> <div class="col-tab"> <ul class="tabBut cu-li"> <li class="on" id="tab_1"><?php echo L('url_list')?></li> </ul> <div class="content pad-10" id="show_div_1" style="height:auto"> <?php foreach ($url as $key=>$val):?> <?php echo $val['title']?><br> <div style="float:right"><a href="javascript:void(0)" onclick="show_content('<?php echo urlencode($val['url'])?>')"><span><?php echo L('view')?></span></a></div><?php echo $val['url']?> <hr size="1" /> <?php endforeach;?> </div> </div> </div> <script type="text/javascript"> <!-- function show_content(url) { art.dialog({id:'test',content:'<?php echo L('loading')?>',width:'100',height:'30', lock:true}); $.get("?m=collection&c=node&a=public_test_content&nodeid=<?php echo $nodeid?>&url="+url+'&pc_hash=<?php echo $_SESSION['pc_hash']?>', function(data){art.dialog({id:'test'}).close(); art.dialog({title:'<?php echo L('content_view')?>',id:'test',content:'<textarea rows="26" cols="90">'+data+'</textarea>',width:'500',height:'400', lock:false});}); } window.top.$('#display_center_id').css('display','none'); //--> </script> </body> </html>
PHP
<?php defined('IN_ADMIN') or exit('No permission resources.');?> <?php include $this->admin_tpl('header', 'admin');?> <div class="pad-lr-10"> <form name="myform" action="?m=collection&c=node&a=del" method="post" onsubmit="return confirm('<?php echo L('sure_delete')?>')"> <div class="table-list"> <table width="100%" cellspacing="0"> <thead> <tr> <th align="left" width="20"><input type="checkbox" value="" id="check_box" onclick="selectall('nodeid[]');"></th> <th align="left">ID</th> <th align="left"><?php echo L('nodename')?></th> <th align="left"><?php echo L('lastdate')?></th> <th align="left"><?php echo L('content').L('operation')?></th> <th align="left"><?php echo L('operation')?></th> </tr> </thead> <tbody> <?php foreach($nodelist as $k=>$v) { ?> <tr> <td align="left"><input type="checkbox" value="<?php echo $v['nodeid']?>" name="nodeid[]"></td> <td align="left"><?php echo $v['nodeid']?></td> <td align="left"><?php echo $v['name']?></td> <td align="left"><?php echo format::date($v['lastdate'], 1)?></td> <td align="left"><a href="?m=collection&c=node&a=col_url_list&nodeid=<?php echo $v['nodeid']?>">[<?php echo L('collection_web_site')?>]</a> <a href="?m=collection&c=node&a=col_content&nodeid=<?php echo $v['nodeid']?>">[<?php echo L('collection_content')?>]</a> <a href="?m=collection&c=node&a=publist&nodeid=<?php echo $v['nodeid']?>&status=2" style="color:red">[<?php echo L('public_content')?>]</a> </td> <td align="left"> <a href="javascript:void(0)" onclick="test_spider(<?php echo $v['nodeid']?>)">[<?php echo L('test')?>]</a> <a href="?m=collection&c=node&a=edit&nodeid=<?php echo $v['nodeid']?>&menuid=957">[<?php echo L('edit')?>]</a> <a href="javascript:void(0)" onclick="copy_spider(<?php echo $v['nodeid']?>)">[<?php echo L('copy')?>]</a> <a href="?m=collection&c=node&a=export&nodeid=<?php echo $v['nodeid']?>">[<?php echo L('export')?>]</a> </td> </tr> <?php } ?> </tbody> </table> <div class="btn"> <label for="check_box"><?php echo L('select_all')?>/<?php echo L('cancel')?></label> <input type="submit" class="button" name="dosubmit" value="<?php echo L('delete')?>"/> <input type="button" class="button" value="<?php echo L('import_collection_points')?>" onclick="import_spider()" /> </div> <div id="pages"><?php echo $pages?></div> </div> </form> </div> <script type="text/javascript"> <!-- function test_spider(id) { window.top.art.dialog({id:'test'}).close(); window.top.art.dialog({title:'<?php echo L('data_acquisition_testdat')?>',id:'test',iframe:'?m=collection&c=node&a=public_test&nodeid='+id,width:'700',height:'500'}, '', function(){window.top.art.dialog({id:'test'}).close()}); } function copy_spider(id) { window.top.art.dialog({id:'test'}).close(); window.top.art.dialog({title:'<?php echo L('copy_node')?>',id:'test',iframe:'?m=collection&c=node&a=copy&nodeid='+id,width:'420',height:'120'}, function(){var d = window.top.art.dialog({id:'test'}).data.iframe;var form = d.document.getElementById('dosubmit');form.click();return false;}, function(){window.top.art.dialog({id:'test'}).close()}); } function import_spider() { window.top.art.dialog({id:'test'}).close(); window.top.art.dialog({title:'<?php echo L('import_collection_points')?>',id:'test',iframe:'?m=collection&c=node&a=node_import',width:'420',height:'200'}, function(){var d = window.top.art.dialog({id:'test'}).data.iframe;var form = d.document.getElementById('dosubmit');form.click();return false;}, function(){window.top.art.dialog({id:'test'}).close()}); } window.top.$('#display_center_id').css('display','none'); //--> </script> </body> </html>
PHP
<?php defined('IN_ADMIN') or exit('No permission resources.');?> <?php include $this->admin_tpl('header', 'admin');?> <div class="pad-10"> <div class="col-tab"> <ul class="tabBut cu-li"> <li class="on" id="tab_1"><?php echo L('url_list')?></li> </ul> <div class="content pad-10" id="show_div_1" style="height:auto"> <b><?php echo L('url_list')?></b>:<?php echo $url_list;?><br><br> <?php echo L('in_all')?>: <?php echo $total?> <?php echo L('all_count_msg')?>:<?php echo $re;?><?php echo L('import_num_msg')?><?php echo $total-$re;?> <br><br> <?php if (is_array($url))foreach ($url as $v):?> <?php echo $v['title'].'<br>'.$v['url'];?> <hr size="1" /> <?php endforeach;?> <?php if ($total_page > $page) { echo "<script type='text/javascript'>location.href='?m=collection&c=node&a=col_url_list&page=".($page+1)."&nodeid=$nodeid&pc_hash=".$_SESSION['pc_hash']."'</script>"; } else {?> <script type="text/javascript"> window.top.art.dialog({id:'test'}).close(); window.top.art.dialog({id:'test',content:'<h2><?php echo L('collection_success')?></h2><span style="fotn-size:16px;"><?php echo L('following_operation')?></span><br /><ul style="fotn-size:14px;"><li><a href="?m=collection&c=node&a=col_content&nodeid=<?php echo $nodeid?>&pc_hash=<?php echo $_SESSION['pc_hash']?>" target="right" onclick="window.top.art.dialog({id:\'test\'}).close()"><?php echo L('following_operation_1')?></a></li><li><a href="?m=collection&c=node&a=manage&menuid=957&pc_hash=<?php echo $_SESSION['pc_hash']?>" target="right" onclick="window.top.art.dialog({id:\'test\'}).close()"><?php echo L('following_operation_2')?></a></li></ul>',width:'400',height:'200'}); </script> <?php }?> </div> </div> </div> </body> </html>
PHP
<?php defined('IN_ADMIN') or exit('No permission resources.');?> <?php include $this->admin_tpl('header', 'admin');?> <div class="pad-10"> <div class="col-tab"> <ul class="tabBut cu-li"> <li class="on" id="tab_1"><?php echo L('url_list')?></li> </ul> <div class="content pad-10" id="show_div_1" style="height:auto"> <?php while ($pagesize_start <= $pagesize_end):?> <?php echo str_replace('(*)', $pagesize_start, $urlpage);$pagesize_start=$pagesize_start+$par_num;?> <hr size="1" /> <?php endwhile;?> </div> </div> </div> </body> </html>
PHP
<?php defined('IN_ADMIN') or exit('No permission resources.');?> <?php include $this->admin_tpl('header', 'admin');?> <script type="text/javascript"> $(document).ready(function() { $.formValidator.initConfig({formid:"myform",autotip:true,onerror:function(msg,obj){window.top.art.dialog({content:msg,lock:true,width:'200',height:'50'})}}); $("#name").formValidator({onshow:"<?php echo L('input').L('nodename')?>",onfocus:"<?php echo L('input').L('nodename')?>"}).inputValidator({min:1,onerror:"<?php echo L('input').L('nodename')?>"}).ajaxValidator({type : "get",url : "",data :"m=collection&c=node&a=public_name",datatype : "html",async:'false',success : function(data){ if( data == "1" ){return true;}else{return false;}},buttons: $("#dosubmit"),onerror : "<?php echo L('nodename').L('exists')?>",onwait : "<?php echo L('connecting')?>"}); }); </script> <div class="pad-10"> <form name="myform" action="?m=collection&c=node&a=copy&nodeid=<?php if(isset($nodeid)) echo $nodeid?>" method="post" id="myform"> <div class="common-form"> <table width="100%" class="table_form"> <tr> <td width="120"><?php echo L('had_collected_from_the_roll')?>:</td> <td> <?php if(isset($data['name'])) echo $data['name']?> </td> </tr> <tr> <td width="120"><?php echo L('the_new_gathering')?>:</td> <td> <input type="text" name="name" id="name" class="input-text" value="" /> </td> </tr> </table> <input name="dosubmit" type="submit" id="dosubmit" value="<?php echo L('submit')?>" class="dialog"> </div> </div> </form> </body> </html>
PHP
<?php defined('IN_ADMIN') or exit('No permission resources.');?> <?php include $this->admin_tpl('header', 'admin');?> <style> <!-- #show_funcs_div{position:absolute ;background-color:#fff;border:#D0D0D0 solid 1px; border-top-style:none;display:none} .show_funcs_div{height:200px;overflow-y:scroll;} #show_funcs_div ul li{padding:3px 0 3px 5px;} #show_funcs_div ul li:hover{background-color:#EEEEEE;cursor:hand;} .funcs_div{background:#fff; width:160px; border:solid #D0D0D0 1px;} .funcs{border:none;background:none} --> </style> <div id="show_funcs_div" onmouseover="clearh()" onmouseout="hidden_funcs_div_1()"> <ul> <?php if (isset($spider_funs) && is_array($spider_funs)) foreach ($spider_funs as $k=>$v):?> <li onclick="insert_txt('<?php echo $k;?>')"><?php echo $v?>(<?php echo $k;?>)</li> <?php endforeach;?> </ul> </div> <div class="pad-lr-10"> <form name="myform" action="?m=collection&c=node&a=import_program_add&nodeid=<?php if(isset($nodeid)) echo $nodeid?>&type=<?php echo $type?>&ids=<?php echo $ids?>&catid=<?php echo $catid?>" method="post" id="myform"> <fieldset> <legend><?php echo L('the_new_publication_solutions')?></legend> <table width="100%" class="table_form"> <tr> <td width="120"><?php echo L('category')?>:</td> <td> <?php echo $cat['catname'];?> </td> </tr> <tr> <td width="120"><?php echo L('the_withdrawal_of_the_summary')?>:</td> <td> <label><input name="add_introduce" type="checkbox" value="1"><?php echo L('if_the_contents_of_intercepted')?></label><input type="text" name="introcude_length" value="200" size="3"><?php echo L('characters_to_a_summary_of_contents')?> </td> </tr> <tr> <td width="120"><?php echo L('the_withdrawal_of_thumbnails')?>:</td> <td> <label><input type='checkbox' name='auto_thumb' value="1"><?php echo L('whether_access_to_the_content_of')?></label><input type="text" name="auto_thumb_no" value="1" size="2" class=""><?php echo L('picture_a_caption_pictures')?> </td> </tr> <tr> <td width="120"><?php echo L('import_article_state')?>:</td> <td> <?php if(!empty($cat['setting']['workflowid'])) {echo form::radio(array('1'=>L('pendingtrial'), '99'=>L('fantaoboys')), '1', 'name="content_status"');} else {echo form::radio(array('99'=>L('fantaoboys')), '99', 'name="content_status"');}?> </td> </tr> </table> </fieldset> <div class="bk10"></div> <fieldset> <legend><?php echo L('corresponding_labels_and_a_database_ties') ?></legend> <div class="table-list"> <table width="100%" cellspacing="0"> <thead> <tr> <th align="left"><?php echo L('the_original_database_field')?></th> <th align="left"><?php echo L('explain')?></th> <th align="left"><?php echo L('label_field__collected_with_the_result_')?></th> <th align="left"><?php echo L('handler_functions')?></th> </tr> </thead> <tbody> <?php foreach($model as $k=>$v) { if (in_array($v['formtype'], array('catid', 'typeid', 'posids', 'groupid', 'readpoint','template'))) continue; ?> <tr> <td align="left"><?php echo $v['field']?></td> <td align="left"><?php echo $v['name']?></td> <td align="left"><input type="hidden" name="model_field[]" value="<?php echo $v['field']?>"><?php echo form::select($node_field, (in_array($v['field'], array('inputtime', 'updatetime')) ? 'time' : $v['field']), 'name="node_field[]"')?></td> <td align="left"><div class="funcs_div"><input type="text" name="funcs[]" class="funcs"><a href="javascript:void(0)" onclick="clearh();show_funcs(this);" onmouseout="hidden_funcs_div_1()"><img src="<?php echo IMG_PATH?>admin_img/toggle-collapse-dark.png"></a></div></td> </tr> <?php } ?> </tbody> </table> </fieldset> <div class="btn"> <input type="submit" class="button" name="dosubmit" value="<?php echo L('submit')?>"/> </div> <div id="pages"><?php echo $pages?></div> </div> </form> </div> <script type="text/javascript"> <!-- var div_obj; function show_funcs(obj) { div_obj = $(obj).parent('div'); var pos = $(obj).parent('div').offset(); $('#show_funcs_div').css('left',pos.left+'px').css('top',(pos.top+24)+'px').width($(obj).parent().width()).show(); } var s = 0; var h; function hidden_funcs_div_2() { s++; if(s>=5) { $('#show_funcs_div').hide().css('left','0px').css('top','0px'); clearInterval(h); s = 0; } } function clearh(){ if(h)clearInterval(h); } function hidden_funcs_div_1() { h = setInterval("hidden_funcs_div_2()", 1); } function insert_txt(obj) { $(div_obj).children('input').val(obj); } //--> </script> </body> </html>
PHP
<?php defined('IN_ADMIN') or exit('No permission resources.');?> <?php include $this->admin_tpl('header', 'admin');?> <div class="pad-lr-10"> <fieldset> <legend><?php echo L('the_new_publication_solutions')?></legend> <form name="myform" action="?" method="get" id="myform"> <table width="100%" class="table_form"> <tr> <td width="120"><?php echo L('category')?>:</td> <td> <?php echo form::select_category('', '', 'name="catid"', L('please_choose'), 0, 0, 1)?> </td> </tr> </table> <input type="hidden" name="m" value="collection"> <input type="hidden" name="c" value="node"> <input type="hidden" name="a" value="import_program_add"> <input type="hidden" name="nodeid" value="<?php if(isset($nodeid)) echo $nodeid?>"> <input type="hidden" name="type" value="<?php echo $type?>"> <input type="hidden" name="ids" value="<?php echo $ids?>"> <input type="submit" id="dosubmit" class="button" value="<?php echo L('submit')?>"> </form> </fieldset> <div class="bk15"></div> <fieldset> <legend><?php echo L('publish_the_list')?></legend> <form name="myform" action="?" method="get" > <div class="bk15"></div> <?php foreach($program_list as $k=>$v) { echo form::radio(array($v['id']=>$cat[$v['catid']]['catname']), '', 'name="programid"', 150); ?> <span style="margin-right:10px;"><a href="?m=collection&c=node&a=import_program_del&id=<?php echo $v['id']?>" style="color:#ccc"><?php echo L('delete')?></a></span> <?php } ?> </fieldset> <input type="hidden" name="m" value="collection"> <input type="hidden" name="c" value="node"> <input type="hidden" name="a" value="import_content"> <input type="hidden" name="nodeid" value="<?php if(isset($nodeid)) echo $nodeid?>"> <input type="hidden" name="type" value="<?php echo $type?>"> <input type="hidden" name="ids" value="<?php echo $ids?>"> <div class="btn"> <label for="check_box"><input type="submit" class="button" name="dosubmit" value="<?php echo L('submit')?>"/> </div> </div> </form> </div> <script type="text/javascript"> <!-- window.top.$('#display_center_id').css('display','none'); //--> </script> </body> </html>
PHP
<?php defined('IN_ADMIN') or exit('No permission resources.');?> <?php include $this->admin_tpl('header', 'admin');?> <script type="text/javascript"> $(document).ready(function() { $.formValidator.initConfig({formid:"myform",autotip:true,onerror:function(msg,obj){window.top.art.dialog({content:msg,lock:true,width:'200',height:'50'})}}); $("#name").formValidator({onshow:"<?php echo L('input').L('nodename')?>",onfocus:"<?php echo L('input').L('nodename')?>"}).inputValidator({min:1,onerror:"<?php echo L('input').L('nodename')?>"}).ajaxValidator({type : "get",url : "",data :"m=collection&c=node&a=public_name",datatype : "html",async:'false',success : function(data){ if( data == "1" ){return true;}else{return false;}},buttons: $("#dosubmit"),onerror : "<?php echo L('nodename').L('exists')?>",onwait : "<?php echo L('connecting')?>"}); }); </script> <div class="pad-10"> <form name="myform" action="?m=collection&c=node&a=node_import" method="post" id="myform" enctype="multipart/form-data"> <div class="common-form"> <table width="100%" class="table_form"> <tr> <td width="120"><?php echo L('collect_call')?>:</td> <td> <input type="text" name="name" id="name" class="input-text" value="" /> </td> </tr> <tr> <td width="120"><?php echo L('cfg')?>:</td> <td> <input type="file" name="file" class="input-text" value="" /> <br /><?php echo L('only_support_txt_file_upload')?> </td> </tr> </table> <input name="dosubmit" type="submit" id="dosubmit" value="<?php echo L('submit')?>" class="dialog"> </div> </div> </form> </body> </html>
PHP
<?php defined('IN_ADMIN') or exit('No permission resources.');?> <?php include $this->admin_tpl('header', 'admin');?> <div class="subnav"> <h1 class="title-2 line-x"><?php echo $node['name']?> - <?php echo L('content_list')?></h1> </div> <div class="pad-lr-10"> <div class="col-tab"> <ul class="tabBut cu-li"> <li <?php if(empty($status)) echo 'class="on" '?>id="tab_1"><a href="?m=collection&c=node&a=publist&nodeid=<?php echo $nodeid?>"><?php echo L('all')?></a></li> <li <?php if($status==1) echo 'class="on" '?>id="tab_1"><a href="?m=collection&c=node&a=publist&nodeid=<?php echo $nodeid?>&status=1"><?php echo L('if_bsnap_then')?></a></li> <li <?php if($status==2) echo 'class="on" '?> id="tab_2"><a href="?m=collection&c=node&a=publist&nodeid=<?php echo $nodeid?>&status=2"><?php echo L('spidered')?></a></li> <li <?php if($status==3) echo 'class="on" '?> id="tab_3"><a href="?m=collection&c=node&a=publist&nodeid=<?php echo $nodeid?>&status=3"><?php echo L('imported')?></a></li> </ul> <div class="content pad-10" id="show_div_1" style="height:auto"> <form name="myform" id="myform" action="" method="get"> <div id="form_"> <input type="hidden" name="m" value="collection" /> <input type="hidden" name="c" value="node" /> <input type="hidden" name="a" value="content_del" /> </div> <div class="table-list"> <table width="100%" cellspacing="0"> <thead> <tr> <th align="left" width="20"><input type="checkbox" value="" id="check_box" onclick="selectall('id[]');"></th> <th align="left"><?php echo L('status')?></th> <th align="left"><?php echo L('title')?></th> <th align="left"><?php echo L('url')?></th> <th align="left"><?php echo L('operation')?></th> </tr> </thead> <tbody> <?php if(is_array($data) && !empty($data))foreach($data as $k=>$v) { ?> <tr> <td align="left"><input type="checkbox" value="<?php echo $v['id']?>" name="id[]"></td> <td align="left"><?php if ($v['status'] == '0') {echo L('if_bsnap_then');} elseif ($v['status'] == 1) {echo L('spidered');} elseif ($v['status'] == 2) {echo L('imported');} ?></td> <td align="left"><?php echo $v['title']?></td> <td align="left"><?php echo $v['url']?></td> <td align="left"><a href="javascript:void(0)" onclick="$('#tab_<?php echo $v['id']?>').toggle()"><?php echo L('view')?></a></td> </tr> <tr id="tab_<?php echo $v['id']?>" style="display:none"> <td align="left" colspan="5"><textarea style="width:98%;height:300px;"><?php echo htmlspecialchars($v['data'])?></textarea></td> </tr> <?php } ?> </tbody> </table> <div class="btn"> <label for="check_box"><?php echo L('select_all')?>/<?php echo L('cancel')?></label> <input type="submit" class="button" name="dosubmit" value="<?php echo L('delete')?>" onclick="re_url('m=collection&c=node&a=content_del&nodeid=<?php echo $nodeid?>');return check_checkbox(1);"/> <input type="submit" class="button" name="dosubmit" onclick="re_url('m=collection&c=node&a=content_del&nodeid=<?php echo $nodeid?>&history=1');return check_checkbox(1);" value="<?php echo L('also_delete_the_historical')?>"/> <input type="submit" class="button" name="dosubmit" onclick="re_url('m=collection&c=node&a=import&nodeid=<?php echo $nodeid?>');return check_checkbox();" value="<?php echo L('import_selected')?>"/> <input type="submit" class="button" name="dosubmit" onclick="re_url('m=collection&c=node&a=import&type=all&nodeid=<?php echo $nodeid?>')" value="<?php echo L('import_all')?>"/> </div> <div id="pages"><?php echo $pages?></div> </div> </form> </div> </div> <script type="text/javascript"> <!-- function re_url(url) { var urls = url.split('&'); var num = urls.length; var str = ''; for (var i=0;i<num;i++){ var a = urls[i].split('='); str +='<input type="hidden" name="'+a[0]+'" value="'+a[1]+'" />'; } $('#form_').html(str); } function check_checkbox(obj) { var checked = 0; $("input[type='checkbox'][name='id[]']").each(function (i,n){if (this.checked) { checked = 1; }}); if (checked != 0) { if (obj) { if (confirm('<?php echo L('sure_delete')?>')) { return true; } else { return false; } } return true; } else { alert('<?php echo L('select_article')?>'); return false; } } window.top.$('#display_center_id').css('display','none'); //--> </script> </body> </html>
PHP
<?php defined('IN_PHPCMS') or exit('No permission resources.'); $spider_funs = array( 'trim'=>'过滤空格', 'spider_photos'=>'处理为组图', 'spider_downurls'=>'处理为下载列表', 'spider_keywords'=>'获取关键字', );
PHP
<?php defined('IN_PHPCMS') or exit('No permission resources.'); function spider_photos($str) { $field = $GLOBALS['field']; $_POST[$field.'_url'] = array(); preg_match_all('/<img[^>]*src=[\'"]?([^>\'"\s]*)[\'"]?[^>]*>/i', $str, $out); $array = array(); if (isset($out[1]))foreach ($out[1] as $v) { $_POST[$field.'_url'][] = $v; } return '1'; } function spider_downurls($str) { $field = $GLOBALS['field']; $_POST[$field.'_fileurl'] = array(); preg_match_all('/<a[^>]*href=[\'"]?([^>\'"\s]*)[\'"]?[^>]*>/i', $str, $out); $array = array(); if (isset($out[1]))foreach ($out[1] as $v) { $_POST[$field.'_fileurl'][] = $v; } return '1'; }
PHP
<?php defined('IN_PHPCMS') or exit('No permission resources.'); function spider_keywords($data) { $http = pc_base::load_sys_class('http'); if(CHARSET == 'utf-8') { $data = iconv('utf-8', 'gbk', $data); } $http->post('http://tool.phpcms.cn/api/get_keywords.php', array('siteurl'=>APP_PATH, 'charset'=>CHARSET, 'data'=>$data, 'number'=>3)); if($http->is_ok()) { if(CHARSET != 'utf-8') { return $http->get_data(); } else { return iconv('gbk', 'utf-8', $http->get_data()); } } else { return $data; } }
PHP
<?php defined('IN_PHPCMS') or exit('No permission resources.'); class collection { protected static $url,$config; /** * 采集内容 * @param string $url 采集地址 * @param array $config 配置参数 * @param integer $page 分页采集模式 */ public static function get_content($url, $config, $page = 0) { set_time_limit(300); static $oldurl = array(); $page = intval($page) ? intval($page) : 0; if ($html = self::get_html($url, $config)) { if (empty($page)) { //获取标题 if ($config['title_rule']) { $title_rule = self::replace_sg($config['title_rule']); $data['title'] = self::replace_item(self::cut_html($html, $title_rule[0], $title_rule[1]), $config['title_html_rule']); } //获取作者 if ($config['author_rule']) { $author_rule = self::replace_sg($config['author_rule']); $data['author'] = self::replace_item(self::cut_html($html, $author_rule[0], $author_rule[1]), $config['author_html_rule']); } //获取来源 if ($config['comeform_rule']) { $comeform_rule = self::replace_sg($config['comeform_rule']); $data['comeform'] = self::replace_item(self::cut_html($html, $comeform_rule[0], $comeform_rule[1]), $config['comeform_html_rule']); } //获取时间 if ($config['time_rule']) { $time_rule = self::replace_sg($config['time_rule']); $data['time'] = strtotime(self::replace_item(self::cut_html($html, $time_rule[0], $time_rule[1]), $config['time_html_rule'])); } if (empty($data['time'])) $data['time'] = SYS_TIME; //对自定义数据进行采集 if ($config['customize_config'] = string2array($config['customize_config'])) { foreach ($config['customize_config'] as $k=>$v) { if (empty($v['rule'])) continue; $rule = self::replace_sg($v['rule']); $data[$v['en_name']] = self::replace_item(self::cut_html($html, $rule[0], $rule[1]), $v['html_rule']); } } } //获取内容 if ($config['content_rule']) { $content_rule = self::replace_sg($config['content_rule']); $data['content'] = self::replace_item(self::cut_html($html, $content_rule[0], $content_rule[1]), $config['content_html_rule']); } //处理分页 if (in_array($page, array(0,2)) && !empty($config['content_page_start']) && !empty($config['content_page_end'])) { $oldurl[] = $url; $tmp[] = $data['content']; $page_html = self::cut_html($html, $config['content_page_start'], $config['content_page_end']); //上下页模式 if ($config['content_page_rule'] == 2 && in_array($page, array(0,2)) && $page_html) { preg_match_all('/<a[^>]*href=[\'"]?([^>\'" ]*)[\'"]?[^>]*>([^<\/]*)<\/a>/i', $page_html, $out); if (!empty($out[1]) && !empty($out[2])) { foreach ($out[2] as $k=>$v) { if (strpos($v, $config['content_nextpage']) === false) continue; if ($out[1][$k] == '#') continue; $out[1][$k] = self::url_check($out[1][$k], $url, $config); if (in_array($out[1][$k], $oldurl)) continue; $oldurl[] = $out[1][$k]; $results = self::get_content($out[1][$k], $config, 2); if (!in_array($results['content'], $tmp)) $tmp[] = $results['content']; } } } //全部罗列模式 if ($config['content_page_rule'] == 1 && $page == 0 && $page_html) { preg_match_all('/<a[^>]*href=[\'"]?([^>\'" ]*)[\'"]?/i', $page_html, $out); if (is_array($out[1]) && !empty($out[1])) { $out = array_unique($out[1]); foreach ($out as $k=>$v) { if ($out[1][$k] == '#') continue; $v = self::url_check($v, $url, $config); $results = self::get_content($v, $config, 1); if (!in_array($results['content'], $tmp)) $tmp[] = $results['content']; } } } $data['content'] = $config['content_page'] == 1 ? implode('[page]', $tmp) : implode('', $tmp); } if ($page == 0) { self::$url = $url; self::$config = $config; $data['content'] = preg_replace('/<img[^>]*src=[\'"]?([^>\'"\s]*)[\'"]?[^>]*>/ie', "self::download_img('$0', '$1')", $data['content']); //下载内容中的图片到本地 if (empty($page) && !empty($data['content']) && $config['down_attachment'] == 1) { pc_base::load_sys_class('attachment','',0); $attachment = new attachment('collection','0',get_siteid()); $data['content'] = $attachment->download('content', $data['content'],$config['watermark']); } } return $data; } } /** * 转换图片地址为绝对路径,为下载做准备。 * @param array $out 图片地址 */ protected static function download_img($old, $out) { if (!empty($old) && !empty($out) && strpos($out, '://') === false) { return str_replace($out, self::url_check($out, self::$url, self::$config), $old); } else { return $old; } } /** * 得到需要采集的网页列表页 * @param array $config 配置参数 * @param integer $num 返回数 */ public static function url_list(&$config, $num = '') { $url = array(); switch ($config['sourcetype']) { case '1'://序列化 $num = empty($num) ? $config['pagesize_end'] : $num; for ($i = $config['pagesize_start']; $i <= $num; $i = $i + $config['par_num']) { $url[$i] = str_replace('(*)', $i, $config['urlpage']); } break; case '2'://多网址 $url = explode("\r\n", $config['urlpage']); break; case '3'://单一网址 case '4'://RSS $url[] = $config['urlpage']; break; } return $url; } /** * 获取文章网址 * @param string $url 采集地址 * @param array $config 配置 */ public static function get_url_lists($url, &$config) { if ($html = self::get_html($url, $config)) { if ($config['sourcetype'] == 4) { //RSS $xml = pc_base::load_sys_class('xml'); $html = $xml->xml_unserialize($html); if (pc_base::load_config('system', 'charset') == 'gbk') { $html = array_iconv($html, 'utf-8', 'gbk'); } $data = array(); if (is_array($html['rss']['channel']['item']))foreach ($html['rss']['channel']['item'] as $k=>$v) { $data[$k]['url'] = $v['link']; $data[$k]['title'] = $v['title']; } } else { $html = self::cut_html($html, $config['url_start'], $config['url_end']); $html = str_replace(array("\r", "\n"), '', $html); $html = str_replace(array("</a>", "</A>"), "</a>\n", $html); preg_match_all('/<a([^>]*)>([^\/a>].*)<\/a>/i', $html, $out); $out[1] = array_unique($out[1]); $out[2] = array_unique($out[2]); $data = array(); foreach ($out[1] as $k=>$v) { if (preg_match('/href=[\'"]?([^\'" ]*)[\'"]?/i', $v, $match_out)) { if ($config['url_contain']) { if (strpos($match_out[1], $config['url_contain']) === false) { continue; } } if ($config['url_except']) { if (strpos($match_out[1], $config['url_except']) !== false) { continue; } } $url2 = $match_out[1]; $url2 = self::url_check($url2, $url, $config); $data[$k]['url'] = $url2; $data[$k]['title'] = strip_tags($out[2][$k]); } else { continue; } } } return $data; } else { return false; } } /** * 获取远程HTML * @param string $url 获取地址 * @param array $config 配置 */ protected static function get_html($url, &$config) { if (!empty($url) && $html = @file_get_contents($url)) { if ($syscharset != $config['sourcecharset'] && $config['sourcetype'] != 4) { $html = iconv($config['sourcecharset'], CHARSET.'//IGNORE', $html); } return $html; } else { return false; } } /** * * HTML切取 * @param string $html 要进入切取的HTML代码 * @param string $start 开始 * @param string $end 结束 */ protected static function cut_html($html, $start, $end) { if (empty($html)) return false; $html = str_replace(array("\r", "\n"), "", $html); $start = str_replace(array("\r", "\n"), "", $start); $end = str_replace(array("\r", "\n"), "", $end); $html = explode(trim($start), $html); if(is_array($html)) $html = explode(trim($end), $html[1]); return $html[0]; } /** * 过滤代码 * @param string $html HTML代码 * @param array $config 过滤配置 */ protected static function replace_item($html, $config) { if (empty($config)) return $html; $config = explode("\n", $config); $patterns = $replace = array(); $p = 0; foreach ($config as $k=>$v) { if (empty($v)) continue; $c = explode('[|]', $v); $patterns[$k] = '/'.str_replace('/', '\/', $c[0]).'/i'; $replace[$k] = $c[1]; $p = 1; } return $p ? @preg_replace($patterns, $replace, $html) : false; } /** * 替换采集内容 * @param $html 采集规则 */ protected static function replace_sg($html) { $list = explode(L('[content]'), $html); if (is_array($list)) foreach ($list as $k=>$v) { $list[$k] = str_replace(array("\r", "\n"), '', trim($v)); } return $list; } /** * URL地址检查 * @param string $url 需要检查的URL * @param string $baseurl 基本URL * @param array $config 配置信息 */ protected static function url_check($url, $baseurl, $config) { $urlinfo = parse_url($baseurl); $baseurl = $urlinfo['scheme'].'://'.$urlinfo['host'].(substr($urlinfo['path'], -1, 1) === '/' ? substr($urlinfo['path'], 0, -1) : str_replace('\\', '/', dirname($urlinfo['path']))).'/'; if (strpos($url, '://') === false) { if ($url[0] == '/') { $url = $urlinfo['scheme'].'://'.$urlinfo['host'].$url; } else { if ($config['page_base']) { $url = $config['page_base'].$url; } else { $url = $baseurl.$url; } } } return $url; } }
PHP
<?php defined('IN_ADMIN') or exit('No permission resources.'); $show_dialog = 1; include $this->admin_tpl('header', 'admin'); ?> <div class="pad-lr-10"> <form name="myform" action="?m=vote&c=vote&a=delete" method="post" onsubmit="checkuid();return false;"> <div class="table-list"> <table width="100%" cellspacing="0"> <thead> <tr> <th width="35" align="center"><input type="checkbox" value="" id="check_box" onclick="selectall('subjectid[]');"></th> <th><?php echo L('title')?></th> <th width="40" align="center"><?php echo L('vote_num')?></th> <th width="68" align="center"><?php echo L('startdate')?></th> <th width="68" align="center"><?php echo L('enddate')?></th> <th width='68' align="center"><?php echo L('inputtime')?></th> <th width="180" align="center"><?php echo L('operations_manage')?></th> </tr> </thead> <tbody> <?php if(is_array($infos)){ foreach($infos as $info){ ?> <tr> <td align="center"><input type="checkbox" name="subjectid[]" value="<?php echo $info['subjectid']?>"></td> <td><a href="?m=vote&c=index&a=show&show_type=1&subjectid=<?php echo $info['subjectid']?>&siteid=<?php echo $info['siteid'];?>" title="<?php echo L('check_vote')?>" target="_blank"><?php echo $info['subject'];?></a> <font color=red><?php if($info['enabled']==0)echo L('lock'); ?></font></td> <td align="center"><font color=blue><?php echo $info['votenumber']?></font> </td> <td align="center"><?php echo $info['fromdate'];?></td> <td align="center"><?php echo $info['todate'];?></td> <td align="center"><?php echo date("Y-m-d",$info['addtime']);?></td> <td align="center"><a href='###' onclick="statistics(<?php echo $info['subjectid']?>, '<?php echo new_addslashes($info['subject'])?>')"> <?php echo L('statistics')?></a> | <a href="###" onclick="edit(<?php echo $info['subjectid']?>, '<?php echo new_addslashes($info['subject'])?>')" title="<?php echo L('edit')?>"><?php echo L('edit')?></a> | <a href="javascript:call(<?php echo new_addslashes($info['subjectid'])?>);void(0);"><?php echo L('call_js_code')?></a> | <a href='?m=vote&c=vote&a=delete&subjectid=<?php echo new_addslashes($info['subjectid'])?>' onClick="return confirm('<?php echo L('vote_confirm_del')?>')"><?php echo L('delete')?></a> </td> </tr> <?php } } ?> </tbody> </table> <div class="btn"><a href="#" onClick="javascript:$('input[type=checkbox]').attr('checked', true)"><?php echo L('selected_all')?></a>/<a href="#" onClick="javascript:$('input[type=checkbox]').attr('checked', false)"><?php echo L('cancel')?></a> <input name="submit" type="submit" class="button" value="<?php echo L('remove_all_selected')?>" onClick="return confirm('<?php echo L('vote_confirm_del')?>')">&nbsp;&nbsp;</div> <div id="pages"><?php echo $pages?></div> </form> </div> <script type="text/javascript"> function edit(id, name) { window.top.art.dialog({id:'edit'}).close(); window.top.art.dialog({title:'<?php echo L('edit')?> '+name+' ',id:'edit',iframe:'?m=vote&c=vote&a=edit&subjectid='+id,width:'700',height:'450'}, function(){var d = window.top.art.dialog({id:'edit'}).data.iframe;var form = d.document.getElementById('dosubmit');form.click();return false;}, function(){window.top.art.dialog({id:'edit'}).close()}); } function statistics(id, name) { window.top.art.dialog({id:'statistics'}).close(); window.top.art.dialog({title:'<?php echo L('statistics')?> '+name+' ',id:'edit',iframe:'?m=vote&c=vote&a=statistics&subjectid='+id,width:'700',height:'350'}, function(){var d = window.top.art.dialog({id:'statistics'}).data.iframe;var form = d.document.getElementById('dosubmit');form.click();return false;}, function(){window.top.art.dialog({id:'statistics'}).close()}); } function call(id) { window.top.art.dialog({id:'call'}).close(); window.top.art.dialog({title:'<?php echo L('vote')?><?php echo L('linkage_calling_code','','admin');?>', id:'call', iframe:'?m=vote&c=vote&a=public_call&subjectid='+id, width:'600px', height:'470px'}, function(){window.top.art.dialog({id:'call'}).close();}, function(){window.top.art.dialog({id:'call'}).close();}) } function checkuid() { var ids=''; $("input[name='subjectid[]']:checked").each(function(i, n){ ids += $(n).val() + ','; }); if(ids=='') { window.top.art.dialog({content:'<?php echo L('before_select_operation')?>',lock:true,width:'200',height:'50',time:1.5},function(){}); return false; } else { myform.submit(); } } </script> </body> </html>
PHP
<?php defined('IN_ADMIN') or exit('No permission resources.'); ?> <form style="border: medium none;" id="voteform<?php echo $subjectid;?>" method="post" action="{APP_PATH}index.php?m=vote&c=index&a=post&subjectid=<?php echo $subjectid;?>"> <dl> <dt><?php echo $subject;?></dt> </dl> <dl> <?php if(is_array($options)) { $i=0; foreach($options as $optionid=>$option){ $i++; ?> <dd> &nbsp;&nbsp;<input type="radio" value="<?php echo $option['optionid']?>" name="radio[]" id="radio"> <?php echo $option['option'];?> </dd> <?php }}?> <input type="hidden" name="voteid" value="<?php echo $subjectid;?>"> </dl> <p> &nbsp;&nbsp; <input type="submit" value="<?php echo L('submit')?>" name="dosubmit" /> &nbsp;&nbsp; <a href="<?php echo SITE_PROTOCOL.SITE_URL?>/index.php?m=vote&c=index&a=result&id=<?php echo $subjectid;?>"><?php echo L('vote_showresult')?></a> </p> </form>
PHP
<?php defined('IN_ADMIN') or exit('No permission resources.'); include $this->admin_tpl('header','admin'); ?> <script type="text/javascript"> <!-- $(function(){ $.formValidator.initConfig({formid:"myform",autotip:true,onerror:function(msg,obj){window.top.art.dialog({content:msg,lock:true,width:'200',height:'50'}, function(){this.close();$(obj).focus();})}}); $("#subject_title").formValidator({onshow:"<?php echo L("input").L('vote_title')?>",onfocus:"<?php echo L("input").L('vote_title')?>"}).inputValidator({min:1,onerror:"<?php echo L("input").L('vote_title')?>"}).regexValidator({regexp:"notempty",datatype:"enum",param:'i',onerror:"<?php echo L('input_not_space')?>"}).ajaxValidator({type : "get",url : "",data :"m=vote&c=vote&a=public_name",datatype : "html",async:'false',success : function(data){ if( data == "1" ){return true;}else{return false;}},buttons: $("#dosubmit"),onerror : "<?php echo L('vote_title').L('exists')?>",onwait : "<?php echo L('connecting')?>"}); $("#option1").formValidator({onshow:"<?php echo L("input").L('vote_option')?>",onfocus:"<?php echo L("input").L('vote_option')?>"}).inputValidator({min:1,onerror:"<?php echo L("input").L('vote_option')?>"}).regexValidator({regexp:"notempty",datatype:"enum",param:'i',onerror:"<?php echo L('input_not_space')?>"}); $("#option2").formValidator({onshow:"<?php echo L("input").L('vote_option')?>",onfocus:"<?php echo L("input").L('vote_option')?>"}).inputValidator({min:1,onerror:"<?php echo L("input").L('vote_option')?>"}).regexValidator({regexp:"notempty",datatype:"enum",param:'i',onerror:"<?php echo L('input_not_space')?>"}); $("#fromdate").formValidator({onshow:"<?php echo L('select').L('fromdate')?>",onfocus:"<?php echo L('select').L('fromdate')?>",oncorrect:"<?php echo L('time_is_ok'); ?>"}).inputValidator(); $("#todate").formValidator({onshow:"<?php echo L('select').L('todate')?>",onfocus:"<?php echo L('select').L('todate')?>",oncorrect:"<?php echo L('time_is_ok');?>"}).inputValidator(); $('#style').formValidator({onshow:"<?php echo L('select_style')?>",onfocus:"<?php echo L('select_style')?>",oncorrect:"<?php echo L('right_all')?>"}).inputValidator({min:1,onerror:"<?php echo L('select_style')?>"}); }); //--> </script> <div class="pad_10"> <form action="?m=vote&c=vote&a=add" method="post" name="myform" id="myform"> <table cellpadding="2" cellspacing="1" class="table_form" width="100%"> <tr> <th width="100"><?php echo L('vote_title')?> :</th> <td><input type="text" name="subject[subject]" id="subject_title" size="30" class="input-text"></td> </tr> <tr> <th width="20%"><?php echo L('select_type')?> :</th> <td><select name="subject[ischeckbox]" id="" onchange="AdsType(this.value)"> <option value="0"><?php echo L('radio');?></option> <option value="1"><?php echo L('checkbox');?></option> </select></td> </tr> <tr id="SizeFormat" style="display: none;"> <th></th> <td><label><?php echo L('minval')?></label>&nbsp;&nbsp;<input name="subject[minval]" class="input-text" type="text" size="5"> <?php echo L('item')?> &nbsp;&nbsp;&nbsp;&nbsp; <label><?php echo L('maxval')?></label>&nbsp;&nbsp;<input name="subject[maxval]" type="text" class="input-text" size="5"> <?php echo L('item')?></td> </tr> <tr> <th width="20%"><?php echo L('vote_option')?> :</th> <td> <input type="button" id="addItem" value="<?php echo L('add_option')?>" class="button" onclick="add_option()"> <div id="option_list_1"> <div><br> <input type="text" name="option[]" id="option1" size="40" require="true" id="opt1"/></div> <div><br> <input type="text" name="option[]" id="option2" size="40" id="opt2" /></div> </div> <div id="new_option"></div> </td> </tr> <tr> <th><?php echo L('fromdate')?> :</th> <td><?php echo form::date('subject[fromdate]', '', '')?></td> </tr> <tr> <th><?php echo L('todate')?> :</th> <td><?php echo form::date('subject[todate]', '', '')?></td> </tr> <tr> <th><?php echo L('vote_description')?></th> <td><textarea name="subject[description]" id="description" cols="60" rows="6"></textarea></td> </tr> <tr> <th><?php echo L('allowview')?>:</th> <td><input name="subject[allowview]" type="radio" value="1" checked>&nbsp;<?php echo L('allow')?>&nbsp;&nbsp;<input name="subject[allowview]" type="radio" value="0">&nbsp;<?php echo L('not_allow')?></td> </tr> <tr> <th><?php echo L('allowguest')?>:</th> <td><input name="subject[allowguest]" type="radio" value="1" <?php if($allowguest == 1) {?>checked<?php }?>>&nbsp;<?php echo L('yes')?>&nbsp;&nbsp;<input name="subject[allowguest]" type="radio" value="0" <?php if($allowguest == 0) {?>checked<?php }?>>&nbsp;<?php echo L('no')?></td> </tr> <tr> <th><?php echo L('credit')?>:</th> <td><input name="subject[credit]" type="text" value="<?php echo $credit;?>" size='5'></td> </tr> <tr> <th><?php echo L('interval')?>: </th> <td> <input type="text" name="subject[interval]" value="<?php echo $interval;?>" size='5' /> <?php echo L('more_ip')?>,<font color=red>0</font> <?php echo L('one_ip')?></td> </tr> <tr> <th><?php echo L('vote_style')?>:</th> <td> <?php echo form::select($template_list, $default_style, 'name="vote_subject[style]" id="style" onchange="load_file_list(this.value)"', L('please_select'))?> </td> </tr> <tr> <th><?php echo L('template')?>:</th> <td id="show_template"> <?php echo form::select_template($default_style, 'vote', $vote_tp_template, 'name="vote_subject[vote_tp_template]"', 'vote_tp');?> </td> </tr> <tr> <th><?php echo L('enabled')?>:</th> <td><input name="subject[enabled]" type="radio" value="1" <?php if($enabled == 1) {?>checked<?php }?>>&nbsp;<?php echo L('yes')?>&nbsp;&nbsp;<input name="subject[enabled]" type="radio" value="0" <?php if($enabled == 0) {?>checked<?php }?>>&nbsp;<?php echo L('no')?></td> </tr> <tr> <th></th> <td> <input type="hidden"name="from_api" value="<?php echo $_GET['from_api'];?>"> <input type="submit" name="dosubmit" id="dosubmit" class="dialog" value=" <?php echo L('submit')?> "></td> </tr> </table> </form> </div> </body> </html> <script language="javascript" type="text/javascript"> function AdsType(adstype) { $('#SizeFormat').css('display', 'none'); if(adstype=='0') { } else if(adstype=='1') { $('#SizeFormat').css('display', ''); } } $('#AlignBox').click( function (){ if($('#AlignBox').attr('checked')) { $('#PaddingLeft').attr('disabled', true); $('#PaddingTop').attr('disabled', true); } else { $('#PaddingLeft').attr('disabled', false); $('#PaddingTop').attr('disabled', false); } }); </script> <script language="javascript"> var i = 1; function add_option() { //var i = 1; var htmloptions = ''; htmloptions += '<div id='+i+'><span><br><input type="text" name="option[]" size="40" msg="<?php echo L('must_input')?>" value="" class="input-text"/><input type="button" value="<?php echo L('del')?>" onclick="del('+i+')" class="button"/><br></span></div>'; $(htmloptions).appendTo('#new_option'); var htmloptions = ''; i = i+1; } function del(o){ $("div [id=\'"+o+"\']").remove(); } function load_file_list(id) { $.getJSON('?m=admin&c=category&a=public_tpl_file_list&style='+id+'&module=vote&templates=vote_tp&name=vote_subject&pc_hash='+pc_hash, function(data){$('#show_template').html(data.vote_tp_template);}); } </script>
PHP
<?php defined('IN_ADMIN') or exit('No permission resources.'); $show_dialog = 1; include $this->admin_tpl('header', 'admin'); ?> <div class="pad-10"> <div class="col-tab"> <ul class="tabBut cu-li"> <li class="on"><a href="?m=vote&c=vote&a=statistics_userlist&subjectid=<?php echo $subjectid;?>"><?php echo L('user_list')?></a></li> <li><a href="?m=vote&c=vote&a=statistics&subjectid=<?php echo $subjectid;?>"><?php echo L('vote_result')?></a></li> </ul> <div class="content pad-10" style="height:auto"> <form name="myform" action="?m=vote&c=vote&a=delete_statistics" method="post"> <div class="table-list"> <br> <table width="100%" cellspacing="0"> <thead> <tr> <th><?php echo L('username')?></th> <th width="155" align="center"><?php echo L('up_vote_time')?></th> <th width="14%" align="center"><?php echo L('ip')?></th> </tr> </thead> <tbody> <?php if(is_array($infos)){ foreach($infos as $info){ ?> <tr> <td><?php if($info['username']=="")echo L('guest');else echo $info['username']?></td> <td align="center" width="155"><?php echo date("Y-m-d h-i",$info['time']);?></td> <td align="center" width="14%"><?php echo $info['ip'];?></td> </tr> <?php } } ?> </tbody> </table> <div id="pages"><?php echo $pages?></div> </form> </div> </div> </div> </body> </html> <script type="text/javascript"> function edit(id, name) { window.top.art.dialog({id:'edit'}).close(); window.top.art.dialog({title:'<?php echo L('edit')?> '+name+' ',id:'edit',iframe:'?m=vote&c=vote&a=edit&subjectid='+id,width:'700',height:'450'}, function(){var d = window.top.art.dialog({id:'edit'}).data.iframe;var form = d.document.getElementById('dosubmit');form.click();return false;}, function(){window.top.art.dialog({id:'edit'}).close()}); } </script>
PHP
<?php defined('IN_ADMIN') or exit('No permission resources.'); $show_header = $show_validator = $show_scroll = 1; include $this->admin_tpl('header', 'admin'); ?> <div class="pad-10"> <h2 class="title-1 f14 lh28">(<?php echo $r['subject'];?>)<?php echo L('vote_call')?></h2> <div class="bk10"></div> <div class="explain-col"> <strong><?php echo L('vote_call_info')?>:</strong><br /> <?php echo L('vote_call_infos')?> </div> <div class="bk10"></div> <fieldset> <legend><?php echo L('vote_call_1')?></legend> <?php echo L('vote_phpcall')?><br /> <input name="jscode1" id="jscode1" value='<script language="javascript" src="<?php echo APP_PATH;?>index.php?m=vote&c=index&a=show&action=js&subjectid=<?php echo $r['subjectid']?>&type=3"></script>' style="width:410px"> <input type="button" onclick="$('#jscode1').select();document.execCommand('Copy');" value="<?php echo L('copy_code')?>" class="button" style="width:114px"> </fieldset> <div class="bk10"></div> <fieldset> <legend><?php echo L('vote_call_2')?></legend> <?php echo L('vote_phpcall')?><br /> <input name="jscode2" id="jscode2" value='<script language="javascript" src="<?php echo APP_PATH;?>index.php?m=vote&c=index&a=show&action=js&subjectid=<?php echo $r['subjectid']?>&type=2"></script>' style="width:410px"> <input type="button" onclick="$('#jscode2').select();document.execCommand('Copy');" value="<?php echo L('copy_code')?>" class="button" style="width:114px"> </fieldset> <div class="bk10"></div> <fieldset> <legend><?php echo L('vote_jscall')?></legend> <?php echo L('vote_jscall_info')?><br /> <input name="jscode2" id="jscode3" value='<script language="javascript" src="<?php echo APP_PATH;?>caches/vote_js/vote_<?php echo $r['subjectid']?>.js"></script>' style="width:410px"> <input type="button" onclick="$('#jscode3').select();document.execCommand('Copy');" value="<?php echo L('copy_code')?>" class="button" style="width:114px"> </fieldset> </div> </body> </html>
PHP