first commit

This commit is contained in:
droomo 2015-09-30 03:26:19 +08:00
parent 51dfabee0d
commit 2e7257b7b2
12 changed files with 6828 additions and 0 deletions

View File

@ -0,0 +1,3 @@
<?php
//检测API路径
require_once dirname(__FILE__).DIRECTORY_SEPARATOR.'sdk.class.php';

13
AliOssSdk/conf.inc.php Normal file
View File

@ -0,0 +1,13 @@
<?php
//是否记录日志
define('ALI_LOG', TRUE);
//自定义日志路径,如果没有设置,则使用系统默认路径,在./logs/
//define('ALI_LOG_PATH','');
//是否显示LOG输出
define('ALI_DISPLAY_LOG', FALSE);
//语言版本设置
define('ALI_LANG', 'zh');

File diff suppressed because it is too large Load Diff

99
AliOssSdk/lang/zh.inc.php Normal file
View File

@ -0,0 +1,99 @@
<?php
/*%*************************************************************************************%*/
//access id & access key 相关
define('NOT_SET_OSS_ACCESS_ID', '未设置OSS服务的ACCESS ID');
define('NOT_SET_OSS_ACCESS_KEY', '未设置OSS服务的ACCESS KEY');
define('NOT_SET_OSS_ACCESS_ID_AND_ACCESS_KEY', '没有设置ACCESS ID & ACCESS KEY');
define('OSS_ACCESS_ID_OR_ACCESS_KEY_EMPTY', 'ACCESS ID或ACCESS KEY为空');
/*%*************************************************************************************%*/
//OSS语言包以及文件相关
define('OSS_LANG_FILE_NOT_EXIST', 'OSS语言包文件不存在');
define('OSS_CONFIG_FILE_NOT_EXIST',OSS_API_PATH.DIRECTORY_SEPARATOR.'conf.inc.php不存在');
define('OSS_UTILS_FILE_NOT_EXIST',OSS_API_PATH.DIRECTORY_SEPARATOR.'util'.DIRECTORY_SEPARATOR.'utils.php不存在');
define('OSS_CURL_EXTENSION_MUST_BE_LOAD','系统没有安装CURL扩展');
define('OSS_NO_ANY_EXTENSIONS_LOADED','系统没有安装任何扩展,请检查系统配置');
/*%*************************************************************************************%*/
//日志文件相关
define('OSS_WRITE_LOG_TO_FILE_FAILED','日志写入失败,请检查日志文件是否存在或者日志文件的权限');
define('OSS_LOG_PATH_NOT_EXIST','日志路径不存在');
/*%**************************************************************************************%*/
//OSS bucket操作相关
define('OSS_OPTIONS_MUST_BE_ARRAY', '$option必须为数组');
define('OSS_GET_BUCKET_LIST_SUCCESS','获取Bucket列表成功!');
define('OSS_GET_BUCKET_LIST_FAILED', '获取Bucket列表失败!');
define('OSS_CREATE_BUCKET_SUCCESS', '创建Bucket成功');
define('OSS_CREATE_BUCKET_FAILED', '创建Bucket失败');
define('OSS_DELETE_BUCKET_SUCCESS', '删除Bucket成功');
define('OSS_DELETE_BUCKET_FAILED', '删除Bucket失败');
define('OSS_BUCKET_NAME_INVALID', '未通过Bucket名称规则校验');
define('OSS_GET_BUCKET_ACL_SUCCESS','获取Bucket ACL成功');
define('OSS_GET_BUCKET_ACL_FAILED','获取Bucket ACL失败');
define('OSS_SET_BUCKET_ACL_SUCCESS','设置Bucket ACL成功');
define('OSS_SET_BUCKET_ACL_FAILED','设置Bucket ACL失败');
define('OSS_ACL_INVALID','ACL不在允许范围,目前仅允许(private,public-read,public-read-write三种权限)');
define('OSS_BUCKET_IS_NOT_ALLOWED_EMPTY', 'Bucket不允许为空');
define('OSS_TARGET_BUCKET_IS_NOT_ALLOWED_EMPTY', 'TargetBucket不允许为空');
define('OSS_INDEX_DOCUMENT_IS_NOT_ALLOWED_EMPTY', 'IndexDocument不允许为空');
/*%****************************************************************************************%*/
//OSS object操作相关
define('OSS_GET_OBJECT_LIST_SUCCESS','获得OBJECT列表成功');
define('OSS_GET_OBJECT_LIST_FAILED','获得OBJECT列表失败');
define('OSS_CREATE_OBJECT_DIR_SUCCESS','创建OBJECT目录成功');
define('OSS_CREATE_OBJECT_DIR_FAILED','创建OBJECT目录失败');
define('OSS_DELETE_OBJECT_SUCCESS','删除OBJECT成功');
define('OSS_DELETE_OBJECT_FAILED','删除OBJECT失败');
define('OSS_UPLOAD_FILE_BY_CONTENT_SUCCESS','通过Http Body上传文件成功');
define('OSS_UPLOAD_FILE_BY_CONTENT_FAILED','通过Http Body上传文件失败');
define('OSS_GET_OBJECT_META_SUCCESS','获得OBJECT META成功');
define('OSS_GET_OBJECT_META_FAILED','获得OBJECT META失败');
define('OSS_OBJECT_NAME_INVALID','未通过Object名称规则校验');
define('OSS_OBJECT_IS_NOT_ALLOWED_EMPTY','Object不允许为空');
define('OSS_INVALID_HTTP_BODY_CONTENT','Http Body的内容非法');
define('OSS_GET_OBJECT_SUCCESS','获得Object成功');
define('OSS_GET_OBJECT_FAILED','获得Object失败');
define('OSS_OBJECT_EXIST','Object存在');
define('OSS_OBJECT_NOT_EXIST','Object不存在');
define('OSS_NOT_SET_HTTP_CONTENT','未设置Http Body');
define('OSS_INVALID_CONTENT_LENGTH','非法的Content-Length值');
define('OSS_CONTENT_LENGTH_MUST_MORE_THAN_ZERO','Content-Length必须大于0');
define('OSS_UPLOAD_FILE_NOT_EXIST','上传文件不存在');
define('OSS_COPY_OBJECT_SUCCESS','拷贝Object成功');
define('OSS_COPY_OBJECT_FAILED', '拷贝Object失败');
define('OSS_FILE_NOT_EXIST','文件不存在');
define('OSS_FILE_PATH_IS_NOT_ALLOWED_EMPTY', '上传文件路径为空');
define('OSS_INVALID_METHOD','Method值非法');
/*%****************************************************************************************%*/
//OSS object Group操作相关
define('OSS_CREATE_OBJECT_GROUP_SUCCESS','创建Object Group成功');
define('OSS_CREATE_OBJECT_GROUP_FAILED','创建Object Group失败');
define('OSS_GET_OBJECT_GROUP_SUCCESS','获取Object Group成功');
define('OSS_GET_OBJECT_GROUP_FAILED','获取Object Group失败');
define('OSS_GET_OBJECT_GROUP_INDEX_SUCCESS','获取Object Group Index成功');
define('OSS_GET_OBJECT_GROUP_INDEX_FAILED','获取Object Group Index失败');
define('OSS_GET_OBJECT_GROUP_META_SUCCESS','获取Object Group Group Meta成功');
define('OSS_GET_OBJECT_GROUP_META_FAILED','获取Object Group Group Meta失败');
define('OSS_DELETE_OBJECT_GROUP_SUCCESS','删除Object Group Group成功');
define('OSS_DELETE_OBJECT_GROUP_FAILED','删除Object Group Group失败');
define('OSS_OBJECT_GROUP_IS_NOT_ALLOWED_EMPTY', 'Object Group不允许为空');
define('OSS_OBJECT_ARRAY_IS_EMPTY','创建Object Group的Object不允许为空');
define('OSS_OBJECT_GROUP_TOO_MANY_OBJECT','每个Object Group最多包含1000个Object');
/*%****************************************************************************************%*/
//OSS Multi-Part Upload相关
define('OSS_INITIATE_MULTI_PART_SUCCESS', '初始化Multi-Part Upload成功');
define('OSS_INITIATE_MULTI_PART_FAILED', '初始化Multi-Part Upload失败');
/*%*******************************************************************************************%*/
//其他
define('OSS_INVALID_OPTION_HEADERS', 'OPTIONS不是数组');

