fckeditor远程图片上传插件[For PHP][可上传QQ空间的图片][原创]

第1步:FCKConfig.Plugins.Add( 'RemoteUpload', 'en,zh-cn' ) ;
第2步:在ToolbarSets里面添加RemoteUpload;
第3步:建立RemoteUpload目录;
第4步:建立fckplugin.js文件:
FCKCommands.RegisterCommand( 'RemoteUpload'        , new FCKDialogCommand( FCKLang['DlgRemoteUploadTitle']    , FCKLang['DlgRemoteUploadTitle']        , FCKConfig.PluginsPath + 'RemoteUpload/remoteupload.htm'    , 500, 400 ) ) ;

var oRemoteUploadItem        = new FCKToolbarButton( 'RemoteUpload', FCKLang['DlgRemoteUploadTitle'] ) ;
oRemoteUploadItem.IconPath    = FCKConfig.PluginsPath + 'RemoteUpload/remoteupload.gif' ;

FCKToolbarItems.RegisterItem( 'RemoteUpload', oRemoteUploadItem ) ;

第5步:创建save.php:
<?php
error_reporting(0);
define('_DEBUG', 0);
function saveRemoteImage($url) {
    if(strlen($url) < 10){
        return '';
    }
    $arr_url  = parse_url($url);
    $stmp      = $arr_url['scheme'].$arr_url['host'].$arr_url['path'];

    $useragent= array(
                    "Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)",
                    'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)',
                    'Mozilla/5.0 (Windows; U; Windows NT 5.2; zh-CN; rv:1.9.2.16) Gecko/20110319 Firefox/3.6.16',
                    'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.3) Gecko/20070309 Firefox/2.0.0.3',
    );
    $refer      = array(
                    "$stmp",
                    "$url",
    );
    $r  = $refer[array_rand($refer)];
    $u  = $useragent[array_rand($useragent)];
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($ch, CURLOPT_USERAGENT, $u);
    curl_setopt($ch, CURLOPT_REFERER, $r);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    $output = curl_exec($ch);
    curl_close($ch);
    $filename = saveFile($output);
    if(_DEBUG){
        $t = file_get_contents('./a.txt');
        $content = "\n=======\n" . $r."\n".$u."\n".$filename."\n=========\n".$t ;
        file_put_contents('./a.txt', $content);
    }

    return $filename;
}
function checkImageType($filename){
    $_IMGTYPE = array(
                    'png' => 'image/png',
                    'jpeg'=> 'image/jpeg',
                    'jpg' => 'image/jpeg',
                    'gif' => 'image/gif',
    );
    if(file_exists($filename) && function_exists('getimagesize') && !getimagesize($filename)){
        unlink($filename);
    }
}

function saveFile($streamdata){
    if(empty($streamdata)) return '';
    $path = '../../../../uploadfile/'.date('Y');
    $path = str_ireplace('//', '/', $path);
    if(!is_dir($path)) mkdir($path, 0777);
    $name = date('Y-m-d_H-i-s').'_'.rand(1,9).'_.jpg';
    $filename = $path.'/'.$name;
    file_put_contents($filename, $streamdata);
    chmod($filename, 0777);
    checkImageType($filename);
    return '/uploadfile/'.date('Y').'/'.$name;
}

function checkReferer(){
    if(stripos($_SERVER['HTTP_REFERER'],'remoteupload.htm') === false){
        header('HTTP/1.1 404 Not Found');exit;
    }
}

