vtlib 文件夹,中间存储了 vTiger 的开发库。

This commit is contained in:
YUCHENG HU 2013-01-30 22:11:57 -05:00
parent 1431ad5b82
commit 8f9852d0e3
16 changed files with 19056 additions and 0 deletions

120
vtlib/Vtiger/Profile.php Normal file
View File

@ -0,0 +1,120 @@
<?php
/*+**********************************************************************************
* The contents of this file are subject to the vtiger CRM Public License Version 1.0
* ("License"); You may not use this file except in compliance with the License
* The Original Code is: vtiger CRM Open Source
* The Initial Developer of the Original Code is vtiger.
* Portions created by vtiger are Copyright (C) vtiger.
* All Rights Reserved.
************************************************************************************/
include_once('vtlib/Vtiger/Utils.php');
/**
* Provides API to work with vtiger CRM Profile
* @package vtlib
*/
class Vtiger_Profile {
/**
* Helper function to log messages
* @param String Message to log
* @param Boolean true appends linebreak, false to avoid it
* @access private
*/
static function log($message, $delimit=true) {
Vtiger_Utils::Log($message, $delimit);
}
/**
* Initialize profile setup for Field
* @param Vtiger_Field Instance of the field
* @access private
*/
static function initForField($fieldInstance) {
global $adb;
// Allow field access to all
$adb->pquery("INSERT INTO vtiger_def_org_field (tabid, fieldid, visible, readonly) VALUES(?,?,?,?)",
Array($fieldInstance->getModuleId(), $fieldInstance->id, '0', '0'));
$profileids = self::getAllIds();
foreach($profileids as $profileid) {
$adb->pquery("INSERT INTO vtiger_profile2field (profileid, tabid, fieldid, visible, readonly) VALUES(?,?,?,?,?)",
Array($profileid, $fieldInstance->getModuleId(), $fieldInstance->id, '0', '0'));
}
}
/**
* Delete profile information related with field.
* @param Vtiger_Field Instance of the field
* @access private
*/
static function deleteForField($fieldInstance) {
global $adb;
$adb->pquery("DELETE FROM vtiger_def_org_field WHERE fieldid=?", Array($fieldInstance->id));
$adb->pquery("DELETE FROM vtiger_profile2field WHERE fieldid=?", Array($fieldInstance->id));
}
/**
* Get all the existing profile ids
* @access private
*/
static function getAllIds() {
global $adb;
$profileids = Array();
$result = $adb->query('SELECT profileid FROM vtiger_profile');
for($index = 0; $index < $adb->num_rows($result); ++$index) {
$profileids[] = $adb->query_result($result, $index, 'profileid');
}
return $profileids;
}
/**
* Initialize profile setup for the module
* @param Vtiger_Module Instance of module
* @access private
*/
static function initForModule($moduleInstance) {
global $adb;
$actionids = Array();
$result = $adb->query("SELECT actionid from vtiger_actionmapping WHERE actionname IN
('Save','EditView','Delete','index','DetailView')");
/*
* NOTE: Other actionname (actionid >= 5) is considered as utility (tools) for a profile.
* Gather all the actionid for associating to profile.
*/
for($index = 0; $index < $adb->num_rows($result); ++$index) {
$actionids[] = $adb->query_result($result, $index, 'actionid');
}
$profileids = self::getAllIds();
foreach($profileids as $profileid) {
$adb->pquery("INSERT INTO vtiger_profile2tab (profileid, tabid, permissions) VALUES (?,?,?)",
Array($profileid, $moduleInstance->id, 0));
if($moduleInstance->isentitytype) {
foreach($actionids as $actionid) {
$adb->pquery(
"INSERT INTO vtiger_profile2standardpermissions (profileid, tabid, Operation, permissions) VALUES(?,?,?,?)",
Array($profileid, $moduleInstance->id, $actionid, 0));
}
}
}
self::log("Initializing module permissions ... DONE");
}
/**
* Delete profile setup of the module
* @param Vtiger_Module Instance of module
* @access private
*/
static function deleteForModule($moduleInstance) {
global $adb;
$adb->pquery("DELETE FROM vtiger_profile2tab WHERE tabid=?", Array($moduleInstance->id));
$adb->pquery("DELETE FROM vtiger_profile2standardpermissions WHERE tabid=?", Array($moduleInstance->id));
}
}
?>

122
vtlib/Vtiger/Unzip.php Normal file
View File

@ -0,0 +1,122 @@
<?php
/*+**********************************************************************************
* The contents of this file are subject to the vtiger CRM Public License Version 1.0
* ("License"); You may not use this file except in compliance with the License
* The Original Code is: vtiger CRM Open Source
* The Initial Developer of the Original Code is vtiger.
* Portions created by vtiger are Copyright (C) vtiger.
* All Rights Reserved.
************************************************************************************/
require_once('vtlib/thirdparty/dUnzip2.inc.php');
/**
* Provides API to make working with zip file extractions easy
* @package vtlib
*/
class Vtiger_Unzip extends dUnzip2 {
/**
* Check existence of path in the given array
* @access private
*/
function __checkPathInArray($path, $pathArray) {
foreach($pathArray as $checkPath) {
if(strpos($path, $checkPath) === 0)
return true;
}
return false;
}
/**
* Check if the file path is directory
* @param String Zip file path
*/
function isdir($filepath) {
if(substr($filepath, -1, 1) == "/") return true;
return false;
}
/**
* Extended unzipAll function (look at base class)
* Allows you to rename while unzipping and handle exclusions.
* @access private
*/
Function unzipAllEx($targetDir=false, $includeExclude=false, $renamePaths=false, $ignoreFiles=false,
$baseDir="", $applyChmod=0777){
// We want to always maintain the structure
$maintainStructure = true;
if($targetDir === false)
$targetDir = dirname(__FILE__)."/";
if($renamePaths === false) $renamePaths = Array();
/*
* Setup includeExclude parameter
* FORMAT:
* Array(
* 'include'=> Array('zipfilepath1', 'zipfilepath2', ...),
* 'exclude'=> Array('zipfilepath3', ...)
* )
*
* DEFAULT: If include is specified only files under the specified path will be included.
* If exclude is specified folders or files will be excluded.
*/
if($includeExclude === false) $includeExclude = Array();
$lista = $this->getList();
if(sizeof($lista)) foreach($lista as $fileName=>$trash){
// Should the file be ignored?
if($includeExclude['include'] &&
!$this->__checkPathInArray($fileName, $includeExclude['include'])) {
// Do not include something not specified in include
continue;
}
if($includeExclude['exclude'] &&
$this->__checkPathInArray($fileName, $includeExclude['exclude'])) {
// Do not include something not specified in include
continue;
}
// END
$dirname = dirname($fileName);
// Rename the path with the matching one (as specified)
if(!empty($renamePaths)) {
foreach($renamePaths as $lookup => $replace) {
if(strpos($dirname, $lookup) === 0) {
$dirname = substr_replace($dirname, $replace, 0, strlen($lookup));
break;
}
}
}
// END
$outDN = "$targetDir/$dirname";
if(substr($dirname, 0, strlen($baseDir)) != $baseDir)
continue;
if(!is_dir($outDN) && $maintainStructure){
$str = "";
$folders = explode("/", $dirname);
foreach($folders as $folder){
$str = $str?"$str/$folder":$folder;
if(!is_dir("$targetDir/$str")){
$this->debugMsg(1, "Creating folder: $targetDir/$str");
mkdir("$targetDir/$str");
if($applyChmod)
@chmod("$targetDir/$str", $applyChmod);
}
}
}
if(substr($fileName, -1, 1) == "/")
continue;
$this->unzip($fileName, "$targetDir/$dirname/".basename($fileName), $applyChmod);
}
}
}
?>

264
vtlib/Vtiger/Utils.php Normal file
View File

@ -0,0 +1,264 @@
<?php
/*+***********************************************************************************
* The contents of this file are subject to the vtiger CRM Public License Version 1.0
* ("License"); You may not use this file except in compliance with the License
* The Original Code is: vtiger CRM Open Source
* The Initial Developer of the Original Code is vtiger.
* Portions created by vtiger are Copyright (C) vtiger.
* All Rights Reserved.
************************************************************************************/
include_once('config.inc.php');
include_once('include/utils/utils.php');
/**
* Provides few utility functions
* @package vtlib
*/
class Vtiger_Utils {
/**
* Check if given value is a number or not
* @param mixed String or Integer
*/
static function isNumber($value) {
return is_numeric($value)? intval($value) == $value : false;
}
/**
* Implode the prefix and suffix as string for given number of times
* @param String prefix to use
* @param Integer Number of times
* @param String suffix to use (optional)
*/
static function implodestr($prefix, $count, $suffix=false) {
$strvalue = '';
for($index = 0; $index < $count; ++$index) {
$strvalue .= $prefix;
if($suffix && $index != ($count-1)) {
$strvalue .= $suffix;
}
}
return $strvalue;
}
/**
* Function to check the file access is made within web root directory as well as is safe for php inclusion
* @param String File path to check
* @param Boolean False to avoid die() if check fails
*/
static function checkFileAccessForInclusion($filepath, $dieOnFail=true) {
global $root_directory;
// Set the base directory to compare with
$use_root_directory = $root_directory;
if(empty($use_root_directory)) {
$use_root_directory = realpath(dirname(__FILE__).'/../../.');
}
$unsafeDirectories = array('storage', 'cache', 'test');
$realfilepath = realpath($filepath);
/** Replace all \\ with \ first */
$realfilepath = str_replace('\\\\', '\\', $realfilepath);
$rootdirpath = str_replace('\\\\', '\\', $use_root_directory);
/** Replace all \ with / now */
$realfilepath = str_replace('\\', '/', $realfilepath);
$rootdirpath = str_replace('\\', '/', $rootdirpath);
$relativeFilePath = str_replace($rootdirpath, '', $realfilepath);
$filePathParts = explode('/', $relativeFilePath);
if(stripos($realfilepath, $rootdirpath) !== 0 || in_array($filePathParts[0], $unsafeDirectories)) {
if($dieOnFail) {
die("Sorry! Attempt to access restricted file.");
}
return false;
}
return true;
}
/**
* Function to check the file access is made within web root directory.
* @param String File path to check
* @param Boolean False to avoid die() if check fails
*/
static function checkFileAccess($filepath, $dieOnFail=true) {
global $root_directory;
// Set the base directory to compare with
$use_root_directory = $root_directory;
if(empty($use_root_directory)) {
$use_root_directory = realpath(dirname(__FILE__).'/../../.');
}
$realfilepath = realpath($filepath);
/** Replace all \\ with \ first */
$realfilepath = str_replace('\\\\', '\\', $realfilepath);
$rootdirpath = str_replace('\\\\', '\\', $use_root_directory);
/** Replace all \ with / now */
$realfilepath = str_replace('\\', '/', $realfilepath);
$rootdirpath = str_replace('\\', '/', $rootdirpath);
if(stripos($realfilepath, $rootdirpath) !== 0) {
if($dieOnFail) {
die("Sorry! Attempt to access restricted file.");
}
return false;
}
return true;
}
/**
* Log the debug message
* @param String Log message
* @param Boolean true to append end-of-line, false otherwise
*/
static function Log($message, $delimit=true) {
global $Vtiger_Utils_Log, $log;
$log->debug($message);
if(!isset($Vtiger_Utils_Log) || $Vtiger_Utils_Log == false) return;
print_r($message);
if($delimit) {
if(isset($_REQUEST)) echo "<BR>";
else echo "\n";
}
}
/**
* Escape the string to avoid SQL Injection attacks.
* @param String Sql statement string
*/
static function SQLEscape($value) {
if($value == null) return $value;
global $adb;
return $adb->sql_escape_string($value);
}
/**
* Check if table is present in database
* @param String tablename to check
*/
static function CheckTable($tablename) {
global $adb;
$old_dieOnError = $adb->dieOnError;
$adb->dieOnError = false;
$tablename = Vtiger_Utils::SQLEscape($tablename);
$tablecheck = $adb->query("SELECT 1 FROM $tablename LIMIT 1");
$tablePresent = true;
if(empty($tablecheck))
$tablePresent = false;
$adb->dieOnError = $old_dieOnError;
return $tablePresent;
}
/**
* Create table (supressing failure)
* @param String tablename to create
* @param String table creation criteria like '(columnname columntype, ....)'
* @param String Optional suffix to add during table creation
* <br>
* will be appended to CREATE TABLE $tablename SQL
*/
static function CreateTable($tablename, $criteria, $suffixTableMeta=false) {
global $adb;
$org_dieOnError = $adb->dieOnError;
$adb->dieOnError = false;
$sql = "CREATE TABLE " . $tablename . $criteria;
if($suffixTableMeta !== false) {
if($suffixTableMeta === true) {
if($adb->isMySQL()) {
$suffixTableMeta = ' ENGINE=InnoDB DEFAULT CHARSET=utf8';
} else {
// TODO Handle other database types.
}
}
$sql .= $suffixTableMeta;
}
$adb->query($sql);
$adb->dieOnError = $org_dieOnError;
}
/**
* Alter existing table
* @param String tablename to alter
* @param String alter criteria like ' ADD columnname columntype' <br>
* will be appended to ALTER TABLE $tablename SQL
*/
static function AlterTable($tablename, $criteria) {
global $adb;
$adb->query("ALTER TABLE " . $tablename . $criteria);
}
/**
* Add column to existing table
* @param String tablename to alter
* @param String columnname to add
* @param String columntype (criteria like 'VARCHAR(100)')
*/
static function AddColumn($tablename, $columnname, $criteria) {
global $adb;
if(!in_array($columnname, $adb->getColumnNames($tablename))) {
self::AlterTable($tablename, " ADD COLUMN $columnname $criteria");
}
}
/**
* Get SQL query
* @param String SQL query statement
*/
static function ExecuteQuery($sqlquery, $supressdie=false) {
global $adb;
$old_dieOnError = $adb->dieOnError;
if($supressdie) $adb->dieOnError = false;
$adb->query($sqlquery);
$adb->dieOnError = $old_dieOnError;
}
/**
* Get CREATE SQL for given table
* @param String tablename for which CREATE SQL is requried
*/
static function CreateTableSql($tablename) {
global $adb;
$create_table = $adb->query("SHOW CREATE TABLE $tablename");
$sql = decode_html($adb->query_result($create_table, 0, 1));
return $sql;
}
/**
* Check if the given SQL is a CREATE statement
* @param String SQL String
*/
static function IsCreateSql($sql) {
if(preg_match('/(CREATE TABLE)/', strtoupper($sql))) {
return true;
}
return false;
}
/**
* Check if the given SQL is destructive (DELETE's DATA)
* @param String SQL String
*/
static function IsDestructiveSql($sql) {
if(preg_match('/(DROP TABLE)|(DROP COLUMN)|(DELETE FROM)/',
strtoupper($sql))) {
return true;
}
return false;
}
}
?>

View File

@ -0,0 +1,115 @@
<?php
/*+***********************************************************************************
* The contents of this file are subject to the vtiger CRM Public License Version 1.0
* ("License"); You may not use this file except in compliance with the License
* The Original Code is: vtiger CRM Open Source
* The Initial Developer of the Original Code is vtiger.
* Portions created by vtiger are Copyright (C) vtiger.
* All Rights Reserved.
*************************************************************************************/
/**
* Template class will enable you to replace a merge fields defined in the String
* with values set dynamically.
*
* @author Prasad
* @package vtlib
*/
class Vtiger_StringTemplate {
// Template variables set dynamically
var $tplvars = Array();
/**
* Identify variable with the following pattern
* $VARIABLE_KEY$
*/
var $_lookfor = '/\$([^\$]+)\$/';
/**
* Constructor
*/
function __construct() {
}
/**
* Assign replacement value for the variable.
*/
function assign($key, $value) {
$this->tplvars[$key] = $value;
}
/**
* Get replacement value for the variable.
*/
function get($key) {
$value = false;
if(isset($this->tplvars[$key])) {
$value = $this->tplvars[$key];
}
return $value;
}
/**
* Clear all the assigned variable values.
* (except the once in the given list)
*/
function clear($exceptvars=false) {
$restorevars = Array();
if($exceptvars) {
foreach($exceptvars as $varkey) {
$restorevars[$varkey] = $this->get($varkey);
}
}
unset($this->tplvars);
$this->tplvars = Array();
foreach($restorevars as $key=>$val) $this->assign($key, $val);
}
/**
* Merge the given file with variable values assigned.
* @param $instring input string template
* @param $avoidLookup should be true if only verbatim file copy needs to be done
* @returns merged contents
*/
function merge($instring, $avoidLookup=false) {
if(empty($instring)) return $instring;
if(!$avoidLookup) {
/** Look for variables */
$matches = Array();
preg_match_all($this->_lookfor, $instring, $matches);
/** Replace variables found with value assigned. */
$matchcount = count($matches[1]);
for($index = 0; $index < $matchcount; ++$index) {
$matchstr = $matches[0][$index];
$matchkey = $matches[1][$index];
$matchstr_regex = $this->__formatAsRegex($matchstr);
$replacewith = $this->get($matchkey);
if($replacewith) {
$instring = preg_replace(
"/$matchstr_regex/", $replacewith, $instring);
}
}
}
return $instring;
}
/**
* Clean up the input to be used as a regex
* @access private
*/
function __formatAsRegex($value) {
// If / is not already escaped as \/ do it now
$value = preg_replace('/\//', '\\/', $value);
// If $ is not already escaped as \$ do it now
$value = preg_replace('/(?<!\\\)\$/', '\\\\$', $value);
return $value;
}
}
?>

63
vtlib/Vtiger/Version.php Normal file
View File

@ -0,0 +1,63 @@
<?php
/*+***********************************************************************************
* The contents of this file are subject to the vtiger CRM Public License Version 1.0
* ("License"); You may not use this file except in compliance with the License
* The Original Code is: vtiger CRM Open Source
* The Initial Developer of the Original Code is vtiger.
* Portions created by vtiger are Copyright (C) vtiger.
* All Rights Reserved.
*************************************************************************************/
include_once('vtigerversion.php');
/**
* Provides utility APIs to work with Vtiger Version detection
* @package vtlib
*/
class Vtiger_Version {
/**
* Get current version of vtiger in use.
*/
static function current() {
global $vtiger_current_version;
return $vtiger_current_version;
}
/**
* Check current version of vtiger with given version
* @param String Version against which comparision to be done
* @param String Condition like ( '=', '!=', '<', '<=', '>', '>=')
*/
static function check($with_version, $condition='=') {
$current_version = self::current();
//xml node is passed to this method sometimes
if(!is_string($with_version)) {
$with_version = (string) $with_version;
}
$with_version = self::getUpperLimitVersion($with_version);
return version_compare($current_version, $with_version, $condition);
}
static function endsWith($string, $endString) {
$strLen = strlen($string);
$endStrLen = strlen($endString);
if ($endStrLen > $strLen) return false;
return substr_compare($string, $endString, -$endStrLen) === 0;
}
static function getUpperLimitVersion($version) {
if(!self::endsWith($version, '.*')) return $version;
$version = rtrim($version, '.*');
$lastVersionPartIndex = strrpos($version, '.');
if ($lastVersionPartIndex === false) {
$version = ((int) $version) + 1;
} else {
$lastVersionPart = substr($version, $lastVersionPartIndex+1, strlen($version));
$upgradedVersionPart = ((int) $lastVersionPart) + 1;
$version = substr($version, 0, $lastVersionPartIndex+1) . $upgradedVersionPart;
}
return $version;
}
}
?>

View File

@ -0,0 +1,56 @@
<?php
/*+**********************************************************************************
* The contents of this file are subject to the vtiger CRM Public License Version 1.0
* ("License"); You may not use this file except in compliance with the License
* The Original Code is: vtiger CRM Open Source
* The Initial Developer of the Original Code is vtiger.
* Portions created by vtiger are Copyright (C) vtiger.
* All Rights Reserved.
************************************************************************************/
include_once('vtlib/Vtiger/Utils.php');
/**
* Provides API to work with vtiger CRM Webservice (available from vtiger 5.1)
* @package vtlib
*/
class Vtiger_Webservice {
/**
* Helper function to log messages
* @param String Message to log
* @param Boolean true appends linebreak, false to avoid it
* @access private
*/
static function log($message, $delim=true) {
Vtiger_Utils::Log($message, $delim);
}
/**
* Initialize webservice for the given module
* @param Vtiger_Module Instance of the module.
*/
static function initialize($moduleInstance) {
if($moduleInstance->isentitytype) {
// TODO: Enable support when webservice API support is added.
if(function_exists('vtws_addDefaultModuleTypeEntity')) {
vtws_addDefaultModuleTypeEntity($moduleInstance->name);
self::log("Initializing webservices support ...DONE");
}
}
}
/**
* Initialize webservice for the given module
* @param Vtiger_Module Instance of the module.
*/
static function uninitialize($moduleInstance) {
if($moduleInstance->isentitytype) {
// TODO: Enable support when webservice API support is added.
if(function_exists('vtws_deleteWebserviceEntity')) {
vtws_deleteWebserviceEntity($moduleInstance->name);
self::log("De-Initializing webservices support ...DONE");
}
}
}
}
?>

111
vtlib/Vtiger/Zip.php Normal file
View File

@ -0,0 +1,111 @@
<?php
/*+**********************************************************************************
* The contents of this file are subject to the vtiger CRM Public License Version 1.0
* ("License"); You may not use this file except in compliance with the License
* The Original Code is: vtiger CRM Open Source
* The Initial Developer of the Original Code is vtiger.
* Portions created by vtiger are Copyright (C) vtiger.
* All Rights Reserved.
************************************************************************************/
require_once('vtlib/thirdparty/dZip.inc.php');
/**
* Wrapper class over dZip.
* @package vtlib
*/
class Vtiger_Zip extends dZip {
/**
* Push out the file content for download.
*/
function forceDownload($zipfileName) {
header("Pragma: public");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: private",false);
header("Content-Type: application/zip");
header("Content-Disposition: attachment; filename=".basename($zipfileName).";" );
//header("Content-Transfer-Encoding: binary");
// For details on this workaround check here the ticket
// http://trac.vtiger.com/cgi-bin/trac.cgi/ticket/5298
$disk_file_size = filesize($zipfileName);
$zipfilesize = $disk_file_size + ($disk_file_size % 1024);
header("Content-Length: ".$zipfilesize);
$fileContent = fread(fopen($zipfileName, "rb"), $zipfilesize);
echo $fileContent;
}
/**
* Get relative path (w.r.t base)
*/
function __getRelativePath($basepath, $srcpath) {
$base_realpath = $this->__normalizePath(realpath($basepath));
$src_realpath = $this->__normalizePath(realpath($srcpath));
$search_index = strpos($src_realpath, $base_realpath);
if($search_index === 0) {
$startindex = strlen($base_realpath)+1;
// On windows $base_realpath ends with / and On Linux it will not have / at end!
if(strrpos($base_realpath, '/') == strlen($base_realpath)-1) $startindex -= 1;
$relpath = substr($src_realpath, $startindex);
}
return $relpath;
}
/**
* Check and add '/' directory separator
*/
function __fixDirSeparator($path) {
if($path != '' && (strripos($path, '/') != strlen($path)-1)) $path .= '/';
return $path;
}
/**
* Normalize the directory path separators.
*/
function __normalizePath($path) {
if($path && strpos($path, '\\')!== false) $path = preg_replace("/\\\\/", "/", $path);
return $path;
}
/**
* Copy the directory on the disk into zip file.
*/
function copyDirectoryFromDisk($dirname, $zipdirname=null, $excludeList=null, $basedirname=null) {
$dir = opendir($dirname);
if(strripos($dirname, '/') != strlen($dirname)-1)
$dirname .= '/';
if($basedirname == null) $basedirname = realpath($dirname);
while(false !== ($file = readdir($dir))) {
if($file != '.' && $file != '..' &&
$file != '.svn' && $file != 'CVS') {
// Exclude the file/directory
if(!empty($excludeList) && in_array("$dirname$file", $excludeList))
continue;
if(is_dir("$dirname$file")) {
$this->copyDirectoryFromDisk("$dirname$file", $zipdirname, $excludeList, $basedirname);
} else {
$zippath = $dirname;
if($zipdirname != null && $zipdirname != '') {
$zipdirname = $this->__fixDirSeparator($zipdirname);
$zippath = $zipdirname.$this->__getRelativePath($basedirname, $dirname);
}
$this->copyFileFromDisk($dirname, $zippath, $file);
}
}
}
closedir($dir);
}
/**
* Copy the disk file into the zip.
*/
function copyFileFromDisk($path, $zippath, $file) {
$path = $this->__fixDirSeparator($path);
$zippath = $this->__fixDirSeparator($zippath);
$this->addFile("$path$file", "$zippath$file");
}
}
?>

517
vtlib/thirdparty/dUnzip2.inc.php vendored Normal file
View File

@ -0,0 +1,517 @@
<?php
/**
* DOWNLOADED FROM: http://www.phpclasses.org/browse/package/2495/
* License: BSD License
*/
?>
<?php
// 15/07/2006 (2.6)
// - Changed the algorithm to parse the ZIP file.. Now, the script will try to mount the compressed
// list, searching on the 'Central Dir' records. If it fails, the script will try to search by
// checking every signature. Thanks to Jayson Cruz for pointing it.
// 25/01/2006 (2.51)
// - Fixed bug when calling 'unzip' without calling 'getList' first. Thanks to Bala Murthu for pointing it.
// 01/12/2006 (2.5)
// - Added optional parameter "applyChmod" for the "unzip()" method. It auto applies the given chmod for
// extracted files.
// - Permission 777 (all read-write-exec) is default. If you want to change it, you'll need to make it
// explicit. (If you want the OS to determine, set "false" as "applyChmod" parameter)
// 28/11/2005 (2.4)
// - dUnzip2 is now compliant with old-style "Data Description", made by some compressors,
// like the classes ZipLib and ZipLib2 by 'Hasin Hayder'. Thanks to Ricardo Parreno for pointing it.
// 09/11/2005 (2.3)
// - Added optional parameter '$stopOnFile' on method 'getList()'.
// If given, file listing will stop when find given filename. (Useful to open and unzip an exact file)
// 06/11/2005 (2.21)
// - Added support to PK00 file format (Packed to Removable Disk) (thanks to Lito [PHPfileNavigator])
// - Method 'getExtraInfo': If requested file doesn't exist, return FALSE instead of Array()
// 31/10/2005 (2.2)
// - Removed redundant 'file_name' on centralDirs declaration (thanks to Lito [PHPfileNavigator])
// - Fixed redeclaration of file_put_contents when in PHP4 (not returning true)
##############################################################
# Class dUnzip2 v2.6
#
# Author: Alexandre Tedeschi (d)
# E-Mail: alexandrebr at gmail dot com
# Londrina - PR / Brazil
#
# Objective:
# This class allows programmer to easily unzip files on the fly.
#
# Requirements:
# This class requires extension ZLib Enabled. It is default
# for most site hosts around the world, and for the PHP Win32 dist.
#
# To do:
# * Error handling
# * Write a PHP-Side gzinflate, to completely avoid any external extensions
# * Write other decompress algorithms
#
# If you modify this class, or have any ideas to improve it, please contact me!
# You are allowed to redistribute this class, if you keep my name and contact e-mail on it.
#
# PLEASE! IF YOU USE THIS CLASS IN ANY OF YOUR PROJECTS, PLEASE LET ME KNOW!
# If you have problems using it, don't think twice before contacting me!
#
##############################################################
if(!function_exists('file_put_contents')){
// If not PHP5, creates a compatible function
Function file_put_contents($file, $data){
if($tmp = fopen($file, "w")){
fwrite($tmp, $data);
fclose($tmp);
return true;
}
echo "<b>file_put_contents:</b> Cannot create file $file<br>";
return false;
}
}
class dUnzip2{
Function getVersion(){
return "2.6";
}
// Public
var $fileName;
var $compressedList; // You will problably use only this one!
var $centralDirList; // Central dir list... It's a kind of 'extra attributes' for a set of files
var $endOfCentral; // End of central dir, contains ZIP Comments
var $debug;
// Private
var $fh;
var $zipSignature = "\x50\x4b\x03\x04"; // local file header signature
var $dirSignature = "\x50\x4b\x01\x02"; // central dir header signature
var $dirSignatureE= "\x50\x4b\x05\x06"; // end of central dir signature
// Public
Function dUnzip2($fileName){
$this->fileName = $fileName;
$this->compressedList =
$this->centralDirList =
$this->endOfCentral = Array();
}
Function getList($stopOnFile=false){
if(sizeof($this->compressedList)){
$this->debugMsg(1, "Returning already loaded file list.");
return $this->compressedList;
}
// Open file, and set file handler
$fh = fopen($this->fileName, "r");
$this->fh = &$fh;
if(!$fh){
$this->debugMsg(2, "Failed to load file.");
return false;
}
$this->debugMsg(1, "Loading list from 'End of Central Dir' index list...");
if(!$this->_loadFileListByEOF($fh, $stopOnFile)){
$this->debugMsg(1, "Failed! Trying to load list looking for signatures...");
if(!$this->_loadFileListBySignatures($fh, $stopOnFile)){
$this->debugMsg(1, "Failed! Could not find any valid header.");
$this->debugMsg(2, "ZIP File is corrupted or empty");
return false;
}
}
if($this->debug){
#------- Debug compressedList
$kkk = 0;
echo "<table border='0' style='font: 11px Verdana; border: 1px solid #000'>";
foreach($this->compressedList as $fileName=>$item){
if(!$kkk && $kkk=1){
echo "<tr style='background: #ADA'>";
foreach($item as $fieldName=>$value)
echo "<td>$fieldName</td>";
echo '</tr>';
}
echo "<tr style='background: #CFC'>";
foreach($item as $fieldName=>$value){
if($fieldName == 'lastmod_datetime')
echo "<td title='$fieldName' nowrap='nowrap'>".date("d/m/Y H:i:s", $value)."</td>";
else
echo "<td title='$fieldName' nowrap='nowrap'>$value</td>";
}
echo "</tr>";
}
echo "</table>";
#------- Debug centralDirList
$kkk = 0;
if(sizeof($this->centralDirList)){
echo "<table border='0' style='font: 11px Verdana; border: 1px solid #000'>";
foreach($this->centralDirList as $fileName=>$item){
if(!$kkk && $kkk=1){
echo "<tr style='background: #AAD'>";
foreach($item as $fieldName=>$value)
echo "<td>$fieldName</td>";
echo '</tr>';
}
echo "<tr style='background: #CCF'>";
foreach($item as $fieldName=>$value){
if($fieldName == 'lastmod_datetime')
echo "<td title='$fieldName' nowrap='nowrap'>".date("d/m/Y H:i:s", $value)."</td>";
else
echo "<td title='$fieldName' nowrap='nowrap'>$value</td>";
}
echo "</tr>";
}
echo "</table>";
}
#------- Debug endOfCentral
$kkk = 0;
if(sizeof($this->endOfCentral)){
echo "<table border='0' style='font: 11px Verdana' style='border: 1px solid #000'>";
echo "<tr style='background: #DAA'><td colspan='2'>dUnzip - End of file</td></tr>";
foreach($this->endOfCentral as $field=>$value){
echo "<tr>";
echo "<td style='background: #FCC'>$field</td>";
echo "<td style='background: #FDD'>$value</td>";
echo "</tr>";
}
echo "</table>";
}
}
return $this->compressedList;
}
Function getExtraInfo($compressedFileName){
return
isset($this->centralDirList[$compressedFileName])?
$this->centralDirList[$compressedFileName]:
false;
}
Function getZipInfo($detail=false){
return $detail?
$this->endOfCentral[$detail]:
$this->endOfCentral;
}
Function unzip($compressedFileName, $targetFileName=false, $applyChmod=0777){
if(!sizeof($this->compressedList)){
$this->debugMsg(1, "Trying to unzip before loading file list... Loading it!");
$this->getList(false, $compressedFileName);
}
$fdetails = &$this->compressedList[$compressedFileName];
if(!isset($this->compressedList[$compressedFileName])){
$this->debugMsg(2, "File '<b>$compressedFileName</b>' is not compressed in the zip.");
return false;
}
if(substr($compressedFileName, -1) == "/"){
$this->debugMsg(2, "Trying to unzip a folder name '<b>$compressedFileName</b>'.");
return false;
}
if(!$fdetails['uncompressed_size']){
$this->debugMsg(1, "File '<b>$compressedFileName</b>' is empty.");
return $targetFileName?
file_put_contents($targetFileName, ""):
"";
}
fseek($this->fh, $fdetails['contents-startOffset']);
$ret = $this->uncompress(
fread($this->fh, $fdetails['compressed_size']),
$fdetails['compression_method'],
$fdetails['uncompressed_size'],
$targetFileName
);
if($applyChmod && $targetFileName)
@chmod($targetFileName, 0777);
return $ret;
}
Function unzipAll($targetDir=false, $baseDir="", $maintainStructure=true, $applyChmod=0777){
if($targetDir === false)
$targetDir = dirname(__FILE__)."/";
$lista = $this->getList();
if(sizeof($lista)) foreach($lista as $fileName=>$trash){
$dirname = dirname($fileName);
$outDN = "$targetDir/$dirname";
if(substr($dirname, 0, strlen($baseDir)) != $baseDir)
continue;
if(!is_dir($outDN) && $maintainStructure){
$str = "";
$folders = explode("/", $dirname);
foreach($folders as $folder){
$str = $str?"$str/$folder":$folder;
if(!is_dir("$targetDir/$str")){
$this->debugMsg(1, "Creating folder: $targetDir/$str");
mkdir("$targetDir/$str");
if($applyChmod)
chmod("$targetDir/$str", $applyChmod);
}
}
}
if(substr($fileName, -1, 1) == "/")
continue;
$maintainStructure?
$this->unzip($fileName, "$targetDir/$fileName", $applyChmod):
$this->unzip($fileName, "$targetDir/".basename($fileName), $applyChmod);
}
}
Function close(){ // Free the file resource
if($this->fh)
fclose($this->fh);
}
Function __destroy(){
$this->close();
}
// Private (you should NOT call these methods):
Function uncompress($content, $mode, $uncompressedSize, $targetFileName=false){
switch($mode){
case 0:
// Not compressed
return $targetFileName?
file_put_contents($targetFileName, $content):
$content;
case 1:
$this->debugMsg(2, "Shrunk mode is not supported... yet?");
return false;
case 2:
case 3:
case 4:
case 5:
$this->debugMsg(2, "Compression factor ".($mode-1)." is not supported... yet?");
return false;
case 6:
$this->debugMsg(2, "Implode is not supported... yet?");
return false;
case 7:
$this->debugMsg(2, "Tokenizing compression algorithm is not supported... yet?");
return false;
case 8:
// Deflate
return $targetFileName?
file_put_contents($targetFileName, gzinflate($content, $uncompressedSize)):
gzinflate($content, $uncompressedSize);
case 9:
$this->debugMsg(2, "Enhanced Deflating is not supported... yet?");
return false;
case 10:
$this->debugMsg(2, "PKWARE Date Compression Library Impoloding is not supported... yet?");
return false;
case 12:
// Bzip2
return $targetFileName?
file_put_contents($targetFileName, bzdecompress($content)):
bzdecompress($content);
case 18:
$this->debugMsg(2, "IBM TERSE is not supported... yet?");
return false;
default:
$this->debugMsg(2, "Unknown uncompress method: $mode");
return false;
}
}
Function debugMsg($level, $string){
if($this->debug)
if($level == 1)
echo "<b style='color: #777'>dUnzip2:</b> $string<br>";
if($level == 2)
echo "<b style='color: #F00'>dUnzip2:</b> $string<br>";
}
Function _loadFileListByEOF(&$fh, $stopOnFile=false){
// Check if there's a valid Central Dir signature.
// Let's consider a file comment smaller than 1024 characters...
// Actually, it length can be 65536.. But we're not going to support it.
for($x = 0; $x < 1024; $x++){
fseek($fh, -22-$x, SEEK_END);
$signature = fread($fh, 4);
if($signature == $this->dirSignatureE){
// If found EOF Central Dir
$eodir['disk_number_this'] = unpack("v", fread($fh, 2)); // number of this disk
$eodir['disk_number'] = unpack("v", fread($fh, 2)); // number of the disk with the start of the central directory
$eodir['total_entries_this'] = unpack("v", fread($fh, 2)); // total number of entries in the central dir on this disk
$eodir['total_entries'] = unpack("v", fread($fh, 2)); // total number of entries in
$eodir['size_of_cd'] = unpack("V", fread($fh, 4)); // size of the central directory
$eodir['offset_start_cd'] = unpack("V", fread($fh, 4)); // offset of start of central directory with respect to the starting disk number
$zipFileCommentLenght = unpack("v", fread($fh, 2)); // zipfile comment length
$eodir['zipfile_comment'] = $zipFileCommentLenght[1]?fread($fh, $zipFileCommentLenght[1]):''; // zipfile comment
$this->endOfCentral = Array(
'disk_number_this'=>$eodir['disk_number_this'][1],
'disk_number'=>$eodir['disk_number'][1],
'total_entries_this'=>$eodir['total_entries_this'][1],
'total_entries'=>$eodir['total_entries'][1],
'size_of_cd'=>$eodir['size_of_cd'][1],
'offset_start_cd'=>$eodir['offset_start_cd'][1],
'zipfile_comment'=>$eodir['zipfile_comment'],
);
// Then, load file list
fseek($fh, $this->endOfCentral['offset_start_cd']);
$signature = fread($fh, 4);
while($signature == $this->dirSignature){
$dir['version_madeby'] = unpack("v", fread($fh, 2)); // version made by
$dir['version_needed'] = unpack("v", fread($fh, 2)); // version needed to extract
$dir['general_bit_flag'] = unpack("v", fread($fh, 2)); // general purpose bit flag
$dir['compression_method'] = unpack("v", fread($fh, 2)); // compression method
$dir['lastmod_time'] = unpack("v", fread($fh, 2)); // last mod file time
$dir['lastmod_date'] = unpack("v", fread($fh, 2)); // last mod file date
$dir['crc-32'] = fread($fh, 4); // crc-32
$dir['compressed_size'] = unpack("V", fread($fh, 4)); // compressed size
$dir['uncompressed_size'] = unpack("V", fread($fh, 4)); // uncompressed size
$fileNameLength = unpack("v", fread($fh, 2)); // filename length
$extraFieldLength = unpack("v", fread($fh, 2)); // extra field length
$fileCommentLength = unpack("v", fread($fh, 2)); // file comment length
$dir['disk_number_start'] = unpack("v", fread($fh, 2)); // disk number start
$dir['internal_attributes'] = unpack("v", fread($fh, 2)); // internal file attributes-byte1
$dir['external_attributes1']= unpack("v", fread($fh, 2)); // external file attributes-byte2
$dir['external_attributes2']= unpack("v", fread($fh, 2)); // external file attributes
$dir['relative_offset'] = unpack("V", fread($fh, 4)); // relative offset of local header
$dir['file_name'] = fread($fh, $fileNameLength[1]); // filename
$dir['extra_field'] = $extraFieldLength[1] ?fread($fh, $extraFieldLength[1]) :''; // extra field
$dir['file_comment'] = $fileCommentLength[1]?fread($fh, $fileCommentLength[1]):''; // file comment
// Convert the date and time, from MS-DOS format to UNIX Timestamp
$BINlastmod_date = str_pad(decbin($dir['lastmod_date'][1]), 16, '0', STR_PAD_LEFT);
$BINlastmod_time = str_pad(decbin($dir['lastmod_time'][1]), 16, '0', STR_PAD_LEFT);
$lastmod_dateY = bindec(substr($BINlastmod_date, 0, 7))+1980;
$lastmod_dateM = bindec(substr($BINlastmod_date, 7, 4));
$lastmod_dateD = bindec(substr($BINlastmod_date, 11, 5));
$lastmod_timeH = bindec(substr($BINlastmod_time, 0, 5));
$lastmod_timeM = bindec(substr($BINlastmod_time, 5, 6));
$lastmod_timeS = bindec(substr($BINlastmod_time, 11, 5));
$this->centralDirList[$dir['file_name']] = Array(
'version_madeby'=>$dir['version_madeby'][1],
'version_needed'=>$dir['version_needed'][1],
'general_bit_flag'=>str_pad(decbin($dir['general_bit_flag'][1]), 8, '0', STR_PAD_LEFT),
'compression_method'=>$dir['compression_method'][1],
'lastmod_datetime' =>mktime($lastmod_timeH, $lastmod_timeM, $lastmod_timeS, $lastmod_dateM, $lastmod_dateD, $lastmod_dateY),
'crc-32' =>str_pad(dechex(ord($dir['crc-32'][3])), 2, '0', STR_PAD_LEFT).
str_pad(dechex(ord($dir['crc-32'][2])), 2, '0', STR_PAD_LEFT).
str_pad(dechex(ord($dir['crc-32'][1])), 2, '0', STR_PAD_LEFT).
str_pad(dechex(ord($dir['crc-32'][0])), 2, '0', STR_PAD_LEFT),
'compressed_size'=>$dir['compressed_size'][1],
'uncompressed_size'=>$dir['uncompressed_size'][1],
'disk_number_start'=>$dir['disk_number_start'][1],
'internal_attributes'=>$dir['internal_attributes'][1],
'external_attributes1'=>$dir['external_attributes1'][1],
'external_attributes2'=>$dir['external_attributes2'][1],
'relative_offset'=>$dir['relative_offset'][1],
'file_name'=>$dir['file_name'],
'extra_field'=>$dir['extra_field'],
'file_comment'=>$dir['file_comment'],
);
$signature = fread($fh, 4);
}
// If loaded centralDirs, then try to identify the offsetPosition of the compressed data.
if($this->centralDirList) foreach($this->centralDirList as $filename=>$details){
$i = $this->_getFileHeaderInformation($fh, $details['relative_offset']);
$this->compressedList[$filename]['file_name'] = $filename;
$this->compressedList[$filename]['compression_method'] = $details['compression_method'];
$this->compressedList[$filename]['version_needed'] = $details['version_needed'];
$this->compressedList[$filename]['lastmod_datetime'] = $details['lastmod_datetime'];
$this->compressedList[$filename]['crc-32'] = $details['crc-32'];
$this->compressedList[$filename]['compressed_size'] = $details['compressed_size'];
$this->compressedList[$filename]['uncompressed_size'] = $details['uncompressed_size'];
$this->compressedList[$filename]['lastmod_datetime'] = $details['lastmod_datetime'];
$this->compressedList[$filename]['extra_field'] = $i['extra_field'];
$this->compressedList[$filename]['contents-startOffset']=$i['contents-startOffset'];
if(strtolower($stopOnFile) == strtolower($filename))
break;
}
return true;
}
}
return false;
}
Function _loadFileListBySignatures(&$fh, $stopOnFile=false){
fseek($fh, 0);
$return = false;
for(;;){
$details = $this->_getFileHeaderInformation($fh);
if(!$details){
$this->debugMsg(1, "Invalid signature. Trying to verify if is old style Data Descriptor...");
fseek($fh, 12 - 4, SEEK_CUR); // 12: Data descriptor - 4: Signature (that will be read again)
$details = $this->_getFileHeaderInformation($fh);
}
if(!$details){
$this->debugMsg(1, "Still invalid signature. Probably reached the end of the file.");
break;
}
$filename = $details['file_name'];
$this->compressedList[$filename] = $details;
$return = true;
if(strtolower($stopOnFile) == strtolower($filename))
break;
}
return $return;
}
Function _getFileHeaderInformation(&$fh, $startOffset=false){
if($startOffset !== false)
fseek($fh, $startOffset);
$signature = fread($fh, 4);
if($signature == $this->zipSignature){
# $this->debugMsg(1, "Zip Signature!");
// Get information about the zipped file
$file['version_needed'] = unpack("v", fread($fh, 2)); // version needed to extract
$file['general_bit_flag'] = unpack("v", fread($fh, 2)); // general purpose bit flag
$file['compression_method'] = unpack("v", fread($fh, 2)); // compression method
$file['lastmod_time'] = unpack("v", fread($fh, 2)); // last mod file time
$file['lastmod_date'] = unpack("v", fread($fh, 2)); // last mod file date
$file['crc-32'] = fread($fh, 4); // crc-32
$file['compressed_size'] = unpack("V", fread($fh, 4)); // compressed size
$file['uncompressed_size'] = unpack("V", fread($fh, 4)); // uncompressed size
$fileNameLength = unpack("v", fread($fh, 2)); // filename length
$extraFieldLength = unpack("v", fread($fh, 2)); // extra field length
$file['file_name'] = fread($fh, $fileNameLength[1]); // filename
$file['extra_field'] = $extraFieldLength[1]?fread($fh, $extraFieldLength[1]):''; // extra field
$file['contents-startOffset']= ftell($fh);
// Bypass the whole compressed contents, and look for the next file
fseek($fh, $file['compressed_size'][1], SEEK_CUR);
// Convert the date and time, from MS-DOS format to UNIX Timestamp
$BINlastmod_date = str_pad(decbin($file['lastmod_date'][1]), 16, '0', STR_PAD_LEFT);
$BINlastmod_time = str_pad(decbin($file['lastmod_time'][1]), 16, '0', STR_PAD_LEFT);
$lastmod_dateY = bindec(substr($BINlastmod_date, 0, 7))+1980;
$lastmod_dateM = bindec(substr($BINlastmod_date, 7, 4));
$lastmod_dateD = bindec(substr($BINlastmod_date, 11, 5));
$lastmod_timeH = bindec(substr($BINlastmod_time, 0, 5));
$lastmod_timeM = bindec(substr($BINlastmod_time, 5, 6));
$lastmod_timeS = bindec(substr($BINlastmod_time, 11, 5));
// Mount file table
$i = Array(
'file_name' =>$file['file_name'],
'compression_method'=>$file['compression_method'][1],
'version_needed' =>$file['version_needed'][1],
'lastmod_datetime' =>mktime($lastmod_timeH, $lastmod_timeM, $lastmod_timeS, $lastmod_dateM, $lastmod_dateD, $lastmod_dateY),
'crc-32' =>str_pad(dechex(ord($file['crc-32'][3])), 2, '0', STR_PAD_LEFT).
str_pad(dechex(ord($file['crc-32'][2])), 2, '0', STR_PAD_LEFT).
str_pad(dechex(ord($file['crc-32'][1])), 2, '0', STR_PAD_LEFT).
str_pad(dechex(ord($file['crc-32'][0])), 2, '0', STR_PAD_LEFT),
'compressed_size' =>$file['compressed_size'][1],
'uncompressed_size' =>$file['uncompressed_size'][1],
'extra_field' =>$file['extra_field'],
'general_bit_flag' =>str_pad(decbin($file['general_bit_flag'][1]), 8, '0', STR_PAD_LEFT),
'contents-startOffset'=>$file['contents-startOffset']
);
return $i;
}
return false;
}
}
?>

153
vtlib/thirdparty/dZip.inc.php vendored Normal file
View File

@ -0,0 +1,153 @@
<?php
/**
* DOWNLOADED FROM: http://www.phpclasses.org/browse/package/2495/
* License: BSD License
*/
?>
<?php
class dZip{
var $filename;
var $overwrite;
var $zipSignature = "\x50\x4b\x03\x04"; // local file header signature
var $dirSignature = "\x50\x4b\x01\x02"; // central dir header signature
var $dirSignatureE= "\x50\x4b\x05\x06"; // end of central dir signature
var $files_count = 0;
var $fh;
Function dZip($filename, $overwrite=true){
$this->filename = $filename;
$this->overwrite = $overwrite;
}
Function addDir($dirname, $fileComments=''){
if(substr($dirname, -1) != '/')
$dirname .= '/';
$this->addFile(false, $dirname, $fileComments);
}
Function addFile($filename, $cfilename, $fileComments='', $data=false){
if(!($fh = &$this->fh))
$fh = fopen($this->filename, $this->overwrite?'wb':'a+b');
// $filename can be a local file OR the data wich will be compressed
if(substr($cfilename, -1)=='/'){
$details['uncsize'] = 0;
$data = '';
}
elseif(file_exists($filename)){
$details['uncsize'] = filesize($filename);
$data = file_get_contents($filename);
}
elseif($filename){
echo "<b>Cannot add $filename. File not found</b><br>";
return false;
}
else{
$details['uncsize'] = strlen($data); // Prasad: Fixed instead of strlen($filename)
// DATA is given.. use it! :|
}
// if data to compress is too small, just store it
if($details['uncsize'] < 256){
$details['comsize'] = $details['uncsize'];
$details['vneeded'] = 10;
$details['cmethod'] = 0;
$zdata = &$data;
}
else{ // otherwise, compress it
$zdata = gzcompress($data);
$zdata = substr(substr($zdata, 0, strlen($zdata) - 4), 2); // fix crc bug (thanks to Eric Mueller)
$details['comsize'] = strlen($zdata);
$details['vneeded'] = 10;
$details['cmethod'] = 8;
}
$details['bitflag'] = 0;
$details['crc_32'] = crc32($data);
// Convert date and time to DOS Format, and set then
$lastmod_timeS = str_pad(decbin(date('s')>=32?date('s')-32:date('s')), 5, '0', STR_PAD_LEFT);
$lastmod_timeM = str_pad(decbin(date('i')), 6, '0', STR_PAD_LEFT);
$lastmod_timeH = str_pad(decbin(date('H')), 5, '0', STR_PAD_LEFT);
$lastmod_dateD = str_pad(decbin(date('d')), 5, '0', STR_PAD_LEFT);
$lastmod_dateM = str_pad(decbin(date('m')), 4, '0', STR_PAD_LEFT);
$lastmod_dateY = str_pad(decbin(date('Y')-1980), 7, '0', STR_PAD_LEFT);
# echo "ModTime: $lastmod_timeS-$lastmod_timeM-$lastmod_timeH (".date("s H H").")\n";
# echo "ModDate: $lastmod_dateD-$lastmod_dateM-$lastmod_dateY (".date("d m Y").")\n";
$details['modtime'] = bindec("$lastmod_timeH$lastmod_timeM$lastmod_timeS");
$details['moddate'] = bindec("$lastmod_dateY$lastmod_dateM$lastmod_dateD");
$details['offset'] = ftell($fh);
fwrite($fh, $this->zipSignature);
fwrite($fh, pack('s', $details['vneeded'])); // version_needed
fwrite($fh, pack('s', $details['bitflag'])); // general_bit_flag
fwrite($fh, pack('s', $details['cmethod'])); // compression_method
fwrite($fh, pack('s', $details['modtime'])); // lastmod_time
fwrite($fh, pack('s', $details['moddate'])); // lastmod_date
fwrite($fh, pack('V', $details['crc_32'])); // crc-32
fwrite($fh, pack('I', $details['comsize'])); // compressed_size
fwrite($fh, pack('I', $details['uncsize'])); // uncompressed_size
fwrite($fh, pack('s', strlen($cfilename))); // file_name_length
fwrite($fh, pack('s', 0)); // extra_field_length
fwrite($fh, $cfilename); // file_name
// ignoring extra_field
fwrite($fh, $zdata);
// Append it to central dir
$details['external_attributes'] = (substr($cfilename, -1)=='/'&&!$zdata)?16:32; // Directory or file name
$details['comments'] = $fileComments;
$this->appendCentralDir($cfilename, $details);
$this->files_count++;
}
Function setExtra($filename, $property, $value){
$this->centraldirs[$filename][$property] = $value;
}
Function save($zipComments=''){
if(!($fh = &$this->fh))
$fh = fopen($this->filename, $this->overwrite?'w':'a+');
$cdrec = "";
foreach($this->centraldirs as $filename=>$cd){
$cdrec .= $this->dirSignature;
$cdrec .= "\x0\x0"; // version made by
$cdrec .= pack('v', $cd['vneeded']); // version needed to extract
$cdrec .= "\x0\x0"; // general bit flag
$cdrec .= pack('v', $cd['cmethod']); // compression method
$cdrec .= pack('v', $cd['modtime']); // lastmod time
$cdrec .= pack('v', $cd['moddate']); // lastmod date
$cdrec .= pack('V', $cd['crc_32']); // crc32
$cdrec .= pack('V', $cd['comsize']); // compressed filesize
$cdrec .= pack('V', $cd['uncsize']); // uncompressed filesize
$cdrec .= pack('v', strlen($filename)); // file comment length
$cdrec .= pack('v', 0); // extra field length
$cdrec .= pack('v', strlen($cd['comments'])); // file comment length
$cdrec .= pack('v', 0); // disk number start
$cdrec .= pack('v', 0); // internal file attributes
$cdrec .= pack('V', $cd['external_attributes']); // internal file attributes
$cdrec .= pack('V', $cd['offset']); // relative offset of local header
$cdrec .= $filename;
$cdrec .= $cd['comments'];
}
$before_cd = ftell($fh);
fwrite($fh, $cdrec);
// end of central dir
fwrite($fh, $this->dirSignatureE);
fwrite($fh, pack('v', 0)); // number of this disk
fwrite($fh, pack('v', 0)); // number of the disk with the start of the central directory
fwrite($fh, pack('v', $this->files_count)); // total # of entries "on this disk"
fwrite($fh, pack('v', $this->files_count)); // total # of entries overall
fwrite($fh, pack('V', strlen($cdrec))); // size of central dir
fwrite($fh, pack('V', $before_cd)); // offset to start of central dir
fwrite($fh, pack('v', strlen($zipComments))); // .zip file comment length
fwrite($fh, $zipComments);
fclose($fh);
}
// Private
Function appendCentralDir($filename,$properties){
$this->centraldirs[$filename] = $properties;
}
}
?>

592
vtlib/thirdparty/network/Net/Socket.php vendored Normal file
View File

@ -0,0 +1,592 @@
<?php
//
// +----------------------------------------------------------------------+
// | PHP Version 4 |
// +----------------------------------------------------------------------+
// | Copyright (c) 1997-2003 The PHP Group |
// +----------------------------------------------------------------------+
// | This source file is subject to version 2.0 of the PHP license, |
// | that is bundled with this package in the file LICENSE, and is |
// | available at through the world-wide-web at |
// | http://www.php.net/license/2_02.txt. |
// | If you did not receive a copy of the PHP license and are unable to |
// | obtain it through the world-wide-web, please send a note to |
// | license@php.net so we can mail you a copy immediately. |
// +----------------------------------------------------------------------+
// | Authors: Stig Bakken <ssb@php.net> |
// | Chuck Hagenbuch <chuck@horde.org> |
// +----------------------------------------------------------------------+
//
// $Id: Socket.php,v 1.38 2008/02/15 18:24:17 chagenbu Exp $
require_once dirname(__FILE__) . '/../PEAR.php';
define('NET_SOCKET_READ', 1);
define('NET_SOCKET_WRITE', 2);
define('NET_SOCKET_ERROR', 4);
/**
* Generalized Socket class.
*
* @version 1.1
* @author Stig Bakken <ssb@php.net>
* @author Chuck Hagenbuch <chuck@horde.org>
*/
class Net_Socket extends PEAR {
/**
* Socket file pointer.
* @var resource $fp
*/
var $fp = null;
/**
* Whether the socket is blocking. Defaults to true.
* @var boolean $blocking
*/
var $blocking = true;
/**
* Whether the socket is persistent. Defaults to false.
* @var boolean $persistent
*/
var $persistent = false;
/**
* The IP address to connect to.
* @var string $addr
*/
var $addr = '';
/**
* The port number to connect to.
* @var integer $port
*/
var $port = 0;
/**
* Number of seconds to wait on socket connections before assuming
* there's no more data. Defaults to no timeout.
* @var integer $timeout
*/
var $timeout = false;
/**
* Number of bytes to read at a time in readLine() and
* readAll(). Defaults to 2048.
* @var integer $lineLength
*/
var $lineLength = 2048;
/**
* Connect to the specified port. If called when the socket is
* already connected, it disconnects and connects again.
*
* @param string $addr IP address or host name.
* @param integer $port TCP port number.
* @param boolean $persistent (optional) Whether the connection is
* persistent (kept open between requests
* by the web server).
* @param integer $timeout (optional) How long to wait for data.
* @param array $options See options for stream_context_create.
*
* @access public
*
* @return boolean | PEAR_Error True on success or a PEAR_Error on failure.
*/
function connect($addr, $port = 0, $persistent = null, $timeout = null, $options = null)
{
if (is_resource($this->fp)) {
@fclose($this->fp);
$this->fp = null;
}
if (!$addr) {
return $this->raiseError('$addr cannot be empty');
} elseif (strspn($addr, '.0123456789') == strlen($addr) ||
strstr($addr, '/') !== false) {
$this->addr = $addr;
} else {
$this->addr = @gethostbyname($addr);
}
$this->port = $port % 65536;
if ($persistent !== null) {
$this->persistent = $persistent;
}
if ($timeout !== null) {
$this->timeout = $timeout;
}
$openfunc = $this->persistent ? 'pfsockopen' : 'fsockopen';
$errno = 0;
$errstr = '';
$old_track_errors = @ini_set('track_errors', 1);
if ($options && function_exists('stream_context_create')) {
if ($this->timeout) {
$timeout = $this->timeout;
} else {
$timeout = 0;
}
$context = stream_context_create($options);
// Since PHP 5 fsockopen doesn't allow context specification
if (function_exists('stream_socket_client')) {
$flags = $this->persistent ? STREAM_CLIENT_PERSISTENT : STREAM_CLIENT_CONNECT;
$addr = $this->addr . ':' . $this->port;
$fp = stream_socket_client($addr, $errno, $errstr, $timeout, $flags, $context);
} else {
$fp = @$openfunc($this->addr, $this->port, $errno, $errstr, $timeout, $context);
}
} else {
if ($this->timeout) {
$fp = @$openfunc($this->addr, $this->port, $errno, $errstr, $this->timeout);
} else {
$fp = @$openfunc($this->addr, $this->port, $errno, $errstr);
}
}
if (!$fp) {
if ($errno == 0 && isset($php_errormsg)) {
$errstr = $php_errormsg;
}
@ini_set('track_errors', $old_track_errors);
return $this->raiseError($errstr, $errno);
}
@ini_set('track_errors', $old_track_errors);
$this->fp = $fp;
return $this->setBlocking($this->blocking);
}
/**
* Disconnects from the peer, closes the socket.
*
* @access public
* @return mixed true on success or a PEAR_Error instance otherwise
*/
function disconnect()
{
if (!is_resource($this->fp)) {
return $this->raiseError('not connected');
}
@fclose($this->fp);
$this->fp = null;
return true;
}
/**
* Find out if the socket is in blocking mode.
*
* @access public
* @return boolean The current blocking mode.
*/
function isBlocking()
{
return $this->blocking;
}
/**
* Sets whether the socket connection should be blocking or
* not. A read call to a non-blocking socket will return immediately
* if there is no data available, whereas it will block until there
* is data for blocking sockets.
*
* @param boolean $mode True for blocking sockets, false for nonblocking.
* @access public
* @return mixed true on success or a PEAR_Error instance otherwise
*/
function setBlocking($mode)
{
if (!is_resource($this->fp)) {
return $this->raiseError('not connected');
}
$this->blocking = $mode;
socket_set_blocking($this->fp, $this->blocking);
return true;
}
/**
* Sets the timeout value on socket descriptor,
* expressed in the sum of seconds and microseconds
*
* @param integer $seconds Seconds.
* @param integer $microseconds Microseconds.
* @access public
* @return mixed true on success or a PEAR_Error instance otherwise
*/
function setTimeout($seconds, $microseconds)
{
if (!is_resource($this->fp)) {
return $this->raiseError('not connected');
}
return socket_set_timeout($this->fp, $seconds, $microseconds);
}
/**
* Sets the file buffering size on the stream.
* See php's stream_set_write_buffer for more information.
*
* @param integer $size Write buffer size.
* @access public
* @return mixed on success or an PEAR_Error object otherwise
*/
function setWriteBuffer($size)
{
if (!is_resource($this->fp)) {
return $this->raiseError('not connected');
}
$returned = stream_set_write_buffer($this->fp, $size);
if ($returned == 0) {
return true;
}
return $this->raiseError('Cannot set write buffer.');
}
/**
* Returns information about an existing socket resource.
* Currently returns four entries in the result array:
*
* <p>
* timed_out (bool) - The socket timed out waiting for data<br>
* blocked (bool) - The socket was blocked<br>
* eof (bool) - Indicates EOF event<br>
* unread_bytes (int) - Number of bytes left in the socket buffer<br>
* </p>
*
* @access public
* @return mixed Array containing information about existing socket resource or a PEAR_Error instance otherwise
*/
function getStatus()
{
if (!is_resource($this->fp)) {
return $this->raiseError('not connected');
}
return socket_get_status($this->fp);
}
/**
* Get a specified line of data
*
* @access public
* @return $size bytes of data from the socket, or a PEAR_Error if
* not connected.
*/
function gets($size)
{
if (!is_resource($this->fp)) {
return $this->raiseError('not connected');
}
return @fgets($this->fp, $size);
}
/**
* Read a specified amount of data. This is guaranteed to return,
* and has the added benefit of getting everything in one fread()
* chunk; if you know the size of the data you're getting
* beforehand, this is definitely the way to go.
*
* @param integer $size The number of bytes to read from the socket.
* @access public
* @return $size bytes of data from the socket, or a PEAR_Error if
* not connected.
*/
function read($size)
{
if (!is_resource($this->fp)) {
return $this->raiseError('not connected');
}
return @fread($this->fp, $size);
}
/**
* Write a specified amount of data.
*
* @param string $data Data to write.
* @param integer $blocksize Amount of data to write at once.
* NULL means all at once.
*
* @access public
* @return mixed If the socket is not connected, returns an instance of PEAR_Error
* If the write succeeds, returns the number of bytes written
* If the write fails, returns false.
*/
function write($data, $blocksize = null)
{
if (!is_resource($this->fp)) {
return $this->raiseError('not connected');
}
if (is_null($blocksize) && !OS_WINDOWS) {
return @fwrite($this->fp, $data);
} else {
if (is_null($blocksize)) {
$blocksize = 1024;
}
$pos = 0;
$size = strlen($data);
while ($pos < $size) {
$written = @fwrite($this->fp, substr($data, $pos, $blocksize));
if ($written === false) {
return false;
}
$pos += $written;
}
return $pos;
}
}
/**
* Write a line of data to the socket, followed by a trailing "\r\n".
*
* @access public
* @return mixed fputs result, or an error
*/
function writeLine($data)
{
if (!is_resource($this->fp)) {
return $this->raiseError('not connected');
}
return fwrite($this->fp, $data . "\r\n");
}
/**
* Tests for end-of-file on a socket descriptor.
*
* Also returns true if the socket is disconnected.
*
* @access public
* @return bool
*/
function eof()
{
return (!is_resource($this->fp) || feof($this->fp));
}
/**
* Reads a byte of data
*
* @access public
* @return 1 byte of data from the socket, or a PEAR_Error if
* not connected.
*/
function readByte()
{
if (!is_resource($this->fp)) {
return $this->raiseError('not connected');
}
return ord(@fread($this->fp, 1));
}
/**
* Reads a word of data
*
* @access public
* @return 1 word of data from the socket, or a PEAR_Error if
* not connected.
*/
function readWord()
{
if (!is_resource($this->fp)) {
return $this->raiseError('not connected');
}
$buf = @fread($this->fp, 2);
return (ord($buf[0]) + (ord($buf[1]) << 8));
}
/**
* Reads an int of data
*
* @access public
* @return integer 1 int of data from the socket, or a PEAR_Error if
* not connected.
*/
function readInt()
{
if (!is_resource($this->fp)) {
return $this->raiseError('not connected');
}
$buf = @fread($this->fp, 4);
return (ord($buf[0]) + (ord($buf[1]) << 8) +
(ord($buf[2]) << 16) + (ord($buf[3]) << 24));
}
/**
* Reads a zero-terminated string of data
*
* @access public
* @return string, or a PEAR_Error if
* not connected.
*/
function readString()
{
if (!is_resource($this->fp)) {
return $this->raiseError('not connected');
}
$string = '';
while (($char = @fread($this->fp, 1)) != "\x00") {
$string .= $char;
}
return $string;
}
/**
* Reads an IP Address and returns it in a dot formatted string
*
* @access public
* @return Dot formatted string, or a PEAR_Error if
* not connected.
*/
function readIPAddress()
{
if (!is_resource($this->fp)) {
return $this->raiseError('not connected');
}
$buf = @fread($this->fp, 4);
return sprintf('%d.%d.%d.%d', ord($buf[0]), ord($buf[1]),
ord($buf[2]), ord($buf[3]));
}
/**
* Read until either the end of the socket or a newline, whichever
* comes first. Strips the trailing newline from the returned data.
*
* @access public
* @return All available data up to a newline, without that
* newline, or until the end of the socket, or a PEAR_Error if
* not connected.
*/
function readLine()
{
if (!is_resource($this->fp)) {
return $this->raiseError('not connected');
}
$line = '';
$timeout = time() + $this->timeout;
while (!feof($this->fp) && (!$this->timeout || time() < $timeout)) {
$line .= @fgets($this->fp, $this->lineLength);
if (substr($line, -1) == "\n") {
return rtrim($line, "\r\n");
}
}
return $line;
}
/**
* Read until the socket closes, or until there is no more data in
* the inner PHP buffer. If the inner buffer is empty, in blocking
* mode we wait for at least 1 byte of data. Therefore, in
* blocking mode, if there is no data at all to be read, this
* function will never exit (unless the socket is closed on the
* remote end).
*
* @access public
*
* @return string All data until the socket closes, or a PEAR_Error if
* not connected.
*/
function readAll()
{
if (!is_resource($this->fp)) {
return $this->raiseError('not connected');
}
$data = '';
while (!feof($this->fp)) {
$data .= @fread($this->fp, $this->lineLength);
}
return $data;
}
/**
* Runs the equivalent of the select() system call on the socket
* with a timeout specified by tv_sec and tv_usec.
*
* @param integer $state Which of read/write/error to check for.
* @param integer $tv_sec Number of seconds for timeout.
* @param integer $tv_usec Number of microseconds for timeout.
*
* @access public
* @return False if select fails, integer describing which of read/write/error
* are ready, or PEAR_Error if not connected.
*/
function select($state, $tv_sec, $tv_usec = 0)
{
if (!is_resource($this->fp)) {
return $this->raiseError('not connected');
}
$read = null;
$write = null;
$except = null;
if ($state & NET_SOCKET_READ) {
$read[] = $this->fp;
}
if ($state & NET_SOCKET_WRITE) {
$write[] = $this->fp;
}
if ($state & NET_SOCKET_ERROR) {
$except[] = $this->fp;
}
if (false === ($sr = stream_select($read, $write, $except, $tv_sec, $tv_usec))) {
return false;
}
$result = 0;
if (count($read)) {
$result |= NET_SOCKET_READ;
}
if (count($write)) {
$result |= NET_SOCKET_WRITE;
}
if (count($except)) {
$result |= NET_SOCKET_ERROR;
}
return $result;
}
/**
* Turns encryption on/off on a connected socket.
*
* @param bool $enabled Set this parameter to true to enable encryption
* and false to disable encryption.
* @param integer $type Type of encryption. See
* http://se.php.net/manual/en/function.stream-socket-enable-crypto.php for values.
*
* @access public
* @return false on error, true on success and 0 if there isn't enough data and the
* user should try again (non-blocking sockets only). A PEAR_Error object
* is returned if the socket is not connected
*/
function enableCrypto($enabled, $type)
{
if (version_compare(phpversion(), "5.1.0", ">=")) {
if (!is_resource($this->fp)) {
return $this->raiseError('not connected');
}
return @stream_socket_enable_crypto($this->fp, $enabled, $type);
} else {
return $this->raiseError('Net_Socket::enableCrypto() requires php version >= 5.1.0');
}
}
}

485
vtlib/thirdparty/network/Net/URL.php vendored Normal file
View File

@ -0,0 +1,485 @@
<?php
// +-----------------------------------------------------------------------+
// | Copyright (c) 2002-2004, Richard Heyes |
// | All rights reserved. |
// | |
// | Redistribution and use in source and binary forms, with or without |
// | modification, are permitted provided that the following conditions |
// | are met: |
// | |
// | o Redistributions of source code must retain the above copyright |
// | notice, this list of conditions and the following disclaimer. |
// | o Redistributions in binary form must reproduce the above copyright |
// | notice, this list of conditions and the following disclaimer in the |
// | documentation and/or other materials provided with the distribution.|
// | o The names of the authors may not be used to endorse or promote |
// | products derived from this software without specific prior written |
// | permission. |
// | |
// | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS |
// | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT |
// | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR |
// | A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT |
// | OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, |
// | SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT |
// | LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, |
// | DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY |
// | THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT |
// | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE |
// | OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. |
// | |
// +-----------------------------------------------------------------------+
// | Author: Richard Heyes <richard at php net> |
// +-----------------------------------------------------------------------+
//
// $Id: URL.php,v 1.49 2007/06/28 14:43:07 davidc Exp $
//
// Net_URL Class
class Net_URL
{
var $options = array('encode_query_keys' => false);
/**
* Full url
* @var string
*/
var $url;
/**
* Protocol
* @var string
*/
var $protocol;
/**
* Username
* @var string
*/
var $username;
/**
* Password
* @var string
*/
var $password;
/**
* Host
* @var string
*/
var $host;
/**
* Port
* @var integer
*/
var $port;
/**
* Path
* @var string
*/
var $path;
/**
* Query string
* @var array
*/
var $querystring;
/**
* Anchor
* @var string
*/
var $anchor;
/**
* Whether to use []
* @var bool
*/
var $useBrackets;
/**
* PHP4 Constructor
*
* @see __construct()
*/
function Net_URL($url = null, $useBrackets = true)
{
$this->__construct($url, $useBrackets);
}
/**
* PHP5 Constructor
*
* Parses the given url and stores the various parts
* Defaults are used in certain cases
*
* @param string $url Optional URL
* @param bool $useBrackets Whether to use square brackets when
* multiple querystrings with the same name
* exist
*/
function __construct($url = null, $useBrackets = true)
{
$this->url = $url;
$this->useBrackets = $useBrackets;
$this->initialize();
}
function initialize()
{
$HTTP_SERVER_VARS = !empty($_SERVER) ? $_SERVER : $GLOBALS['HTTP_SERVER_VARS'];
$this->user = '';
$this->pass = '';
$this->host = '';
$this->port = 80;
$this->path = '';
$this->querystring = array();
$this->anchor = '';
// Only use defaults if not an absolute URL given
if (!preg_match('/^[a-z0-9]+:\/\//i', $this->url)) {
$this->protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on' ? 'https' : 'http');
/**
* Figure out host/port
*/
if (!empty($HTTP_SERVER_VARS['HTTP_HOST']) &&
preg_match('/^(.*)(:([0-9]+))?$/U', $HTTP_SERVER_VARS['HTTP_HOST'], $matches))
{
$host = $matches[1];
if (!empty($matches[3])) {
$port = $matches[3];
} else {
$port = $this->getStandardPort($this->protocol);
}
}
$this->user = '';
$this->pass = '';
$this->host = !empty($host) ? $host : (isset($HTTP_SERVER_VARS['SERVER_NAME']) ? $HTTP_SERVER_VARS['SERVER_NAME'] : 'localhost');
$this->port = !empty($port) ? $port : (isset($HTTP_SERVER_VARS['SERVER_PORT']) ? $HTTP_SERVER_VARS['SERVER_PORT'] : $this->getStandardPort($this->protocol));
$this->path = !empty($HTTP_SERVER_VARS['PHP_SELF']) ? $HTTP_SERVER_VARS['PHP_SELF'] : '/';
$this->querystring = isset($HTTP_SERVER_VARS['QUERY_STRING']) ? $this->_parseRawQuerystring($HTTP_SERVER_VARS['QUERY_STRING']) : null;
$this->anchor = '';
}
// Parse the url and store the various parts
if (!empty($this->url)) {
$urlinfo = parse_url($this->url);
// Default querystring
$this->querystring = array();
foreach ($urlinfo as $key => $value) {
switch ($key) {
case 'scheme':
$this->protocol = $value;
$this->port = $this->getStandardPort($value);
break;
case 'user':
case 'pass':
case 'host':
case 'port':
$this->$key = $value;
break;
case 'path':
if ($value{0} == '/') {
$this->path = $value;
} else {
$path = dirname($this->path) == DIRECTORY_SEPARATOR ? '' : dirname($this->path);
$this->path = sprintf('%s/%s', $path, $value);
}
break;
case 'query':
$this->querystring = $this->_parseRawQueryString($value);
break;
case 'fragment':
$this->anchor = $value;
break;
}
}
}
}
/**
* Returns full url
*
* @return string Full url
* @access public
*/
function getURL()
{
$querystring = $this->getQueryString();
$this->url = $this->protocol . '://'
. $this->user . (!empty($this->pass) ? ':' : '')
. $this->pass . (!empty($this->user) ? '@' : '')
. $this->host . ($this->port == $this->getStandardPort($this->protocol) ? '' : ':' . $this->port)
. $this->path
. (!empty($querystring) ? '?' . $querystring : '')
. (!empty($this->anchor) ? '#' . $this->anchor : '');
return $this->url;
}
/**
* Adds or updates a querystring item (URL parameter).
* Automatically encodes parameters with rawurlencode() if $preencoded
* is false.
* You can pass an array to $value, it gets mapped via [] in the URL if
* $this->useBrackets is activated.
*
* @param string $name Name of item
* @param string $value Value of item
* @param bool $preencoded Whether value is urlencoded or not, default = not
* @access public
*/
function addQueryString($name, $value, $preencoded = false)
{
if ($this->getOption('encode_query_keys')) {
$name = rawurlencode($name);
}
if ($preencoded) {
$this->querystring[$name] = $value;
} else {
$this->querystring[$name] = is_array($value) ? array_map('rawurlencode', $value): rawurlencode($value);
}
}
/**
* Removes a querystring item
*
* @param string $name Name of item
* @access public
*/
function removeQueryString($name)
{
if ($this->getOption('encode_query_keys')) {
$name = rawurlencode($name);
}
if (isset($this->querystring[$name])) {
unset($this->querystring[$name]);
}
}
/**
* Sets the querystring to literally what you supply
*
* @param string $querystring The querystring data. Should be of the format foo=bar&x=y etc
* @access public
*/
function addRawQueryString($querystring)
{
$this->querystring = $this->_parseRawQueryString($querystring);
}
/**
* Returns flat querystring
*
* @return string Querystring
* @access public
*/
function getQueryString()
{
if (!empty($this->querystring)) {
foreach ($this->querystring as $name => $value) {
// Encode var name
$name = rawurlencode($name);
if (is_array($value)) {
foreach ($value as $k => $v) {
$querystring[] = $this->useBrackets ? sprintf('%s[%s]=%s', $name, $k, $v) : ($name . '=' . $v);
}
} elseif (!is_null($value)) {
$querystring[] = $name . '=' . $value;
} else {
$querystring[] = $name;
}
}
$querystring = implode(ini_get('arg_separator.output'), $querystring);
} else {
$querystring = '';
}
return $querystring;
}
/**
* Parses raw querystring and returns an array of it
*
* @param string $querystring The querystring to parse
* @return array An array of the querystring data
* @access private
*/
function _parseRawQuerystring($querystring)
{
$parts = preg_split('/[' . preg_quote(ini_get('arg_separator.input'), '/') . ']/', $querystring, -1, PREG_SPLIT_NO_EMPTY);
$return = array();
foreach ($parts as $part) {
if (strpos($part, '=') !== false) {
$value = substr($part, strpos($part, '=') + 1);
$key = substr($part, 0, strpos($part, '='));
} else {
$value = null;
$key = $part;
}
if (!$this->getOption('encode_query_keys')) {
$key = rawurldecode($key);
}
if (preg_match('#^(.*)\[([0-9a-z_-]*)\]#i', $key, $matches)) {
$key = $matches[1];
$idx = $matches[2];
// Ensure is an array
if (empty($return[$key]) || !is_array($return[$key])) {
$return[$key] = array();
}
// Add data
if ($idx === '') {
$return[$key][] = $value;
} else {
$return[$key][$idx] = $value;
}
} elseif (!$this->useBrackets AND !empty($return[$key])) {
$return[$key] = (array)$return[$key];
$return[$key][] = $value;
} else {
$return[$key] = $value;
}
}
return $return;
}
/**
* Resolves //, ../ and ./ from a path and returns
* the result. Eg:
*
* /foo/bar/../boo.php => /foo/boo.php
* /foo/bar/../../boo.php => /boo.php
* /foo/bar/.././/boo.php => /foo/boo.php
*
* This method can also be called statically.
*
* @param string $path URL path to resolve
* @return string The result
*/
function resolvePath($path)
{
$path = explode('/', str_replace('//', '/', $path));
for ($i=0; $i<count($path); $i++) {
if ($path[$i] == '.') {
unset($path[$i]);
$path = array_values($path);
$i--;
} elseif ($path[$i] == '..' AND ($i > 1 OR ($i == 1 AND $path[0] != '') ) ) {
unset($path[$i]);
unset($path[$i-1]);
$path = array_values($path);
$i -= 2;
} elseif ($path[$i] == '..' AND $i == 1 AND $path[0] == '') {
unset($path[$i]);
$path = array_values($path);
$i--;
} else {
continue;
}
}
return implode('/', $path);
}
/**
* Returns the standard port number for a protocol
*
* @param string $scheme The protocol to lookup
* @return integer Port number or NULL if no scheme matches
*
* @author Philippe Jausions <Philippe.Jausions@11abacus.com>
*/
function getStandardPort($scheme)
{
switch (strtolower($scheme)) {
case 'http': return 80;
case 'https': return 443;
case 'ftp': return 21;
case 'imap': return 143;
case 'imaps': return 993;
case 'pop3': return 110;
case 'pop3s': return 995;
default: return null;
}
}
/**
* Forces the URL to a particular protocol
*
* @param string $protocol Protocol to force the URL to
* @param integer $port Optional port (standard port is used by default)
*/
function setProtocol($protocol, $port = null)
{
$this->protocol = $protocol;
$this->port = is_null($port) ? $this->getStandardPort($protocol) : $port;
}
/**
* Set an option
*
* This function set an option
* to be used thorough the script.
*
* @access public
* @param string $optionName The optionname to set
* @param string $value The value of this option.
*/
function setOption($optionName, $value)
{
if (!array_key_exists($optionName, $this->options)) {
return false;
}
$this->options[$optionName] = $value;
$this->initialize();
}
/**
* Get an option
*
* This function gets an option
* from the $this->options array
* and return it's value.
*
* @access public
* @param string $opionName The name of the option to retrieve
* @see $this->options
*/
function getOption($optionName)
{
if (!isset($this->options[$optionName])) {
return false;
}
return $this->options[$optionName];
}
}
?>

1118
vtlib/thirdparty/network/PEAR.php vendored Normal file

File diff suppressed because it is too large Load Diff

1522
vtlib/thirdparty/network/Request.php vendored Normal file

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,106 @@
<?php
/**
* Listener for HTTP_Request and HTTP_Response objects
*
* PHP versions 4 and 5
*
* LICENSE:
*
* Copyright (c) 2002-2007, Richard Heyes
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* o Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* o Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* o The names of the authors may not be used to endorse or promote
* products derived from this software without specific prior written
* permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* @category HTTP
* @package HTTP_Request
* @author Alexey Borzov <avb@php.net>
* @copyright 2002-2007 Richard Heyes
* @license http://opensource.org/licenses/bsd-license.php New BSD License
* @version CVS: $Id: Listener.php,v 1.3 2007/05/18 10:33:31 avb Exp $
* @link http://pear.php.net/package/HTTP_Request/
*/
/**
* Listener for HTTP_Request and HTTP_Response objects
*
* This class implements the Observer part of a Subject-Observer
* design pattern.
*
* @category HTTP
* @package HTTP_Request
* @author Alexey Borzov <avb@php.net>
* @version Release: 1.4.4
*/
class HTTP_Request_Listener
{
/**
* A listener's identifier
* @var string
*/
var $_id;
/**
* Constructor, sets the object's identifier
*
* @access public
*/
function HTTP_Request_Listener()
{
$this->_id = md5(uniqid('http_request_', 1));
}
/**
* Returns the listener's identifier
*
* @access public
* @return string
*/
function getId()
{
return $this->_id;
}
/**
* This method is called when Listener is notified of an event
*
* @access public
* @param object an object the listener is attached to
* @param string Event name
* @param mixed Additional data
* @abstract
*/
function update(&$subject, $event, $data = null)
{
echo "Notified of event: '$event'\n";
if (null !== $data) {
echo "Additional data: ";
var_dump($data);
}
}
}
?>

13675
vtlib/thirdparty/parser/feed/simplepie.inc vendored Normal file

File diff suppressed because one or more lines are too long

37
vtlib/vtlib-Copyright.txt Normal file
View File

@ -0,0 +1,37 @@
vtlib uses third party libraries to enable certain functionality.
1. For creating and unpacking zip files
-- ====================================
vtlib/thirdparty/dZip.php
vtlib/thirdparty/dUnzip2.inc.php
DOWNLOAD URL:
http://www.phpclasses.org/browse/package/2495/
BSD License: http://www.opensource.org/licenses/bsd-license.html
NOTE: Bug Fix was added to function addFile of dZip class.
2. For Feed Parsing
-- ===============
vtlib/thirdparty/parser/feed/simplepie.inc
DOWNLOAD URL: http://simplepie.org
BSD License: http://www.opensource.org/licenses/bsd-license.php
3. For HTTP Communication
-- ======================
Vtiger_Net_Client is based on the following:
http://pear.php.net/package/HTTP_Request
[License: http://www.opensource.org/licenses/bsd-license.php]
http://pear.php.net/package/Net_URL
[License: http://www.opensource.org/licenses/bsd-license.php]
http://pear.php.net/package/Net_Socket
[License: http://www.php.net/license/3_01.txt]
http://pear.php.net/package/PEAR (Only PEAR.php)
[License: http://www.php.net/license/3_01.txt]