View File

@ -0,0 +1,25 @@
Copyright (c) 2006-2010 Ryan Parman, Foleeo Inc., and contributors. All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are
permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this list of
conditions and the following disclaimer.
* 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.
* Neither the name of Ryan Parman, Foleeo Inc. nor the names of its contributors may 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 HOLDERS
AND 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.

View File

@ -0,0 +1,15 @@
# RequestCore
RequestCore is a lightweight cURL-based HTTP request/response class that leverages MultiCurl for parallel requests.
### PEAR HTTP_Request?
RequestCore was written as a replacement for [PEAR HTTP_Request](http://pear.php.net/http_request/). While PEAR HTTP_Request is full-featured and heavy, RequestCore features only the essentials and is very lightweight. It also leverages the batch request support in cURL's `curl_multi_exec()` to enable multi-threaded requests that fire in parallel.
### Reference and Download
You can find the class reference at <http://skyzyx.github.com/requestcore/>. You can get the code from <http://github.com/skyzyx/requestcore>.
### License and Copyright
This code is Copyright (c) 2008-2010, Ryan Parman. However, I'm licensing this code for others to use under the [Simplified BSD license](http://www.opensource.org/licenses/bsd-license.php).

File diff suppressed because it is too large Load Diff

2104
AliOssSdk/sdk.class.php Normal file

File diff suppressed because it is too large Load Diff

139
AliOssSdk/thirdparty/xml2array.class.php vendored Normal file
View File

@ -0,0 +1,139 @@
<?php
/**
* XML2Array: A class to convert XML to array in PHP
* It returns the array which can be converted back to XML using the Array2XML script
* It takes an XML string or a DOMDocument object as an input.
*
* See Array2XML: http://www.lalit.org/lab/convert-php-array-to-xml-with-attributes
*
* Author : Lalit Patel
* Website: http://www.lalit.org/lab/convert-xml-to-array-in-php-xml2array
* License: Apache License 2.0
* http://www.apache.org/licenses/LICENSE-2.0
* Version: 0.1 (07 Dec 2011)
* Version: 0.2 (04 Mar 2012)
* Fixed typo 'DomDocument' to 'DOMDocument'
*
* Usage:
* $array = XML2Array::createArray($xml);
*/
class XML2Array {
private static $xml = null;
private static $encoding = 'UTF-8';
/**
* Initialize the root XML node [optional]
* @param $version
* @param $encoding
* @param $format_output
*/
public static function init($version = '1.0', $encoding = 'UTF-8', $format_output = true) {
self::$xml = new DOMDocument($version, $encoding);
self::$xml->formatOutput = $format_output;
self::$encoding = $encoding;
}
/**
* @param $input_xml
* @return mixed
* @throws Exception
*/
public static function &createArray($input_xml) {
$xml = self::getXMLRoot();
if(is_string($input_xml)) {
$parsed = $xml->loadXML($input_xml);
if(!$parsed) {
throw new Exception('[XML2Array] Error parsing the XML string.');
}
} else {
if(get_class($input_xml) != 'DOMDocument') {
throw new Exception('[XML2Array] The input XML object should be of type: DOMDocument.');
}
$xml = self::$xml = $input_xml;
}
$array[$xml->documentElement->tagName] = self::convert($xml->documentElement);
self::$xml = null; // clear the xml node in the class for 2nd time use.
return $array;
}
/**
* Convert an Array to XML
* @param mixed $node - XML as a string or as an object of DOMDocument
* @return mixed
*/
private static function &convert($node) {
$output = array();
switch ($node->nodeType) {
case XML_CDATA_SECTION_NODE:
$output['@cdata'] = trim($node->textContent);
break;
case XML_TEXT_NODE:
$output = trim($node->textContent);
break;
case XML_ELEMENT_NODE:
// for each child node, call the covert function recursively
for ($i=0, $m=$node->childNodes->length; $i<$m; $i++) {
$child = $node->childNodes->item($i);
$v = self::convert($child);
if(isset($child->tagName)) {
$t = $child->tagName;
// assume more nodes of same kind are coming
if(!isset($output[$t])) {
$output[$t] = array();
}
$output[$t][] = $v;
} else {
//check if it is not an empty text node
if($v !== '') {
$output = $v;
}
}
}
if(is_array($output)) {
// if only one node of its kind, assign it directly instead if array($value);
foreach ($output as $t => $v) {
if(is_array($v) && count($v)==1) {
$output[$t] = $v[0];
}
}
if(empty($output)) {
//for empty nodes
$output = '';
}
}
// loop through the attributes and collect them
if($node->attributes->length) {
$a = array();
foreach($node->attributes as $attrName => $attrNode) {
$a[$attrName] = (string) $attrNode->value;
}
// if its an leaf node, store the value in @value instead of directly storing it.
if(!is_array($output)) {
$output = array('@value' => $output);
}
$output['@attributes'] = $a;
}
break;
}
return $output;
}
/*
* Get the root XML node, if there isn't one, create it.
*/
private static function getXMLRoot(){
if(empty(self::$xml)) {
self::init();
}
return self::$xml;
}
}

View File

@ -0,0 +1,240 @@
<?php
/**
* 获得文件的mime type类型
* @author xiaobing.meng
*
*/
class MimeTypes {
public static $mime_types = array (
'xlsx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
'xltx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.template',
'potx' => 'application/vnd.openxmlformats-officedocument.presentationml.template',
'ppsx' => 'application/vnd.openxmlformats-officedocument.presentationml.slideshow',
'pptx' => 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
'sldx' => 'application/vnd.openxmlformats-officedocument.presentationml.slide',
'docx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
'dotx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.template',
'xlam' => 'application/vnd.ms-excel.addin.macroEnabled.12',
'xlsb' => 'application/vnd.ms-excel.sheet.binary.macroEnabled.12',
'apk' => 'application/vnd.android.package-archive',
'hqx' => 'application/mac-binhex40',
'cpt' => 'application/mac-compactpro',
'doc' => 'application/msword',
'ogg' => 'application/ogg',
'pdf' => 'application/pdf',
'rtf' => 'text/rtf',
'mif' => 'application/vnd.mif',
'xls' => 'application/vnd.ms-excel',
'ppt' => 'application/vnd.ms-powerpoint',
'odc' => 'application/vnd.oasis.opendocument.chart',
'odb' => 'application/vnd.oasis.opendocument.database',
'odf' => 'application/vnd.oasis.opendocument.formula',
'odg' => 'application/vnd.oasis.opendocument.graphics',
'otg' => 'application/vnd.oasis.opendocument.graphics-template',
'odi' => 'application/vnd.oasis.opendocument.image',
'odp' => 'application/vnd.oasis.opendocument.presentation',
'otp' => 'application/vnd.oasis.opendocument.presentation-template',
'ods' => 'application/vnd.oasis.opendocument.spreadsheet',
'ots' => 'application/vnd.oasis.opendocument.spreadsheet-template',
'odt' => 'application/vnd.oasis.opendocument.text',
'odm' => 'application/vnd.oasis.opendocument.text-master',
'ott' => 'application/vnd.oasis.opendocument.text-template',
'oth' => 'application/vnd.oasis.opendocument.text-web',
'sxw' => 'application/vnd.sun.xml.writer',
'stw' => 'application/vnd.sun.xml.writer.template',
'sxc' => 'application/vnd.sun.xml.calc',
'stc' => 'application/vnd.sun.xml.calc.template',
'sxd' => 'application/vnd.sun.xml.draw',
'std' => 'application/vnd.sun.xml.draw.template',
'sxi' => 'application/vnd.sun.xml.impress',
'sti' => 'application/vnd.sun.xml.impress.template',
'sxg' => 'application/vnd.sun.xml.writer.global',
'sxm' => 'application/vnd.sun.xml.math',
'sis' => 'application/vnd.symbian.install',
'wbxml' => 'application/vnd.wap.wbxml',
'wmlc' => 'application/vnd.wap.wmlc',
'wmlsc' => 'application/vnd.wap.wmlscriptc',
'bcpio' => 'application/x-bcpio',
'torrent' => 'application/x-bittorrent',
'bz2' => 'application/x-bzip2',
'vcd' => 'application/x-cdlink',
'pgn' => 'application/x-chess-pgn',
'cpio' => 'application/x-cpio',
'csh' => 'application/x-csh',
'dvi' => 'application/x-dvi',
'spl' => 'application/x-futuresplash',
'gtar' => 'application/x-gtar',
'hdf' => 'application/x-hdf',
'jar' => 'application/x-java-archive',
'jnlp' => 'application/x-java-jnlp-file',
'js' => 'application/x-javascript',
'ksp' => 'application/x-kspread',
'chrt' => 'application/x-kchart',
'kil' => 'application/x-killustrator',
'latex' => 'application/x-latex',
'rpm' => 'application/x-rpm',
'sh' => 'application/x-sh',
'shar' => 'application/x-shar',
'swf' => 'application/x-shockwave-flash',
'sit' => 'application/x-stuffit',
'sv4cpio' => 'application/x-sv4cpio',
'sv4crc' => 'application/x-sv4crc',
'tar' => 'application/x-tar',
'tcl' => 'application/x-tcl',
'tex' => 'application/x-tex',
'man' => 'application/x-troff-man',
'me' => 'application/x-troff-me',
'ms' => 'application/x-troff-ms',
'ustar' => 'application/x-ustar',
'src' => 'application/x-wais-source',
'zip' => 'application/zip',
'm3u' => 'audio/x-mpegurl',
'ra' => 'audio/x-pn-realaudio',
'wav' => 'audio/x-wav',
'wma' => 'audio/x-ms-wma',
'wax' => 'audio/x-ms-wax',
'pdb' => 'chemical/x-pdb',
'xyz' => 'chemical/x-xyz',
'bmp' => 'image/bmp',
'gif' => 'image/gif',
'ief' => 'image/ief',
'png' => 'image/png',
'wbmp' => 'image/vnd.wap.wbmp',
'ras' => 'image/x-cmu-raster',
'pnm' => 'image/x-portable-anymap',
'pbm' => 'image/x-portable-bitmap',
'pgm' => 'image/x-portable-graymap',
'ppm' => 'image/x-portable-pixmap',
'rgb' => 'image/x-rgb',
'xbm' => 'image/x-xbitmap',
'xpm' => 'image/x-xpixmap',
'xwd' => 'image/x-xwindowdump',
'css' => 'text/css',
'rtx' => 'text/richtext',
'tsv' => 'text/tab-separated-values',
'jad' => 'text/vnd.sun.j2me.app-descriptor',
'wml' => 'text/vnd.wap.wml',
'wmls' => 'text/vnd.wap.wmlscript',
'etx' => 'text/x-setext',
'mxu' => 'video/vnd.mpegurl',
'flv' => 'video/x-flv',
'wm' => 'video/x-ms-wm',
'wmv' => 'video/x-ms-wmv',
'wmx' => 'video/x-ms-wmx',
'wvx' => 'video/x-ms-wvx',
'avi' => 'video/x-msvideo',
'movie' => 'video/x-sgi-movie',
'ice' => 'x-conference/x-cooltalk',
'3gp' => 'video/3gpp',
'ai' => 'application/postscript',
'aif' => 'audio/x-aiff',
'aifc' => 'audio/x-aiff',
'aiff' => 'audio/x-aiff',
'asc' => 'text/plain',
'atom' => 'application/atom+xml',
'au' => 'audio/basic',
'bin' => 'application/octet-stream',
'cdf' => 'application/x-netcdf',
'cgm' => 'image/cgm',
'class' => 'application/octet-stream',
'dcr' => 'application/x-director',
'dif' => 'video/x-dv',
'dir' => 'application/x-director',
'djv' => 'image/vnd.djvu',
'djvu' => 'image/vnd.djvu',
'dll' => 'application/octet-stream',
'dmg' => 'application/octet-stream',
'dms' => 'application/octet-stream',
'dtd' => 'application/xml-dtd',
'dv' => 'video/x-dv',
'dxr' => 'application/x-director',
'eps' => 'application/postscript',
'exe' => 'application/octet-stream',
'ez' => 'application/andrew-inset',
'gram' => 'application/srgs',
'grxml' => 'application/srgs+xml',
'gz' => 'application/x-gzip',
'htm' => 'text/html',
'html' => 'text/html',
'ico' => 'image/x-icon',
'ics' => 'text/calendar',
'ifb' => 'text/calendar',
'iges' => 'model/iges',
'igs' => 'model/iges',
'jp2' => 'image/jp2',
'jpe' => 'image/jpeg',
'jpeg' => 'image/jpeg',
'jpg' => 'image/jpeg',
'kar' => 'audio/midi',
'lha' => 'application/octet-stream',
'lzh' => 'application/octet-stream',
'm4a' => 'audio/mp4a-latm',
'm4p' => 'audio/mp4a-latm',
'm4u' => 'video/vnd.mpegurl',
'm4v' => 'video/x-m4v',
'mac' => 'image/x-macpaint',
'mathml' => 'application/mathml+xml',
'mesh' => 'model/mesh',
'mid' => 'audio/midi',
'midi' => 'audio/midi',
'mov' => 'video/quicktime',
'mp2' => 'audio/mpeg',
'mp3' => 'audio/mpeg',
'mp4' => 'video/mp4',
'mpe' => 'video/mpeg',
'mpeg' => 'video/mpeg',
'mpg' => 'video/mpeg',
'mpga' => 'audio/mpeg',
'msh' => 'model/mesh',
'nc' => 'application/x-netcdf',
'oda' => 'application/oda',
'ogv' => 'video/ogv',
'pct' => 'image/pict',
'pic' => 'image/pict',
'pict' => 'image/pict',
'pnt' => 'image/x-macpaint',
'pntg' => 'image/x-macpaint',
'ps' => 'application/postscript',
'qt' => 'video/quicktime',
'qti' => 'image/x-quicktime',
'qtif' => 'image/x-quicktime',
'ram' => 'audio/x-pn-realaudio',
'rdf' => 'application/rdf+xml',
'rm' => 'application/vnd.rn-realmedia',
'roff' => 'application/x-troff',
'sgm' => 'text/sgml',
'sgml' => 'text/sgml',
'silo' => 'model/mesh',
'skd' => 'application/x-koan',
'skm' => 'application/x-koan',
'skp' => 'application/x-koan',
'skt' => 'application/x-koan',
'smi' => 'application/smil',
'smil' => 'application/smil',
'snd' => 'audio/basic',
'so' => 'application/octet-stream',
'svg' => 'image/svg+xml',
't' => 'application/x-troff',
'texi' => 'application/x-texinfo',
'texinfo' => 'application/x-texinfo',
'tif' => 'image/tiff',
'tiff' => 'image/tiff',
'tr' => 'application/x-troff',
'txt' => 'text/plain',
'vrml' => 'model/vrml',
'vxml' => 'application/voicexml+xml',
'webm' => 'video/webm',
'wrl' => 'model/vrml',
'xht' => 'application/xhtml+xml',
'xhtml' => 'application/xhtml+xml',
'xml' => 'application/xml',
'xsl' => 'application/xml',
'xslt' => 'application/xslt+xml',
'xul' => 'application/vnd.mozilla.xul+xml',
);
public static function get_mimetype($ext) {
return (isset ( self::$mime_types [$ext] ) ? self::$mime_types [$ext] : 'application/octet-stream');
}
}

View File

@ -0,0 +1,434 @@
<?php
require_once dirname(dirname(__FILE__)).DIRECTORY_SEPARATOR.'thirdparty'.DIRECTORY_SEPARATOR.'xml2array.class.php';
// EXCEPTIONS
/**
* OSS异常类继承自基类
*/
class OSS_Exception extends Exception {}
class body
{
public $Part;
}
class Part
{
public $PartNumber;
public $ETag;
}
class OSSUtil
{
const OSS_CONTENT = 'content';
const OSS_LENGTH = 'length';
const OSS_HEADERS = 'headers';
const OSS_MAX_OBJECT_GROUP_VALUE = 1000;
const OSS_MAX_PART_SIZE = 524288000;
const OSS_MID_PART_SIZE = 52428800;
const OSS_MIN_PART_SIZE = 5242880;
//oss默认响应头
static $OSS_DEFAULT_REAPONSE_HEADERS = array(
'date','content-type','content-length','connection','accept-ranges','cache-control','content-disposition','content-encoding','content-language',
'etag','expires','last-modified','server'
);
public static function get_object_list_marker_from_xml($xml, &$marker)
{
$xml = new SimpleXMLElement($xml);
$is_truncated = $xml->IsTruncated;
$object_list = array();
$marker = $xml->NextMarker;
foreach ( $xml->Contents as $content) {
array_push($object_list, $content->Key);
}
return $object_list;
}
public static function print_res($response, $msg = "", $is_simple_print = true){
if ($is_simple_print){
if ((int)($response->status / 100) == 2){
echo $msg." OK\n";
}
else{
echo "ret:".$response->status."\n";
echo $msg." FAIL\n";
}
}
else {
echo '|-----------------------Start---------------------------------------------------------------------------------------------------'."\n";
echo '|-Status:' . $response->status . "\n";
echo '|-Body:' ."\n";
$body = $response->body . "\n";
echo $body . "\n";
echo "|-Header:\n";
print_r ($response->header);
echo '-----------------------End-----------------------------------------------------------------------------------------------------'."\n\n";
}
}
/*%******************************************************************************************************%*/
//工具类相关
/**
* 生成query params
* @param array $array 关联数组
* @return string 返回诸如 key1=value1&key2=value2
*/
public static function to_query_string($options = array()){
$temp = array();
uksort($options, 'strnatcasecmp');
foreach ($options as $key => $value){
if (is_string($key) && !is_array($value)){
$temp[] = rawurlencode($key) . '=' . rawurlencode($value);
}
}
return implode('&', $temp);
}
/**
* @param $str
* @return string
*/
public static function hex_to_base64($str){
$result = '';
for ($i = 0; $i < strlen($str); $i += 2){
$result .= chr(hexdec(substr($str, $i, 2)));
}
return base64_encode($result);
}
public static function s_replace($subject){
$search = array('<', '>', '&', '\'', '"');
$replace = array('&lt;', '&gt;', '&amp;', '&apos;', '&quot;');
return str_replace($search, $replace, $subject);
}
/**
* @param $subject
* @return mixed
*/
public static function replace_invalid_xml_char($subject){
$search = array(
'&#01;', '&#02;', '&#03;', '&#04;', '&#05;', '&#06;', '&#07;', '&#08;', '&#09;', '&#10;', '&#11;', '&#12;', '&#13;',
'&#14;', '&#15;', '&#16;', '&#17;', '&#18;', '&#19;', '&#20;', '&#21;', '&#22;', '&#23;', '&#24;', '&#25;', '&#26;',
'&#27;', '&#28;', '&#29;', '&#30;', '&#31;', '&#127;'
);
$replace = array(
'%01', '%02', '%03', '%04', '%05', '%06', '%07', '%08', '%09', '%0A', '%0B', '%0C', '%0D',
'%0E', '%0F', '%10', '%11', '%12', '%13', '%14', '%15', '%16', '%17', '%18', '%19', '%1A',
'%1B', '%1C', '%1D', '%1E', '%1F', '%7F'
);
return str_replace($search, $replace, $subject);
}
/**
* @param $str
* @return int
*/
public static function chk_chinese($str){
return preg_match('/[\x80-\xff]./', $str);
}
/**
* 检测是否GB2312编码
* @param string $str
* @author xiaobing
* @since 2012-03-20
* @return boolean false UTF-8编码 TRUE GB2312编码
*/
public static function is_gb2312($str) {
for($i=0; $i<strlen($str); $i++) {
$v = ord( $str[$i]);
if( $v > 127) {
if( ($v >= 228) && ($v <= 233)){
if( ($i+2) >= (strlen($str) - 1)) return true; // not enough characters
$v1 = ord( $str[$i+1]);
$v2 = ord( $str[$i+2]);
if( ($v1 >= 128) && ($v1 <=191) && ($v2 >=128) && ($v2 <= 191))
return false; //UTF-8编码
else
return true; //GB编码
}
}
}
}
/**
* 检测是否GBK编码
* @param string $str
* @param boolean $gbk
* @author xiaobing
* @since 2012-06-04
* @return boolean
*/
public static function check_char($str, $gbk = true){
for($i=0; $i<strlen($str); $i++) {
$v = ord( $str[$i]);
if( $v > 127){
if( ($v >= 228) && ($v <= 233)){
if(($i+2)>= (strlen($str)-1)) return $gbk?true:FALSE; // not enough characters
$v1 = ord( $str[$i+1]); $v2 = ord( $str[$i+2]);
if($gbk){
return (($v1 >= 128) && ($v1 <=191) && ($v2 >=128) && ($v2 <= 191))?FALSE:TRUE;//GBK
}else{
return (($v1 >= 128) && ($v1 <=191) && ($v2 >=128) && ($v2 <= 191))?TRUE:FALSE;
}
}
}
}
return $gbk?TRUE:FALSE;
}
/**
* 检验bucket名称是否合法
* bucket的命名规范
* 1. 只能包括小写字母,数字
* 2. 必须以小写字母或者数字开头
* 3. 长度必须在3-63字节之间
* @param string $bucket (Required)
* @author xiaobing
* @since 2011-12-27
* @return boolean
*/
public static function validate_bucket($bucket){
$pattern = '/^[a-z0-9][a-z0-9-]{2,62}$/';
if (!preg_match($pattern, $bucket)) {
return false;
}
return true;
}
/**
* 检验object名称是否合法
* object命名规范:
* 1. 规则长度必须在1-1023字节之间
* 2. 使用UTF-8编码
* @param string $object (Required)
* @author xiaobing
* @since 2011-12-27
* @return boolean
*/
public static function validate_object($object){
$pattern = '/^.{1,1023}$/';
if (empty($object) || !preg_match($pattern, $object)) {
return false;
}
return true;
}
/**
* 检验$options
* @param array $options (Optional)
* @throws OSS_Exception
* @author xiaobing
* @since 2011-12-27
* @return boolean
*/
public static function validate_options($options){
//$options
if ($options != NULL && !is_array($options)) {
throw new OSS_Exception ($options.':'.OSS_OPTIONS_MUST_BE_ARRAY);
}
}
/**
* 检测上传文件的内容
* @param array $options (Optional)
* @throws OSS_Exception
* @author xiaobing
* @since 2011-12-27
* @return string
*/
public static function validate_content($options){
if(isset($options[self::OSS_CONTENT])){
if($options[self::OSS_CONTENT] == '' || !is_string($options[self::OSS_CONTENT])){
throw new OSS_Exception(OSS_INVALID_HTTP_BODY_CONTENT,'-600');
}
}else{
throw new OSS_Exception(OSS_NOT_SET_HTTP_CONTENT, '-601');
}
}
/**
* @param $options
* @throws OSS_Exception
*/
public static function validate_content_length($options){
if(isset($options[self::OSS_LENGTH]) && is_numeric($options[self::OSS_LENGTH])){
if( !$options[self::OSS_LENGTH] > 0){
throw new OSS_Exception(OSS_CONTENT_LENGTH_MUST_MORE_THAN_ZERO, '-602');
}
}else{
throw new OSS_Exception(OSS_INVALID_CONTENT_LENGTH, '-602');
}
}
/**
* 校验BUCKET/OBJECT/OBJECT GROUP是否为空
* @param string $name (Required)
* @param string $errMsg (Required)
* @throws OSS_Exception
* @author xiaobing
* @since 2011-12-27
* @return void
*/
public static function is_empty($name,$errMsg){
if(empty($name)){
throw new OSS_Exception($errMsg);
}
}
/**
* 设置http header
* @param string $key (Required)
* @param string $value (Required)
* @param array $options (Required)
* @throws OSS_Exception
* @author xiaobing
* @return void
*/
public static function set_options_header($key, $value, &$options) {
if (isset($options[self::OSS_HEADERS])) {
if (!is_array($options[self::OSS_HEADERS])) {
throw new OSS_Exception(OSS_INVALID_OPTION_HEADERS, '-600');
}
} else {
$options[self::OSS_HEADERS] = array ();
}
$options[self::OSS_HEADERS][$key] = $value;
}
/**
* 仅供测试使用的接口,请勿使用
*/
public static function generate_file($filename, $size) {
if (file_exists($filename) && $size == filesize($filename)) {
echo $filename." already exists, no need to create again. ";
return;
}
$part_size = 1*1024*1024;
$write_size = 0;
$fp = fopen($filename, "w");
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$charactersLength = strlen($characters);
if($fp)
{
while ($size > 0) {
if ($size < $part_size) {
$write_size = $size;
} else {
$write_size = $part_size;
}
$size -= $write_size;
$a = $characters[rand(0, $charactersLength - 1)];
$content = str_repeat($a, $write_size);
$flag = fwrite($fp, $content);
if(!$flag)
{
echo "write to ". $filename . " failed. <br>";
break;
}
}
}
else
{
echo "open ". $filename . " failed. <br>";
}
fclose($fp);
}
public static function get_content_md5_of_file($filename, $from_pos, $to_pos) {
$content_md5 = "";
if (($to_pos - $from_pos) > self::OSS_MAX_PART_SIZE) {
return $content_md5;
}
$filesize = filesize($filename);
if ($from_pos >= $filesize || $to_pos >= $filesize || $from_pos < 0 || $to_pos < 0) {
return $content_md5;
}
$total_length = $to_pos - $from_pos + 1;
$buffer = 8192;
$left_length = $total_length;
if (!file_exists($filename)) {
return $content_md5;
}
if (false === $fh = fopen($filename, 'rb')) {
return $content_md5;
}
fseek($fh, $from_pos);
$data = '';
while (!feof($fh)) {
if ($left_length >= $buffer) {
$read_length = $buffer;
}
else {
$read_length = $left_length;
}
if ($read_length <= 0) {
break;
}
else {
$data .= fread($fh, $read_length);
$left_length = $left_length - $read_length;
}
}
fclose($fh);
$content_md5 = base64_encode(md5($data, true));
return $content_md5;
}
/**
* 检测是否windows系统因为windows系统默认编码为GBK
* @return bool
*/
public static function is_win(){
return strtoupper(substr(PHP_OS,0,3)) == "WIN";
}
/**
* 主要是由于windows系统编码是gbk遇到中文时候如果不进行转换处理会出现找不到文件的问题
* @param $file_path
* @return string
*/
public static function encoding_path($file_path){
if(self::chk_chinese($file_path) && self::is_win()){
$file_path = iconv('utf-8', 'gbk',$file_path);
}
return $file_path;
}
/**
* 转换响应
* @param $response
* @return array
* @throws Exception
*/
public static function parse_response($response, $format="array"){
//如果启用响应结果转换,则进行转换,否则原样返回
$body = $response->body;
$headers = $response->header;
switch (strtolower($format)) {
case 'array':
$body = empty($body) ? $body : XML2Array::createArray($body);
break;
case "json":
$body = empty($body) ? $body : json_encode(XML2Array::createArray($body));
break;
default:
break;
}
return array(
'success' => $response->isOk(),
'status' => $response->status,
'header' => $headers,
'body' => $body
);
return $response;
}
}

586
Plugin.php Normal file
View File

@ -0,0 +1,586 @@
<?php
require_once 'AliOssSdk/sdk.class.php';
/**
* AliyunOSS储存Typecho上传附件.
*
* @package AliOssForTypecho
* @author droomo.
* @version 1.0
* @link http://www.droomo.top/
*/
class AliOssForTypecho_Plugin implements Typecho_Plugin_Interface
{
const log_path = 'usr/plugins/AliOssForTypecho/logs/';//错误日志路径,相对网站根目录
const UPLOAD_DIR = 'usr/uploads/';//上传文件目录
/**
* 激活插件方法,如果激活失败,直接抛出异常
*
* @access public
* @return void
* @throws Typecho_Plugin_Exception
*/
public static function activate()
{
Typecho_Plugin::factory('Widget_Upload')->uploadHandle = array('AliOssForTypecho_Plugin', 'uploadHandle');
Typecho_Plugin::factory('Widget_Upload')->modifyHandle = array('AliOssForTypecho_Plugin', 'modifyHandle');
Typecho_Plugin::factory('Widget_Upload')->deleteHandle = array('AliOssForTypecho_Plugin', 'deleteHandle');
Typecho_Plugin::factory('Widget_Upload')->attachmentHandle = array('AliOssForTypecho_Plugin', 'attachmentHandle');
Typecho_Plugin::factory('Widget_Upload')->attachmentDataHandle = array('AliOssForTypecho_Plugin', 'attachmentDataHandle');
return _t('启用成功,请进行相应设置!');
}
/**
* 禁用插件方法,如果禁用失败,直接抛出异常
*
* @static
* @access public
* @return void
* @throws Typecho_Plugin_Exception
*/
public static function deactivate(){}
/**
* 获取插件配置面板
*
* @access public
* @param Typecho_Widget_Helper_Form $form 配置面板
* @return void
*/
public static function config(Typecho_Widget_Helper_Form $form)
{ $des = new Typecho_Widget_Helper_Form_Element_Text('des', NULL, '', _t('插件使用说明;'),
_t('<ol>
<li>插件基于阿里云oss_php_sdk_20150819开发包开发若以后SDK开发包更新导致插件不可用请到 <a target="_blank" href="http://www.droomo.top/">我的博客</a> ^ - ^获取新版本插件如果我还用typecho还用阿里云就会更新。<br><br></li>
<li>阿里云OSS支持自定义域名到OSS获取文件如果你的站点运行在阿里云ECS或ACE并十分清楚阿里云服务的内网互通规则配置连接Bucket与获取文件使用不同的链接可以节省流量。如果你不清楚这些那么就选择Bucket所在节点的外网地址。<br><br></li>
<li>运行在云应用引擎上的站点可以使用本插件,插件不会保存文件到服务器,“在服务器保留备份”选项无效。<br><br></li>
<li>若开启“在服务器保留备份”功能:<br>插件尽在上传到OSS失败或者遇到其他错误时会返回错误信息成功保存到OSS但是没有成功保存到服务器的情况下插件不会抛出异常上传过程会继续进行但是会在' . __TYPECHO_ROOT_DIR__ . self::log_path . '目录下生成错误日志"error.log",请定期查阅并清理。<br><br></li>
<li>未作容错性检测,配置错误会导致上传失败。<br><br></li>
<li>Typecho原因无法上传大写扩展名文件本插件不做修补等待Typecho更新。<br><br></li>
<li>如有问题请到 <a target="_blank" href="http://www.droomo.top/">我的博客</a> 留言</li>
</ol>'));
$form->addInput($des);
$buketName = new Typecho_Widget_Helper_Form_Element_Text('bucketName', NULL, 'yourself bucketName',
_t('Bucket名称'), _t('请填写Buket名称'));
$form->addInput($buketName->addRule('required', _t('必须填写Bucket名称')));
$accessId = new Typecho_Widget_Helper_Form_Element_Text('accessId', NULL, 'yourself AccessId',
_t('ACCESS_ID'), _t('请填写ACCESS_ID'));
$form->addInput($accessId->addRule('required', _t('必须填写ACCESS_ID')));
$accessKey = new Typecho_Widget_Helper_Form_Element_Text('accessKey', NULL, 'yourself AccessKey',
_t('ACCESS_KEY'), _t('请填写请填写ACCESS_KEY'));
$form->addInput($accessKey->addRule('required', _t('必须填写ACCESS_KEY')));
$endPoint = new Typecho_Widget_Helper_Form_Element_Select('endPoint',
array(
"oss-cn-qingdao.aliyuncs.com" => '青岛节点外网地址: oss-cn-qingdao.aliyuncs.com',
"oss-cn-qingdao-internal.aliyuncs.com" => '青岛节点内网地址: oss-cn-qingdao-internal.aliyuncs.com',
"oss-cn-beijing.aliyuncs.com" => '北京节点外网地址: oss-cn-beijing.aliyuncs.com',
"oss-cn-beijing-internal.aliyuncs.com" => '北京节点内网地址: oss-cn-beijing-internal.aliyuncs.com',
"oss-cn-hangzhou.aliyuncs.com" => '杭州节点外网地址: oss-cn-hangzhou.aliyuncs.com',
"oss-cn-hangzhou-internal.aliyuncs.com" => '杭州节点内网地址: oss-cn-hangzhou-internal.aliyuncs.com',
"oss-cn-hongkong.aliyuncs.com" => '香港节点外网地址: oss-cn-hongkong.aliyuncs.com',
"oss-cn-hongkong-internal.aliyuncs.com" => '香港节点内网地址: oss-cn-hongkong-internal.aliyuncs.com',
"oss-cn-shenzhen.aliyuncs.com" => '深圳节点外网地址: oss-cn-shenzhen.aliyuncs.com',
"oss-cn-shenzhen-internal.aliyuncs.com" => '深圳节点内网地址: oss-cn-shenzhen-internal.aliyuncs.com',
"oss-cn-shanghai.aliyuncs.com" => '上海节点外网地址: oss-cn-shanghai.aliyuncs.com',
"oss-cn-shanghai-internal.aliyuncs.com" => '上海节点内网地址: oss-cn-shanghai-internal.aliyuncs.com',
"oss-us-west-1.aliyuncs.com" => '美国硅谷节点外网地址: oss-us-west-1.aliyuncs.com',
"oss-us-west-1-internal.aliyuncs.com" => '美国硅谷节点内网地址: oss-us-west-1-internal.aliyuncs.com',
"oss-ap-southeast-1.aliyuncs.com" => '亚太(新加坡)节点外网地址: oss-ap-southeast-1.aliyuncs.com',
"oss-ap-southeast-1-internal.aliyuncs.com" => '亚太(新加坡)节点内网地址: oss-ap-southeast-1-internal.aliyuncs.com',
"other" => '其他'
),
'oss-cn-qingdao.aliyuncs.com', _t('连接Bucket结点所用地址'), _t('参见使用说明第二条'));
$form->addInput($endPoint);
$otherEndPoint = new Typecho_Widget_Helper_Form_Element_Text('otherEndPoint', NULL, '填写其他节点',
'', _t('不包含http://,结尾不包含"/"'));
$form->addInput($otherEndPoint);
$userDir = new Typecho_Widget_Helper_Form_Element_Text('userDir', NULL, 'typecho/',
_t('要储存的路径'), _t('请填写文件储存的路径相对OSS根目录以字母或数字开头以"/"结尾。留空则上传到根目录。'));
$form->addInput($userDir);
$cdnUrl = new Typecho_Widget_Helper_Form_Element_Text('cdnUrl', NULL, '',
_t('自定义域名'), _t('请填写自定义域名留空则访问OSS源不包含http://,结尾不包含"/"'));
$form->addInput($cdnUrl);
$ifLoaclSave = new Typecho_Widget_Helper_Form_Element_Radio('ifLoaclSave', array( "1" => '保留', "0" => '不保留' ), "1",
_t('在服务器保留备份'), _t('是否在服务器保留备份'));
$form->addInput($ifLoaclSave);
echo '<script>
window.onload = function()
{
var select = document.getElementsByName("endPoint")[0];
var input = document.getElementsByName("otherEndPoint")[0];
document.getElementsByName("des")[0].type = "hidden";
if (!(select.value === "other"))
{
input.type = "hidden";
}
document.getElementsByName("endPoint")[0].onchange = function()
{
if (select.value === "other")
{
input.type = "text";
} else
{
input.type = "hidden";
}
}
}
</script>';
}
/**
* 个人用户的配置面板
*
* @access public
* @param Typecho_Widget_Helper_Form $form
* @return void
*/
public static function personalConfig(Typecho_Widget_Helper_Form $form){}
/**
* 上传文件处理函数
*
* @access public
* @param array $file 上传的文件
* @return mixed
*/
public static function uploadHandle($file)
{
if (empty($file['name']))
{
return FALSE;
}
$ext = self::getSafeName($file['name']);
if (!self::checkFileType($ext))
{
return FALSE;
}
$options = Typecho_Widget::widget('Widget_Options');
$date = new Typecho_Date($options->gmtTime);
$path = $date->year . '/' . $date->month. '/' . $date->day . '/';
//获取文件名
$fileName = substr(time(), 5) . sprintf('%u', crc32(uniqid())) . '.' . $ext;
$userDir = $options->plugin('AliOssForTypecho')->userDir;
$bucket_name = $options->plugin('AliOssForTypecho')->bucketName;
$end_point = ($options->plugin('AliOssForTypecho')->endPoint === "other") ?
$options->plugin('AliOssForTypecho')->otherEndPoint :
$options->plugin('AliOssForTypecho')->endPoint;
$access_id = $options->plugin('AliOssForTypecho')->accessId;
$access_key = $options->plugin('AliOssForTypecho')->accessKey;
$localFile = $path . $fileName;
$object_name = $userDir . $localFile;
if (isset($file['tmp_name']))
{
$content = file_get_contents($file['tmp_name']);
} else if (isset($file['bytes']))
{
$content = $file['bytes'];
} else
{
return FALSE;
}
$fileSize = strlen($content);
$ali_options = array(
'content' => $content,
'length' => $fileSize,
ALIOSS::OSS_HEADERS => array(
'Content-Encoding' => 'utf-8',
'Content-Language' => 'zh-CN',
),
);
$client = new ALIOSS($access_id, $access_key, $end_point);
$client->set_enable_domain_style(TRUE);
$ali_response = $client->upload_file_by_content($bucket_name, $object_name, $ali_options);
if (200 != $ali_response->status)
{
return FALSE;
} else
{
$object_url = $ali_response->header["_info"]["url"];
$ifLoaclSave = $options->plugin('AliOssForTypecho')->ifLoaclSave;
if ($ifLoaclSave === "1" && !Typecho_Common::isAppEngine())
{
$localPath = Typecho_Common::url(defined('__TYPECHO_UPLOAD_DIR__') ? __TYPECHO_UPLOAD_DIR__ : self::UPLOAD_DIR,
defined('__TYPECHO_UPLOAD_ROOT_DIR__') ? __TYPECHO_UPLOAD_ROOT_DIR__ : __TYPECHO_ROOT_DIR__)
. '/' . $path;
$mkdirSuccess = TRUE;
//创建上传目录
if (!is_dir($localPath))
{
if (!self::makeUploadDir($localPath))
{
$mkdirSuccess = FALSE;
}
}
$saveOnServerSuccess = FALSE;
//保存文件到服务器
if ($mkdirSuccess)
{
if (file_put_contents($localPath.$fileName, $content))
{
$saveOnServerSuccess = TRUE;
} else
{
$error = '错误:保存文件失败' . "\r\n" .
'远程文件:' . $object_url . "\r\n" .
'时间:' . date('Y-m-d h:i:sa') . "\r\n\r\n";
error_log($error, 3, $error_log_path . "error.log");
}
} else
{
$error = '错误:创建目录失败' . "\r\n" .
'创建路径:' . $localPath . "\r\n" .
'远程文件:' . $object_url . "\r\n" .
'时间:' . date('Y-m-d h:i:sa') . "\r\n\r\n";
error_log($error, 3, $error_log_path . "error.log");
}
}
}
$name = $file['name'];
//返回相对存储路径
return array(
'name' => $name,
'path' => $localFile,
'size' => $fileSize,
'type' => $ext,
'mime' => Typecho_Common::mimeContentType($localPath . $fileName)
);
}
/**
* 修改文件处理函数
*
* @access public
* @param array $content 老文件
* @param array $file 新上传的文件
* @return mixed
*/
public static function modifyHandle($content, $file)
{
if (empty($file['name'])) {
return false;
}
$ext = self::getSafeName($file['name']);
if ($content['attachment']->type != $ext) {
return false;
}
if (isset($file['tmp_name'])) {
$newContent = file_get_contents($file['tmp_name']);
} else if (isset($file['bytes'])) {
$newContent = $file['bytes'];
} else {
return false;
}
$options = Typecho_Widget::widget('Widget_Options');
$date = new Typecho_Date($options->gmtTime);
$path = $content['attachment']->path;
$userDir = $options->plugin('AliOssForTypecho')->userDir;
$bucket_name = $options->plugin('AliOssForTypecho')->bucketName;
$end_point = ($options->plugin('AliOssForTypecho')->endPoint === "other") ?
$options->plugin('AliOssForTypecho')->otherEndPoint :
$options->plugin('AliOssForTypecho')->endPoint;
$access_id = $options->plugin('AliOssForTypecho')->accessId;
$access_key = $options->plugin('AliOssForTypecho')->accessKey;
$object_name = $userDir . $path;
$fileSize = strlen($newContent);
$ali_options = array(
'content' => $newContent,
'length' => $fileSize,
ALIOSS::OSS_HEADERS => array(
'Content-Encoding' => 'utf-8',
'Content-Language' => 'zh-CN',
),
);
$client = new ALIOSS($access_id, $access_key, $end_point);
$client->set_enable_domain_style(TRUE);
$ali_response = $client->upload_file_by_content($bucket_name, $object_name, $ali_options);
if (200 != $ali_response->status)
{
return FALSE;
} else
{
$object_url = $ali_response->header["_info"]["url"];
$ifLoaclSave = $options->plugin('AliOssForTypecho')->ifLoaclSave;
if ($ifLoaclSave === "1" && !Typecho_Common::isAppEngine())
{
$localFile = Typecho_Common::url(self::UPLOAD_DIR . $path,
defined('__TYPECHO_UPLOAD_ROOT_DIR__') ? __TYPECHO_UPLOAD_ROOT_DIR__ : __TYPECHO_ROOT_DIR__);
$localPath = dirname($localFile);
$mkdirSuccess = TRUE;
//创建上传目录
if (!is_dir($localPath))
{
if (!self::makeUploadDir($localPath))
{
$mkdirSuccess = FALSE;
}
}
$saveOnServerSuccess = FALSE;
//保存文件到服务器
$error_log_path = self::log_path;
if ($mkdirSuccess)
{
$deleteLacalFileSuccess = unlink($localFile);
if (!$deleteLacalFileSuccess)
{
$error_log_path = self::log_path;
if (!is_dir($error_log_path))
{
self::makeUploadDir($error_log_path);
}
$error = '错误:删除文件失败导致无法修改文件' . "\r\n" .
'文件:' . $localFile . "\r\n" .
'远程文件:' . $object_url . "\r\n" .
'时间:' . date('Y-m-d h:i:sa') . "\r\n\r\n";
error_log($error, 3, $error_log_path . "error.log");
} else {
if (file_put_contents($localFile, $newContent))
{
$saveOnServerSuccess = TRUE;
} else
{
$error = '错误:保存文件失败' . "\r\n" .
'远程文件:' . $object_url . "\r\n" .
'时间:' . date('Y-m-d h:i:sa') . "\r\n\r\n";
error_log($error, 3, $error_log_path . "error.log");
}
}
} else
{
$error = '错误:创建目录失败' . "\r\n" .
'创建路径:' . $localPath . "\r\n" .
'远程文件:' . $object_url . "\r\n" .
'时间:' . date('Y-m-d h:i:sa') . "\r\n\r\n";
error_log($error, 3, $error_log_path . "error.log");
}
}
}
//返回相对存储路径
return array(
'name' => $content['attachment']->name,
'path' => $path,
'size' => $fileSize,
'type' => $content['attachment']->type,
'mime' => $content['attachment']->mime
);
}
/**
* 删除文件
*
* @access public
* @param array $content 文件相关信息
* @return string
*/
public static function deleteHandle(array $content)
{
$options = Typecho_Widget::widget('Widget_Options');
$userDir = $options->plugin('AliOssForTypecho')->userDir;
$access_id = $options->plugin('AliOssForTypecho')->accessId;
$access_key = $options->plugin('AliOssForTypecho')->accessKey;
$bucket_name = $options->plugin('AliOssForTypecho')->bucketName;
$end_point = ($options->plugin('AliOssForTypecho')->endPoint === "other") ?
$options->plugin('AliOssForTypecho')->otherEndPoint :
$options->plugin('AliOssForTypecho')->endPoint;
$ali_options = null;
$client = new ALIOSS($access_id, $access_key, $end_point);
$path = $content['attachment']->path;
$object_name = $userDir . $path;
$ali_response = $client->delete_object($bucket_name, $object_name, $ali_options);
$ifLoaclSave = $options->plugin('AliOssForTypecho')->ifLoaclSave;
if ($ifLoaclSave === "1" && !Typecho_Common::isAppEngine())
{
$localPath = Typecho_Common::url(defined('__TYPECHO_UPLOAD_DIR__') ? __TYPECHO_UPLOAD_DIR__ : self::UPLOAD_DIR,
defined('__TYPECHO_UPLOAD_ROOT_DIR__') ? __TYPECHO_UPLOAD_ROOT_DIR__ : __TYPECHO_ROOT_DIR__)
. $path;
$deleteLacalFileSuccess = unlink($localPath);
if (!$deleteLacalFileSuccess)
{
$error_log_path = self::log_path;
if (!is_dir($error_log_path))
{
self::makeUploadDir($error_log_path);
}
$error = '错误:删除文件失败' . "\r\n" .
'文件:' . $localPath . "\r\n" .
'时间:' . date('Y-m-d h:i:sa') . "\r\n\r\n";
error_log($error, 3, $error_log_path . "error.log");
}
}
return ($ali_response->status == 200);
}
/**
* 获取实际文件绝对访问路径
*
* @access public
* @param array $content 文件相关信息
* @return string
*/
public static function attachmentHandle(array $content)
{
$options = Typecho_Widget::widget('Widget_Options');
$cdnUrl = $options->plugin('AliOssForTypecho')->cdnUrl;
$userDir = $options->plugin('AliOssForTypecho')->userDir;
if ($cdnUrl == '')
{
$bucket_name = $options->plugin('AliOssForTypecho')->bucketName;
$end_point = ($options->plugin('AliOssForTypecho')->endPoint === "other") ?
$options->plugin('AliOssForTypecho')->otherEndPoint :
$options->plugin('AliOssForTypecho')->endPoint;
return 'http://' . $bucket_name . '.' . $end_point . '/' . $userDir . $content['attachment']->path;
} else
{
return 'http://' . $cdnUrl . '/' . $userDir . $content['attachment']->path;
}
}
/**
* 获取实际文件数据
*
* @access public
* @param array $content
* @return string
*/
public static function attachmentDataHandle(array $content)
{
$options = Typecho_Widget::widget('Widget_Options');
$cdnUrl = $options->plugin('AliOssForTypecho')->cdnUrl;
$userDir = $options->plugin('AliOssForTypecho')->userDir;
if ($cdnUrl == '')
{
$bucket_name = $options->plugin('AliOssForTypecho')->bucketName;
$end_point = ($options->plugin('AliOssForTypecho')->endPoint === "other") ?
$options->plugin('AliOssForTypecho')->otherEndPoint :
$options->plugin('AliOssForTypecho')->endPoint;
$filePath = 'http://' . $bucket_name . '.' . $end_point . $userDir . $content['attachment']->path;
} else
{
$filePath = 'http://' . $cdnUrl . $userDir . $content['attachment']->path;
}
return file_get_contents($filePath);
}
/**
* 检查文件名
*
* @access private
* @param string $ext 扩展名
* @return boolean
*/
private static function checkFileType($ext)
{
$options = Typecho_Widget::widget('Widget_Options');
return in_array($ext, $options->allowedAttachmentTypes);
}
/**
* 创建上传路径
*
* @access private
* @param string $path 路径
* @return boolean
*/
private static function makeUploadDir($path)
{
$path = preg_replace("/\\\+/", '/', $path);
$current = rtrim($path, '/');
$last = $current;
while (!is_dir($current) && false !== strpos($path, '/'))
{
$last = $current;
$current = dirname($current);
}
if ($last == $current)
{
return true;
}
if (!@mkdir($last))
{
return false;
}
$stat = @stat($last);
$perms = $stat['mode'] & 0007777;
@chmod($last, $perms);
return self::makeUploadDir($path);
}
/**
* 获取安全的文件名
*
* @param string $name
* @static
* @access private
* @return string
*/
private static function getSafeName(&$name)
{
$name = str_replace(array('"', '<', '>'), '', $name);
$name = str_replace('\\', '/', $name);
$name = false === strpos($name, '/') ? ('a' . $name) : str_replace('/', '/a', $name);
$info = pathinfo($name);
$name = substr($info['basename'], 1);
return isset($info['extension']) ? $info['extension'] : '';
}
}