//test();
function demo(){
    $url = 'http://olb.photo.qq.com/?file=9F8414022DC3ADD66268240B173E5EC3E21B8E8BE829E5C49B67B4EF1EE1590B';
    saveRemoteImage($url);
    exit;
}
function test(){
    header("Content-Type:text/xml;charset=utf-8");
    echo '<?xml version="1.0" encoding="utf-8"?><imgs><status total="1" curr="1" currfile="/uploadfile/2008/2008-07-23_18-34-49_6_.jpg"/><img src="http://b38.photo.store.qq.com/http_imgload.cgi?/rurl4_b=e6e6ffa5b1f80d3af1de87902832670b9ba4785cb222e83e02713616b989fb60864e31ca6cde49069fb5a7909d52215d907d5c14f8a84819930b3ece7b538b563d01d2e2fb9b726a00553a6f69ff4138cb26da16&amp;a=41&amp;b=38" drc="/uploadfile/2008/2008-07-23_18-34-49_6_.jpg"/></imgs>
';exit;
    echo '<?xml version="1.0" encoding="UTF-8"?><imgs><status total="12" curr="12" currfile="/uploadfile/2011/2011-06-24_03-17-03_3_.jpg"/><img src="http://olf.photo.qq.com/?file=81B8144DB6A22C403D16CF6DEE83FF715E3529932A4E546D558D35E343F75E15" drc="/uploadfile/2011/2011-06-24_03-16-52_5_.jpg"/><img src="http://olo.photo.qq.com/?file=86999FB8ABD1958122E265D3B7F1FC854D2A19ABAFE7DCCBBF2ADF7A0F790596" drc="/uploadfile/2011/2011-06-24_03-16-53_5_.jpg"/><img src="http://ol3.photo.qq.com/?file=6994F0A62042F6FE0BF7BE25B402DD7627B41EB733E52172B669FC3153280108" drc="/uploadfile/2011/2011-06-24_03-16-54_7_.jpg"/><img src="http://olp.photo.qq.com/?file=3F72221AE060D527FD391CCD4BE00344D882B3D96C8553C16CC9E0815E02ED98" drc="/uploadfile/2011/2011-06-24_03-16-55_8_.jpg"/><img src="http://olb.photo.qq.com/?file=D0FF8A98B52D79CEF1C58BD8B81954459A53EFADC05B4B3AFBB1592CDC7BEE9F" drc="/uploadfile/2011/2011-06-24_03-16-56_3_.jpg"/><img src="http://olw.photo.qq.com/?file=EB2A90CA8182038EB9D8608034ACE10FC1946210EF53E859BC52BDEAA17E6D74" drc="/uploadfile/2011/2011-06-24_03-16-57_8_.jpg"/><img src="http://old.photo.qq.com/?file=F8E394D797DF572992F5A5CABF9D1188FA5E3A96945BA94BF590A1C728EBE538" drc="/uploadfile/2011/2011-06-24_03-16-58_2_.jpg"/><img src="http://ol1.photo.qq.com/?file=8B8A76B7AF2928F7CB74393AD4BF898741BAB7D74D2CA63D73FA2717DDA16BE7" drc="/uploadfile/2011/2011-06-24_03-16-59_6_.jpg"/><img src="http://olw.photo.qq.com/?file=568BAD0A9F08CE1B9CBB70E9C3182A405C245402984548951C094DF085816DBC" drc="/uploadfile/2011/2011-06-24_03-17-00_4_.jpg"/><img src="http://ol4.photo.qq.com/?file=30C2E987921CB3A1D11D1CFE112AAFC95651FAE9FC29D1900B2F34E654661249" drc="/uploadfile/2011/2011-06-24_03-17-01_5_.jpg"/><img src="http://oli.photo.qq.com/?file=A3F21FA34B6313F52107E748FC8DB5222B599EC21D2AC6F004EF53F84471C598" drc="/uploadfile/2011/2011-06-24_03-17-02_4_.jpg"/><img src="http://olb.photo.qq.com/?file=9F8414022DC3ADD66268240B173E5EC3E21B8E8BE829E5C49B67B4EF1EE1590B" drc="/uploadfile/2011/2011-06-24_03-17-03_3_.jpg"/></imgs>';exit;
    echo '<?xml version="1.0" encoding="UTF-8"?><imgs><status total="1" curr="1" currfile="/uploadfile/2011/2011-06-23_12-48-41_4_.jpg"/><img src="http://g.crsky.com/uploadfiles/2011-02-9/2011-02-09_165227.gif" drc="/uploadfile/2011/2011-06-23_12-47-17_2_.jpg"/></imgs>';exit;
}


header("Content-Type:text/xml;charset=utf-8");

//checkReferer();
$postdata = file_get_contents("php://input");
if(empty($postdata)) exit('no data');

$xml = simplexml_load_string($postdata);
if(!$xml) {
    var_dump($xml);
    exit;
}
$status = $xml->xpath('/imgs/status');
$imgs   = $xml->xpath('/imgs/img');
$status[0]['curr'] = 0;
$kv     = array();
foreach($imgs as $k=>$img){
    $attrs = $img->attributes();
    $src   = $attrs['src'];
    $sTmp  = md5($src);
    if(array_key_exists($sTmp, $kv)){
        $drc = $kv[$sTmp];
    }else{
        $drc = saveRemoteImage($src);
        $kv[$sTmp] = $drc;
    }
    $img->addAttribute('drc',$drc);
    $status[0]['curr'] +=1;
    $status[0]['currfile'] = $drc;
}
echo $xml->asXML();
exit;
?>



第6步:创建remoteupload.htm文件:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
 <title></title>
 <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
 <meta content="noindex, nofollow" name="robots">
 <style type="text/css">
    body { margin: 0px;  background-color: buttonface;  }
    td { font-size: 11pt; font-family: Arial;text-align: left;}
    #domProgressBarId{
        width: 100%;height: 15px;border-right: buttonhighlight 1px solid; border-top: buttonshadow 1px solid; border-left: buttonshadow 1px solid;  border-bottom: buttonhighlight 1px solid;  background: #b7d2ec url(loading.gif) center no-repeat;text-align: center;color:#fff;
    }
    #Uploading{
    width:300px;height:20px;position:absolute;    top:0;    left:50%;    margin-left:-150px;    text-align:center;    display:none;
    }
</style>

<script type="text/javascript" language="javascript">
arrRemoteImage = [];

__ISIE      = /msie/i.test(navigator.userAgent);
__ISFF      = /firefox/i.test(navigator.userAgent);

window.parent.SetOkButton( false ) ;
function $(element){
  if (arguments.length>1){
    for (var i=0, elements=[], length=arguments.length; i<length; i++)
      elements.push($(arguments[i]));
    return elements;
  }
  if (typeof element =='string') element=document.getElementById(element);
  return element;
}

var oEditor = window.parent.InnerDialogLoaded() ;

function OnLoad()    {
    oEditor.FCKLanguageManager.TranslatePage( document ) ;

    var innerTxt="";
    getRemoteImage();
    if (arrRemoteImage.length>0)    {
        var remoteList = new Array();
        remoteList       = arrRemoteImage;
        for (var k=0; k<remoteList.length; k++)    {
            if(!(typeof remoteList[k] == "undefined"))
            innerTxt += (k+1)+"<input name=\"imgs\" disabled=disabled type=\"checkbox\" value=\""+remoteList[k]+"\""+(IsRemotePic(remoteList[k])?" checked":"")+" onclick=\"btnStat()\" />"+remoteList[k]+"<br />";
        }
    }else{
        innerTxt+="没有找到图片资料";$("btnSaveRemote").disabled=true;
    }
    $("Anylysis").innerHTML = innerTxt;
    btnStat();
}
function IsRemotePic(ss){
    if(typeof ss=="undefined" || ss==null) return false;
    var local=window.location.protocol+"//"+window.location.host;
    if(ss.substr(0,local.length) != local){
        return true;
    }else{
        return false;
    }
}

function getRemoteImage(){
    var _fckcontent = oEditor.FCK.EditorWindow.document.body.innerHTML;
    var pattern        = /<img.*?src=['"]?(http:\/\/.*?)(?=['"]|\s|>)/gi;
    var mts;
    while (mts = pattern.exec(_fckcontent)){
        if (mts != null){
            //alert(mts[1]);
            arrRemoteImage.push(mts[1]);
        }
    }
}

function btnStat(){
    $('btnSaveRemote').disabled =    (arrRemoteImage.length ==0) ;
    $("domAllFilesCount").innerHTML= arrRemoteImage.length;
}

function Ok(){
    if ( document.getElementsByName('imgs').length == 0 ) return ;
    $("Uploading").style.display="block";
    $("btnSaveRemote").disabled=true;
    var imgs=document.getElementsByName("imgs");

    if(__ISIE){
        var xmlDoc = new ActiveXObject("msxml2.FreeThreadedDOMDocument");
        var p=xmlDoc.createProcessingInstruction("xml","version='1.0' encoding='utf-8'");
        xmlDoc.appendChild(p);

        var root=xmlDoc.createNode(1,"imgs","");

        var status=xmlDoc.createNode(1,"status","");

        var total=xmlDoc.createAttribute("total");
        total.value=imgs.length ;
        status.setAttributeNode(total);
        var curr=xmlDoc.createAttribute("curr");
        curr.value="";
        status.setAttributeNode(curr);
        var currfile=xmlDoc.createAttribute("currfile");
        currfile.value="";
        status.setAttributeNode(currfile);

        root.appendChild(status);
        for(var i=0;i<imgs.length;i++){
            if(imgs[i].checked==1){
                var n=xmlDoc.createNode(1,"img","");
                var r=xmlDoc.createAttribute("src");
                r.value=imgs[i].value;
                n.setAttributeNode(r);
                root.appendChild(n);
            }
        }
        xmlDoc.appendChild(root);
        //alert(xmlDoc.xml);
    }else{
        var text = '<?xml version="1.0" encoding="utf-8" ?><imgs></imgs>';
        var parser = new DOMParser();
        xmlDoc = parser.parseFromString(text, "text/xml");

        //var root = xmlDoc.createElement("imgs");
        var root = xmlDoc.getElementsByTagName('imgs')[0];
        var status = xmlDoc.createElement("status");
        var total=xmlDoc.createAttribute("total");
        total.value=imgs.length;
        status.setAttributeNode(total);

        var curr=xmlDoc.createAttribute("curr");
        curr.value="0";
        status.setAttributeNode(curr);

        var currfile=xmlDoc.createAttribute("currfile");
        currfile.value="";
        status.setAttributeNode(currfile);

        root.appendChild(status);

        for(var i=0;i<imgs.length;i++){
            if(imgs[i].checked==1){
                var n=xmlDoc.createElement("img");
                var r=xmlDoc.createAttribute("src");
                r.value=imgs[i].value;
                n.setAttributeNode(r);
                root.appendChild(n);
            }
        }
        var serializer = new XMLSerializer();
        xmlDoc = serializer.serializeToString(xmlDoc);
        //alert(xmlDoc);
    }
    var myAjax=new Ajax();
    var url="save.php"
    if(myAjax.Create(true)){
          myAjax.Send(url, $("data"), $("domProgressBarId"), xmlDoc);
    }
}
function Ajax(){
var XmlHttp = null;
var DataObject = null;//数据接收对象
var LoadingBar = null;//状态显示对象
var LoadingMax = 100;//进度条最大值
var LoadingWidth = null;//保存宽度,还原初始属性
var LoadingTimer = 10;//刷新时间
var LoadingTimerID = null;//时间ID
var FinishTimer = 10;//完成停留时间,等候进度条完成
var FinishTimerID = null;//时间ID
var HttpState = 0;
var CanFree = false;//释放
this.Create = function(free){
   try{
    if(free)CanFree = true;
    if(__ISIE){
     try{
            XmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
     }catch(e){
      XmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
     }
        }else{
           XmlHttp=new XMLHttpRequest();
        }
     return true;
   }catch(e2){
    return false;
   }
}
this.Send = function(url, obj1, obj2, data){
    try{
        DataObject = obj1;
        LoadingBar = obj2;
        if(LoadingBar){
            LoadingMax = LoadingBar.offsetWidth;//保存可见宽度
            LoadingWidth = LoadingBar.style.width;//可能会没有设置宽度,这时数据为空
            LoadingBar.style.width = "0px";
            LoadingBar.innerHTML = "0%";
            LoadingBar.style.display = "";
            DataObject.style.display = "none";
            HttpState = 0;
            if(LoadingTimerID)clearInterval(LoadingTimerID);//清空时钟
            LoadingTimerID = setInterval(this.StatusBar, LoadingTimer);
        }
        XmlHttp.open("POST", url, false);//ff只能在false下工作
        XmlHttp.setRequestHeader('Content-Type', 'text/xml');
        XmlHttp.send(data);
        this.StateChange();
        return true;
    }catch(e){
        //return false;
    }
}
this.Finish = function(){
    if(FinishTimerID)clearInterval(FinishTimerID);//清空时钟
    var old=oEditor.FCK.EditorWindow.document.body.innerHTML;
    if(__ISIE){
        var items=XmlHttp.responseXML.selectNodes("//imgs/img");
        for (var i=0; i<items.length; i++){
            //var ss=items[i].attributes[0].nodeValue;
            var ss=items[i].attributes[0].xml;
            ss = ss.substr(5, ss.length - 6);

            var dd=items[i].attributes[1].nodeValue;
            ss=ss.replace(/\s+$/gi,"");
            ss=ss.replace(/\:/gi,"\\:");
            ss=ss.replace(/\//gi,"\\/");
            ss=ss.replace(/\./gi,"\\.");
            ss=ss.replace(/\+/gi,"\\+");
            ss=ss.replace(/\*/gi,"\\*");
            ss=ss.replace(/\?/gi,"\\?");

            if(ss.indexOf('qq.com') != -1) ss=ss.replace(/\&/gi,"&amp;");
            var re=new RegExp(ss,"gi");
            old=old.replace(re,dd);
        }
        oEditor.FCK.EditorWindow.document.body.innerHTML=old;
        var status=XmlHttp.responseXML.selectSingleNode("//imgs/status");
        if(status!=null){
            var curr=status.selectSingleNode("./@curr");
            var currfile=status.selectSingleNode("./@currfile");
            $("domAlreadyDownloadFilesCount").innerHTML=curr.nodeValue;
            $("domCurrentFile").innerHTML=currfile.nodeValue;
        }
    }else{
        var xmlimgs = XmlHttp.responseXML.getElementsByTagName("imgs")[0];
        var items=xmlimgs.getElementsByTagName('img');
        for (var i=0; i<items.length; i++){
            var ss=items[i].getAttribute('src');
            var dd=items[i].getAttribute('drc');
            ss=ss.replace(/\s+$/gi,"");
            ss=ss.replace(/\:/gi,"\\:");
            ss=ss.replace(/\//gi,"\\/");
            ss=ss.replace(/\./gi,"\\.");
            ss=ss.replace(/\+/gi,"\\+");
            ss=ss.replace(/\*/gi,"\\*");
            ss=ss.replace(/\?/gi,"\\?");

            ss=ss.replace(/\&/gi,"&amp;");
            var re=new RegExp(ss,"gi");
            old=old.replace(re,dd);

        }
        oEditor.FCK.EditorWindow.document.body.innerHTML=old;
        var status=xmlimgs.getElementsByTagName('status')[0];
        if(status!=null){
            var curr=status.getAttribute("curr");
            var currfile=status.getAttribute("currfile");
            $("domAlreadyDownloadFilesCount").innerHTML=curr;
            $("domCurrentFile").innerHTML=currfile;
        }
    }
    $("Uploading").style.display="none";
    if(CanFree)this.Destroy;
}

this.StateChange = function(){
    if(XmlHttp.readyState)HttpState = XmlHttp.readyState;
    if (XmlHttp.readyState == 4) {
        if(LoadingTimerID)clearInterval(LoadingTimerID);//清空时钟
        if(LoadingBar){
            LoadingBar.style.width = LoadingWidth;
            LoadingBar.innerHTML = "100%";
            if(FinishTimerID)clearInterval(FinishTimerID);//清空时钟
            FinishTimerID = setInterval(this.Finish, FinishTimer);
        }else{
            //DataObject.innerHTML = XmlHttp.responseText;
            if(CanFree)this.Destroy;
        }
    }
}
this.StatusBar = function(){
    try{
        if(LoadingBar.offsetWidth >= LoadingMax){
            LoadingBar.innerHTML = "100%";
            LoadingBar.style.width = LoadingWidth;
            return;//返回
        }

        if(LoadingBar.offsetWidth < (HttpState + 1) * Math.floor(LoadingMax / 4)){
            var loading = LoadingBar.offsetWidth + Math.floor(LoadingMax / 40);//十分之一
            LoadingBar.style.width = loading + "px";
            var percen = Math.floor(loading / LoadingMax * 100);
            LoadingBar.innerHTML = (percen>100?100:percen) + "%";
        }else{
            LoadingBar.style.width = (HttpState + 1) * Math.floor(LoadingMax / 4) + "px";
            LoadingBar.innerHTML = Math.floor(100 / (4 - HttpState)) + "%";
        }
    }catch(e){}
}
this.Destroy = function(){
   if(LoadingTimerID)clearInterval(LoadingTimerID);//清空时钟
   if(FinishTimerID)clearInterval(FinishTimerID);//清空时钟
   XmlHttp = null;
}
}
</script>

</head>
<body onload="OnLoad()">
<div id="Uploading"><span fckLang="DlgRemoteUploading"></span><marquee style="border:1px solid #000000" direction="right" width="200" scrollamount="5" scrolldelay="10" bgcolor="#ECF2FF">
  <table cellspacing="1" cellpadding="0">
  <tr height=8>
  <td bgcolor=#3399FF width=8></td>
  <td></td>
  <td bgcolor=#3399FF width=8></td>
  <td></td>
  <td bgcolor=#3399FF width=8></td>
  <td></td>
  <td bgcolor=#3399FF width=8></td>
  <td></td>
  </tr></table></marquee></div>
    <form id="RemoteUPloadForm">
        <div style="padding-left: 10px;">
            <table border="0" cellspacing="0" cellpadding="2">
                <tr>
                    <td nowrap="nowrap">
                        <label fckLang="DlgRemoteUploadCurrFile">Current Files</label>:&nbsp;<span id="domCurrentFile" style="display: inline; text-overflow: ellipsis"></span></td>
                </tr>
                <tr>
                    <td style="text-align: left; width:500px;">
                        <div id="domProgressBarId"></div><div id="data"></div>
                    </td>
                </tr>
                <tr>
                    <td nowrap="nowrap">
                        <label fckLang="DlgRemoteUploadTotal">Total</label>:&nbsp;<span id="domAllFilesCount"></span>&nbsp;&nbsp;<label fckLang="DlgRemoteUploadUnit">Unit</label></td>
                </tr>
                <tr>
                    <td nowrap="nowrap">
                        <label fckLang="DlgRemoteUploadDownloaded">Downloaded</label>:&nbsp;<span id="domAlreadyDownloadFilesCount">0</span>&nbsp;&nbsp;<label fckLang="DlgRemoteUploadUnit">Unit</label>。</td>
                </tr>
                <tr>
                    <td><div id="Anylysis"><span fckLang="DlgRemoteUploadAnalysis">Analysis...</span></div></td>
                </tr>
                <tr>
                    <td><input id="btnSaveRemote" style="padding-right: 5px; padding-left: 5px" onclick="Ok();return false;" type="submit" value="Save Remote Pics" fcklang="DlgRemoteUploadBtn" /></td>
                </tr>
                </label>
            </table>
        </div>
    </form>
</body>
</html>


第7步:创建lang目录并在目录里创建zh-cn.js文件:
FCKLang['DlgRemoteUploadTitle']            = '保存远程图片' ;
FCKLang['DlgRemoteUploadBtn']            = '保存远程图片' ;
FCKLang['DlgRemoteUploadCurrFile']        = '当前文件' ;
FCKLang['DlgRemoteUploadTotal']            = '共有' ;
FCKLang['DlgRemoteUploadUnit']            = '个文件' ;
FCKLang['DlgRemoteUploadDownloaded']    = '已下载' ;
FCKLang['DlgRemoteUploadAnalysis']        = '正在分析中...' ;
FCKLang['DlgRemoteUploading']            = "文件正在上传处理中.请耐心等待...";

300*300
 文章首页关于迷茫时代关于我写意人生
版权所有:迷茫时代 All rights reserved   
执行时间:0.00624 秒