Ejemplo n.º 1
0
 /**
  * 构造函数
  * @param array $files 要处理的图片列表
  */
 public function __construct(array $files = array())
 {
     //名称生成方式
     $this->namecall = function ($name) {
         return 'Other/' . $name . '-' . md5($name);
     };
     //设置文件信息
     foreach ($files as $key => $file) {
         //写入临时文件获取文件名
         $f = new \SaeFetchurl();
         $filename = tempnam(SAE_TMP_PATH, "SAE_IMAGE");
         $data = $f->fetch(str_replace(' ', '%20', $file));
         if (!file_put_contents($filename, $data)) {
             continue;
         }
         //取得文件的大小信息
         if (false !== ($this->infos[$file] = getimagesize($filename))) {
             //取得扩展名
             //支持格式 see http://www.php.net/manual/zh/function.exif-imagetype.php
             $this->infos[$file]['ext'] = image_type_to_extension(exif_imagetype($filename), 0);
             $this->infos[$file]['data'] = $data;
             //如果不在允许的图片类型范围内
             if (!in_array($this->infos[$file]['ext'], $this->exts)) {
                 unset($this->infos[$file]);
             }
         } else {
             //如果获取信息失败则取消设置
             unset($this->infos[$file]);
         }
     }
 }
 function fetch_data_by_url($url)
 {
     $f = new SaeFetchurl();
     $ret = $f->fetch($url);
     if ($ret === false) {
         return FALSE;
     }
     return $ret;
 }
Ejemplo n.º 3
0
 public static function fetch_url($url)
 {
     switch (RUN_ENV) {
         case 'SAE':
             //使用SAE FetchURL服务
             $f = new SaeFetchurl();
             if (STATIC_HOST) {
                 $f->setHeader('Host', STATIC_HOST);
             }
             $content = $f->fetch($url);
             return array($f->HttpCode(), $content);
             break;
         case 'BAE':
         case 'LOCAL':
         default:
             if (function_exists('curl_init')) {
                 //BAE或普通平台下可使用curl
                 $ch = curl_init();
                 curl_setopt($ch, CURLOPT_URL, $url);
                 curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
                 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
                 curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
                 if (!ini_get('safe_mode')) {
                     curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
                 }
                 if (STATIC_HOST) {
                     curl_setopt($ch, CURLOPT_HTTPHEADER, array('Host: ' . STATIC_HOST));
                 }
                 $con = curl_exec($ch);
                 $cod = curl_getinfo($ch, CURLINFO_HTTP_CODE);
                 return array($cod, $con);
             } else {
                 //否则使用file_get_contents
                 $content = '';
                 if (STATIC_HOST) {
                     $opt = array('http' => array('header' => 'Host: ' . STATIC_HOST));
                     $context = stream_context_create($opt);
                     $content = file_get_contents($url, false, $context);
                 } else {
                     $content = file_get_contents($url);
                 }
                 list($version, $status_code, $msg) = explode(' ', $http_response_header[0], 3);
                 return array($status_code, $content);
             }
     }
 }
Ejemplo n.º 4
0
function getName($stuID, $pwd)
{
    $f = new SaeFetchurl();
    $f->setMethod('post');
    $logindata['IPT_LOGINUSERNAME'] = $stuID;
    $logindata['IPT_LOGINPASSWORD'] = $pwd;
    $f->setPostData($logindata);
    $f->setAllowRedirect(false);
    $f->fetch('http://222.30.60.9/meol/homepage/common/login.jsp');
    if ($f->errno()) {
        $cookies = $f->responseCookies(false);
        $f->setCookies($cookies);
        $content = $f->fetch('http://222.30.60.9/meol/welcomepage/student/index.jsp');
        $name = substr($content, strlen('<li>' . '   ') + strpos($content, '<li>') + 3, (strlen($content) - strpos($content, '</li>')) * -1);
        return iconv('GBK', 'UTF-8//IGNORE', $name);
    } else {
        return false;
    }
}
Ejemplo n.º 5
0
<?php

error_reporting(E_ALL & ~E_DEPRECATED & ~E_NOTICE);
header('Content-Type: text/html; charset=utf-8');
$appdir = dirname(__FILE__);
require $appdir . '/wechat-api.php';
$mysql = new SaeMysql();
$s = new SaeStorage();
$f = new SaeFetchurl();
if (W::isPOST()) {
    $post = $GLOBALS["HTTP_RAW_POST_DATA"];
    $xml = simplexml_load_string($post, 'SimpleXMLElement', LIBXML_NOCDATA);
    $content = trim($xml->Content);
    $type = strtolower($xml->MsgType);
    $openid = $xml->FromUserName;
    $web = 'http://mmbiz.qpic.cn/mmbiz/';
    $mp = 'http://mp.weixin.qq.com/s';
    $xiaoU = array(array('title' => 'Uri', 'cover' => $web . 'icv3Y2jicj1r5zVuHbibOR7ztYtd6tl8zShn0ibKxLCavToicWMuQ8iaJ9wiaK5AqB19KdDOvGXvPQibKfnFABtWIVpwtQ/0?wxfrom=5', 'link' => $mp . '?__biz=MzA3MjAzMTgyMA==&mid=10000058&idx=1&sn=93bf84e650d4df87196988b342b65644#rd'), array('title' => '功能介绍', 'cover' => $web . 'icv3Y2jicj1r5zVuHbibOR7ztYtd6tl8zShXae61cDyL3FDfgB2CEsXyI4lqDXyUyqwGIvWjjKm0jlOy3fCfhPibuQ/0?wxfrom=5', 'link' => $mp . '?__biz=MzA3MjAzMTgyMA==&mid=10000058&idx=2&sn=aa817cfb12b9117cb518d4ab268d28b9#rd'), array('title' => '任务进度', 'cover' => $web . 'icv3Y2jicj1r5zVuHbibOR7ztYtd6tl8zShbfNUxPaicSwXY3daHy1BVbxpx7CEjym1VicU4b3T6dSd6XIjiaRE0lRkA/0?wxfrom=5', 'link' => $mp . '?__biz=MzA3MjAzMTgyMA==&mid=10000058&idx=3&sn=5edb8953ca274271a239626c434df4a2#rd'), array('title' => '联系我们', 'cover' => $web . 'icv3Y2jicj1r5zVuHbibOR7ztYtd6tl8zShO7B8lIEN05Niao9CnJGYsFFviayfqRyOrPGj5JwfGa8zmDYEf1S2DVaA/0?wxfrom=5', 'link' => $mp . '?__biz=MzA3MjAzMTgyMA==&mid=10000058&idx=4&sn=a7d37be0a672e5c2085330799836992b#rd'));
    $biaoqing = array('/::)', '/::~', '/::B', '/::|', '/:8-)', '/::<', '/::$', '/::X', '/::Z', '/::\'(', '/::-|', '/::@', '/::P', '/::D', '/::O', '/::(', '/::+', '/:--b', '/::Q', '/::T', '/:,@P', '/:,@-D', '/::d', '/:,@o', '/::g', '/:|-)', '/::!', '/::L', '/::>', '/::,@', '/:,@f', '/::-S', '/:?', '/:,@x', '/:,@@', '/::8', '/:,@!', '/:!!!', '/:xx', '/:bye', '/:wipe', '/:dig', '/:handclap', '/:&-(', '/:B-)', '/:<@', '/:@>', '/::-O', '/:>-|', '/:P-(', '/::\'|', '/:X-)', '/::*', '/:@x', '/:8*');
    $ghost = array('短篇鬼故事' => 1, '长篇鬼故事' => 2, '校园鬼故事' => 3, '医院鬼故事' => 4, '家里鬼故事' => 5, '民间鬼故事' => 6, '灵异事件' => 7, '听鬼故事' => 10, '中国灵异' => 25, '灵异知识库' => 26, '推理小说' => 46);
    $help = '这是目前小u有的功能:' . "\n" . '-----------------' . "\n" . '[小u]' . "\n" . ':查看小u的基本信息,以及功能介绍和近期更新' . "\n" . '-----------------' . "\n" . '[帮助]' . "\n" . ':查看使用帮助' . "\n" . '-----------------' . "\n" . '[查水表]' . "\n" . ':查询寝室的水电费(华科)' . "\n" . '-----------------' . "\n" . '[每日一句]' . "\n" . ':每天更新一句英语,中英对照' . "\n" . '-----------------' . "\n" . '[点歌]' . "\n" . ':小u每天会为大家推荐好的歌曲,希望大家喜欢。如果想给某人点歌的话,可以直接跟我说哦' . "\n" . '-----------------' . "\n" . '[笑话]' . "\n" . ':郁闷时看看笑话吧,小u这里有好多笑话等着你呢' . "\n" . '-----------------' . "\n" . '[新闻]' . "\n" . ':没事的时候大家多看看新闻吧,小u不懈的为你奉送中' . "\n" . '-----------------' . "\n" . '[彩票]' . "\n" . ':每天的彩票信息一目了然' . "\n" . '-----------------' . "\n" . '翻译' . "\n" . ':发送"#+你要翻译的内容",即可收到详细结果,例如:#doofus' . "\n" . '-----------------' . "\n" . '天气+找小u' . "\n" . ':点击下面的“+”,发送你的的位置信息,即可收到本地的天气预报,并且看到你和小u的距离哟。' . "\n" . '-----------------' . "\n" . 'bing搜索' . "\n" . ':发送"%+你要搜索的内容",即可收到详细结果,例如:%dweeb' . "\n" . '-----------------' . "\n" . '维基百科' . "\n" . ':发送"&+你要搜索的内容",小u会根据你的输入自动判断查询中文维基或是英文,(*^__^*) 嘻嘻。例如:&spaz' . "\n" . '-----------------' . "\n" . '二维码' . "\n" . ':发送"*+你要生成的内容",小u会返回生成的二维码。例如:*嘟嘟噜' . "\n" . '-----------------';
    $help .= "\n" . '豆瓣' . "\n" . '1.书' . "\n" . ' bs:关键字 搜索相关的书籍' . "\n" . ' b:书名 查看详细内容' . "\n" . '2.音乐' . "\n" . ' ms:关键字 搜索相关的音乐' . "\n" . ' m:音乐名 查看详细内容' . "\n" . '3.电影' . "\n" . ' vs:关键字 搜索相关的电影' . "\n" . ' v:电影名 查看详细内容' . "\n" . '-----------------';
    $help .= "\n" . '动态' . "\n" . ':发送":+你要分享的文字"即可,大家可以回复[动态]查看,都可以看到哦。例如 :这是我发的第一个说说' . "\n" . '-----------------';
    $help .= "\n" . '美女识别' . "\n" . ':上传图片,看看小u的眼力吧' . "\n" . '-----------------' . "\n" . '周公解梦' . "\n" . ':发送"梦到xxx",小u来预测吉凶,例如"梦到小u"' . "\n" . '-----------------' . "\n" . '手机号码查询' . "\n" . ':直接发送手机号' . "\n" . '-----------------';
    $help .= "\n" . '[鬼故事]' . "\n" . ':小u精心为你准备的鬼故事哟,超吓人的说,午夜凌晨看一看好阔怕。。' . "\n" . '-----------------' . "\n" . '[短篇鬼故事]' . "\n" . ':让喜欢鬼故事的读者在这里快速感受到不一样的诡异,篇幅较短,适合想快速阅读完鬼故事的朋友' . "\n" . '-----------------' . "\n" . '[长篇鬼故事]' . "\n" . ':篇幅较长,情节曲折,剧情跌宕起伏,一个好的长篇鬼故事,就是一次刺激的心灵旅行' . "\n" . '-----------------' . "\n" . '[校园鬼故事]' . "\n" . ':这里的鬼故事都与校园有关或者是发生在学校里的鬼故事,让喜爱鬼故事的读者了解更多的校园鬼故事' . "\n" . '-----------------' . "\n" . '[医院鬼故事]' . "\n" . ':我们在恐怖鬼片里也常见到发生在医院里的鬼故事事件,但有更多的鬼故事等待你去发现,一起来看医院鬼故事吧' . "\n" . '-----------------' . "\n" . '[家里鬼故事]' . "\n" . ':发生在家里的鬼故事比较多,快来看看都有哪些恐怖的家里鬼故事吧' . "\n" . '-----------------';
    $help .= "\n" . '[民间鬼故事]' . "\n" . ':中国民间鬼故事来源于古代的传奇小说,和现代的民间流传奇闻中。同时鬼故事网也搜集了国外吸血鬼的故事,欢迎大家阅读民间鬼故事' . "\n" . '-----------------' . "\n" . '[灵异事件]' . "\n" . ':灵异事件在世界各地每个角落经常发生,你身边是否也有灵异事件呢?灵异事件频道最全面的记录最新真实灵异事件,中国灵异事件,国外灵异事件,灵异鬼故事大全,带你进入灵异鬼故事的世界' . "\n" . '-----------------' . "\n" . '[中国灵异]' . "\n" . ':整理最全的中国真实灵异事件大全,将会带您走入从古到今发生在中国的灵异事件' . "\n" . '-----------------' . "\n" . '[灵异知识库]' . "\n" . ':灵异知识大全,例如如何避鬼,招鬼,阵法、鬼魂禁忌等等详细内容' . "\n" . '-----------------';
    $help .= "\n" . '[推理小说]' . "\n" . ':内容涵盖惊悚、悬疑、侦探、武侠等,一切以推理为出发点,挑战思维极限,考验缜密的逻辑。风格:先锋、酷炫、丰富多彩、可读性强。杂志力推原创,名家新秀携手亮相,联手打造包罗万象,令人耳目一新、心驰神往的异度空间' . "\n" . '-----------------' . "\n" . '[听鬼故事]' . "\n" . ':张震讲鬼故事,吓死你不偿命' . "\n" . '-----------------';
    $help .= "\n" . '#[xx]内的内容xx是指你发送给小u的';
    // 接收位置
    if ($type == 'location') {
        $uriID = 'oTHwbt_9H0QVjJn8AdI-fmkHdKgM';
Ejemplo n.º 6
0
function Douban($username, $subject, $apikey)
{
    if ($apikey == "") {
        $apikey = '064e10081295144112ea301837bf3cc3';
    }
    $douban = 'http://api.douban.com/people/' . $username . '/collection?cat=' . $subject . '&apikey=' . $apikey;
    $f = new SaeFetchurl();
    $content = $f->fetch($douban);
    $feed = simplexml_load_file($content);
    $children = $feed->children('http://www.w3.org/2005/Atom');
    $a = $children->entry->children('http://www.w3.org/2005/Atom')->xpath('//db:subject');
    echo '<ul>';
    foreach ($a as $d) {
        echo '<li>' . $d->title . '</li>';
    }
    echo '</ul>';
}
Ejemplo n.º 7
0
 protected function sendAndReceive($request)
 {
     $f = new SaeFetchurl();
     $cookie = $this->getCookie();
     if ($cookie != '') {
         $f->setHeader("Cookie", $cookie);
     }
     if ($this->keepAlive) {
         $f->setHeader("Connection", "keep-alive");
         $f->setHeader("Keep-Alive", $this->keepAliveTimeout);
     } else {
         $f->setHeader("Connection", "close");
     }
     foreach ($this->header as $name => $value) {
         $f->setHeader($name, $value);
     }
     $f->setMethod("post");
     $f->setPostData($request);
     $f->setConnectTimeout($this->timeout);
     $f->setSendTimeout($this->timeout);
     $f->setReadTimeout($this->timeout);
     $response = $f->fetch($this->url);
     if ($f->errno()) {
         throw new Exception($f->errno() . ": " . $f->errmsg());
     }
     $http_response_header = $f->responseHeaders(false);
     $this->setCookie($http_response_header);
     return $response;
 }
Ejemplo n.º 8
0
 public function responseMsg()
 {
     //get post data, May be due to the different environments
     $postStr = $GLOBALS["HTTP_RAW_POST_DATA"];
     //extract post data
     if (!empty($postStr)) {
         /* libxml_disable_entity_loader is to prevent XML eXternal Entity Injection,
            the best way is to check the validity of xml by yourself */
         libxml_disable_entity_loader(true);
         $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
         $fromUsername = $postObj->FromUserName;
         $toUsername = $postObj->ToUserName;
         $keyword = trim($postObj->Content);
         $time = time();
         //消息类型
         $form_MsgType = $postObj->MsgType;
         //文字消息模板
         $textTpl = "<xml>\n\t\t\t\t\t\t\t<ToUserName><![CDATA[%s]]></ToUserName>\n\t\t\t\t\t\t\t<FromUserName><![CDATA[%s]]></FromUserName>\n\t\t\t\t\t\t\t<CreateTime>%s</CreateTime>\n\t\t\t\t\t\t\t<MsgType><![CDATA[%s]]></MsgType>\n\t\t\t\t\t\t\t<Content><![CDATA[%s]]></Content>\n\t\t\t\t\t\t\t<FuncFlag>0</FuncFlag>\n\t\t\t\t\t\t\t</xml>";
         //事件消息
         if ($form_MsgType == "event") {
             //获取某一特定事件,这里是订阅事件
             $form_event = $postObj->Event;
             //如果是订阅事件
             if ($form_event == "subscribe") {
                 //回复欢迎文字消息
                 $msgType = "text";
                 $contentStr = "感谢您关注江大计算机考研![愉快]\n回复数据结构可以获得数据结构有关资料\n回复复试可以获得复试资料\n回复导师可以查看导师信息\n发送位置信息可以获取天气预报\n还可以给我发图片\n有意见可以回复我哦\n平台建设中请见谅![玫瑰]\n by XiJiaxiang";
                 $resultStr = sprintf($textTpl, $fromUsername, $toUsername, time(), $msgType, $contentStr);
                 echo $resultStr;
                 exit;
             }
         }
         //非文字消息,这里是图片消息
         if ($form_MsgType == "image") {
             //获取图片url
             $from_PicUrl = $postObj->PicUrl;
             //创建图片名称
             $filename = $fromUsername . date("YmdHis") . ".jpg";
             //抓取的图片类, 新浪云平台提供
             $saefetch = new SaeFetchurl();
             //抓取图片
             $PicResource = $saefetch->fetch($from_PicUrl);
             //没有错误
             if ($saefetch->errno() == 0) {
                 //use sinacloud\sae\Storage as Storage;
                 //使用全局变量global 新浪Storage提供。
                 global $storage;
                 $storage = new Storage();
                 //写入图片,第一个参数是文件,第二个是bucket(新浪方面)。第三个存储路径
                 $storage->putObject($PicResource, "********", "wexinPic/" . $filename);
                 //提示上传成功,返回消息给用户
                 $msgType = "text";
                 $resultStr = sprintf($textTpl, $fromUsername, $toUsername, time(), $msgType, "收到图片了哦");
                 echo $resultStr;
                 exit;
             } else {
                 //提示失败
                 $msgType = "text";
                 $resultStr = sprintf($textTpl, $fromUsername, $toUsername, time(), $msgType, "图片上传失败");
                 echo $resultStr;
                 exit;
             }
         }
         //非文字消息,这里是地理位置信息
         if ($form_MsgType == "location") {
             $from_Location_X = $postObj->Location_X;
             //经度
             echo $from_Location_X;
             $from_Location_Y = $postObj->Location_Y;
             //纬度
             echo $from_Location_Y;
             $from_Location_Scale = $postObj->Scale;
             //地图缩放信息
             $from_Location_Label = $postObj->Label;
             //地址信息
             //使用百度地图api解析地址
             //example //http://api.map.baidu.com/geocoder/v2/?ak=E4805d16520de693a3fe707cdc962045&callback=renderReverse&location=39.983424,1//16.322987&output=json&pois=1
             $map_api_url = "http://api.map.baidu.com/geocoder/v2/?";
             //坐标类型
             $map_coord_type = "coordtype=wgs84ll";
             $ak = "ak=****************************";
             //建立抓取对象
             $fetch = new SaeFetchurl();
             //抓取返回的xml文件,也可以利用json
             $geocoder = $fetch->fetch($map_api_url . $ak . "&callback=renderReverse&location=" . $from_Location_X . "," . $from_Location_Y . "&output=xml&pois=1");
             //抓取成功
             if ($fetch->errno() == 0) {
                 //正则表达式匹配城市
                 preg_match_all("/\\<city\\>(.*?)\\<\\/city\\>/", $geocoder, $city);
                 //将市区县替换为空 例如北京市=》北京
                 $city = str_replace(array("市", "区", "县"), array("", "", ""), $city[1][0]);
                 echo $city;
                 //通过新浪天气接口查询天气链接
                 //example http://php.weather.sina.com.cn/xml.php?city=%B1%B1%BE%A9&password=DJOYnieT8234jlsK&day=0
                 $weather_api_url = "http://php.weather.sina.com.cn/xml.php?";
                 //改变编码
                 $city = "city=" . urlencode(iconv("UTF-8", "GBK", $city));
                 echo $city;
                 //抓取当天天气
                 $weather = $fetch->fetch($weather_api_url . $city . "&password=DJOYnieT8234jlsK&day=0");
                 //抓取到天气
                 if ($fetch->errno() == 0 && strstr($weather, "Weather")) {
                     //正则表达式获取数据
                     preg_match_all("/\\<city\\>(.*?)\\<\\/city\\>/", $weather, $w_city);
                     preg_match_all("/\\<status2\\>(.*?)\\<\\/status2\\>/", $weather, $w_status2);
                     preg_match_all("/\\<status1\\>(.*?)\\<\\/status1\\>/", $weather, $w_status1);
                     preg_match_all("/\\<temperature2\\>(.*?)\\<\\/temperature2\\>/", $weather, $w_temperature2);
                     preg_match_all("/\\<temperature1\\>(.*?)\\<\\/temperature1\\>/", $weather, $w_temperature1);
                     preg_match_all("/\\<direction1\\>(.*?)\\<\\/direction1\\>/", $weather, $w_direction1);
                     preg_match_all("/\\<direction2\\>(.*?)\\<\\/direction2\\>/", $weather, $w_direction2);
                     preg_match_all("/\\<power1\\>(.*?)\\<\\/power1\\>/", $weather, $w_power1);
                     preg_match_all("/\\<power2\\>(.*?)\\<\\/power2\\>/", $weather, $w_power2);
                     //如果天气变化一致
                     if ($w_status2[1][0] == $w_status1[1][0]) {
                         $w_status = $w_status2[1][0];
                     } else {
                         $w_status = $w_status2[1][0] . "转" . $w_status1[1][0];
                     }
                     $weather_res = array($w_city[1][0] . "天气预报", "天气:" . $w_status, "气温:" . $w_temperature2[1][0] . "℃-" . $w_temperature1[1][0] . "℃", "风向:" . $w_direction1[1][0], "风力:" . $w_power1[1][0] . "级");
                     $weather_res = implode("\n", $weather_res);
                     //消息回复
                     $msgType = "text";
                     $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $weather_res);
                     echo $resultStr;
                     exit;
                 } else {
                     echo "抓取天气信息失败";
                     exit;
                 }
             }
         }
         //回复关键字
         if (!empty($keyword)) {
             switch ($keyword) {
                 case "数据结构":
                     $msgType = "text";
                     $contentStr = "http://pan.baidu.com/s/1kUr9NRD";
                     $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
                     echo $resultStr;
                     break;
                 case "复试":
                     $msgType = "text";
                     $contentStr = "http://pan.baidu.com/s/1c1sT2Q8";
                     $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
                     echo $resultStr;
                     break;
                 case "author":
                 case "作者":
                     $msgType = "text";
                     $contentStr = "qq:1163451848";
                     $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
                     echo $resultStr;
                     break;
                     //考研时间
                 //考研时间
                 case "考研时间":
                     $resultStr = "<xml>\n\t\t\t\t\t\t\t\t\t<ToUserName><![CDATA[" . $fromUsername . "]]></ToUserName>\n\t\t\t\t\t\t\t\t\t<FromUserName><![CDATA[" . $toUsername . "]]></FromUserName>\n\t\t\t\t\t\t\t\t\t<CreateTime>" . time() . "</CreateTime>\n\t\t\t\t\t\t\t\t\t<MsgType><![CDATA[news]]></MsgType>\n\t\t\t\t\t\t\t\t\t<ArticleCount>1</ArticleCount>\n\t\t\t\t\t\t\t\t\t<Articles>\n\t\t\t\t\t\t\t\t\t<item>\n\t\t\t\t\t\t\t\t\t\t<Title><![CDATA[考研时间]]></Title> \n\t\t\t\t\t\t\t\t\t\t<Description><![CDATA[test only1]]></Description>\n\t\t\t\t\t\t\t\t\t\t<PicUrl><![CDATA[http://xijiaxiangwexin-xijiaxiangwexin.stor.sinaapp.com/pic%2Ftime.jpg]]></PicUrl>\n\t\t\t\t\t\t\t\t\t\t<Url><![CDATA[http://xijiaxiangwexin.sinaapp.com/wexin/kaoyantime.php]]></Url>\n\t\t\t\t\t\t\t\t\t</item>\n\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t</Articles>\n\t\t\t\t\t\t\t\t\t<FuncFlag>0</FuncFlag>\n\t\t\t\t\t\t\t\t\t</xml> ";
                     echo $resultStr;
                     break;
                 case "天气":
                     $resultStr = "<xml>\n\t\t\t\t\t\t\t\t\t<ToUserName><![CDATA[" . $fromUsername . "]]></ToUserName>\n\t\t\t\t\t\t\t\t\t<FromUserName><![CDATA[" . $toUsername . "]]></FromUserName>\n\t\t\t\t\t\t\t\t\t<CreateTime>" . time() . "</CreateTime>\n\t\t\t\t\t\t\t\t\t<MsgType><![CDATA[news]]></MsgType>\n\t\t\t\t\t\t\t\t\t<ArticleCount>1</ArticleCount>\n\t\t\t\t\t\t\t\t\t<Articles>\n\t\t\t\t\t\t\t\t\t<item>\n\t\t\t\t\t\t\t\t\t\t<Title><![CDATA[天气预报]]></Title> \n\t\t\t\t\t\t\t\t\t\t<Description><![CDATA[test only]]></Description>\n\t\t\t\t\t\t\t\t\t\t<PicUrl><![CDATA[http://xijiaxiangwexin-xijiaxiangwexin.stor.sinaapp.com/pic%2Fweather.jpg]]></PicUrl>\n\t\t\t\t\t\t\t\t\t\t<Url><![CDATA[http://xijiaxiangwexin.sinaapp.com/wexin/weather.php]]></Url>\n\t\t\t\t\t\t\t\t\t</item>\n\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t</Articles>\n\t\t\t\t\t\t\t\t\t<FuncFlag>0</FuncFlag>\n\t\t\t\t\t\t\t\t\t</xml> ";
                     echo $resultStr;
                     break;
                 case "导师":
                     $msgType = "text";
                     $contentStr = "1. https://github.com/TutorWikiUJS/TutorWiki" . "\n" . "2. http://pan.baidu.com/s/1i3PrVPN";
                     $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
                     echo $resultStr;
                     break;
                 default:
                     //引入turling机器人
                     $msgType = "text";
                     //显示一样的消息
                     $contentStr = $keyword;
                     $ch = curl_init();
                     $url = 'http://www.tuling123.com/openapi/api?key=*****************&info=' . $keyword . '&userid=' . $fromUsername;
                     curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
                     // 执行HTTP请求
                     curl_setopt($ch, CURLOPT_URL, $url);
                     $res = curl_exec($ch);
                     $resarr = json_decode($res, true);
                     switch ($resarr["code"]) {
                         case "100000":
                             echo "text";
                             $string = str_replace("<br>", "\n", $resarr["text"]);
                             break;
                         case "200000":
                             echo "url";
                             $string = $resarr["text"] . "\n" . "详细请点击:" . $resarr["url"];
                             break;
                         case "302000":
                             echo "news";
                             echo $resarr["text"] . "\n";
                             for ($i = 0; $i < count($resarr["list"]); $i++) {
                                 $string = "-----------------------" . "\n";
                                 $string .= $resarr["list"][$i]["article"] . "\n";
                                 $string .= $resarr["list"][$i]["source"] . "\n";
                                 $string .= $resarr["list"][$i]["detailurl"] . "\n";
                             }
                             break;
                             //case "305000":echo "trains";break;
                             //case "306000":echo "flights";break;
                         //case "305000":echo "trains";break;
                         //case "306000":echo "flights";break;
                         case "308000":
                             echo "cai pu";
                             $string = $resarr["text"] . "\n";
                             $string .= "-----------------------" . "\n";
                             $string .= "<" . $resarr["list"]["0"]["name"] . ">\n";
                             $string .= "配料:" . $resarr["list"]["0"]["info"] . "\n";
                             $string .= "详细请点击:" . $resarr["list"]["0"]["detailurl"] . "\n";
                             break;
                         case "40001":
                             $string = "sorry,sth wrong";
                             echo "1 turling_err";
                             break;
                         case "40002":
                             $string = "sorry,sth wrong";
                             echo "2 turling_err null";
                             break;
                         case "40004":
                             $string = "sorry,sth wrong";
                             echo "3 turling_err full";
                             break;
                         case "40007":
                             $string = "sorry,sth wrong";
                             echo "4 turling_err ";
                             break;
                         default:
                             $string = "sorry,sth wrong";
                             echo "turling_err";
                             break;
                     }
                     $contentStr = $string;
                     $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
                     echo $resultStr;
             }
         } else {
             echo "something i didn't know :)";
         }
     } else {
         echo "";
         exit;
     }
 }
Ejemplo n.º 9
0
 public static function build_http_query_multi($params)
 {
     if (!$params) {
         return '';
     }
     //print_r( $params );
     //return null;
     // Urlencode both keys and values
     $keys = array_keys($params);
     $values = array_values($params);
     //$keys = OAuthUtil::urlencode_rfc3986(array_keys($params));
     //$values = OAuthUtil::urlencode_rfc3986(array_values($params));
     $params = array_combine($keys, $values);
     // Parameters are sorted by name, using lexicographical byte value ordering.
     // Ref: Spec: 9.1.1 (1)
     uksort($params, 'strcmp');
     $pairs = array();
     self::$boundary = $boundary = uniqid('------------------');
     $MPboundary = '--' . $boundary;
     $endMPboundary = $MPboundary . '--';
     $multipartbody = '';
     foreach ($params as $parameter => $value) {
         //if( $parameter == 'pic' && $value{0} == '@' )
         if (in_array($parameter, array("pic", "image")) && $value[0] == '@') {
             $url = ltrim($value, '@');
             $f = new SaeFetchurl();
             $content = $f->fetch($url);
             $filename = reset(explode('?', basename($url)));
             $mime = self::get_image_mime($url);
             $multipartbody .= $MPboundary . "\r\n";
             $multipartbody .= 'Content-Disposition: form-data; name="' . $parameter . '"; filename="' . $filename . '"' . "\r\n";
             $multipartbody .= 'Content-Type: ' . $mime . "\r\n\r\n";
             $multipartbody .= $content . "\r\n";
         } else {
             $multipartbody .= $MPboundary . "\r\n";
             $multipartbody .= 'content-disposition: form-data; name="' . $parameter . "\"\r\n\r\n";
             $multipartbody .= $value . "\r\n";
         }
     }
     $multipartbody .= $endMPboundary;
     // For each parameter, the name is separated from the corresponding value by an '=' character (ASCII code 61)
     // Each name-value pair is separated by an '&' character (ASCII code 38)
     // echo $multipartbody;
     return $multipartbody;
 }
Ejemplo n.º 10
0
<?php

//
$f = new SaeFetchurl();
//myapp-mybucket.stor.sinaapp.com/pic%2Ftime.jpg
$content = $f->fetch("http://xijiaxiangwexin-xijiaxiangwexin.stor.sinaapp.com/pic%2Ftime.jpg");
if ($f->errno() == 0) {
    echo "success";
} else {
    echo $f->errmsg();
}
use sinacloud\sae\Storage;
$s = new Storage();
//$file=fopen("/test/read.txt","r");
$state = $s->putObject($content, "xijiaxiangwexin", "pic/time1.jpg");
echo $state;
//·¢ÆðpostÇëÇó
/*$f=new SaeFetchurl();
	$f->setMethod("post");
	$f->setPostData(
		array("user"=>"xi","pwd"=>"123")
	);
	$content=$f->fetch("http://xijiaxiangwexin.sinaapp.com/test/form_test_do.php");
	if($f->errno()==0)echo $content."ok";
	else echo $f->errmsg();*/
Ejemplo n.º 11
0
<?php

/**
 * keepsession.php keep session执行
 * ----------------------------------------------------------------
 */
include '../init.php';
$db = DBConnect();
$rows = $db->Dataset("SELECT * FROM " . Tb('keepsession'));
$f = new SaeFetchurl();
foreach ($rows as $row) {
    if (time() > $row['updateTime'] + 300) {
        $f->setHeader("Cookie", urldecode($row['cookie']));
        $con = $f->fetch($row['url']);
        $db->Execute("UPDATE " . Tb('keepsession') . " SET updateTime='" . time() . "' WHERE id='{$row[id]}'");
    }
}
Ejemplo n.º 12
0
header("Content-Type: text/html; charset=utf-8");
if (isset($_POST['action'])) {
    $words = $_POST['words'];
    //$ch = curl_init();
    $url = 'http://apis.baidu.com/apistore/tranlateservice/translate?query=' . $words . '&from=en&to=zh';
    $header = array('apikey: 66b4ab19cc801359be7aa58a3f8bc787');
    // 添加apikey到header
    //curl_setopt($ch, CURLOPT_HTTPHEADER  , $header);
    //curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    // 执行HTTP请求
    //curl_setopt($ch , CURLOPT_URL , $url);
    //$res = curl_exec($ch);*/
    //////////////////////////////
    //建立抓取对象
    $fetch = new SaeFetchurl();
    //$ak="66b4ab19cc801359be7aa58a3f8bc787";
    $flag = $fetch->setHeader("apikey", $header);
    $res = $fetch->fetch($url);
    //////////////////////////////
    echo $res . $flag;
    $result = json_decode($res, true);
    echo $result["retData"]["trans_result"]["0"]["dst"];
    echo '</br><a href="' . $_SERVER['PHP_SELF'] . '">try again</a>';
} else {
    ?>

<form action="translate.php" method="post">
	<input type="text" name="words"/> </br>
	<input type="hidden" name="action" value="submitted"/> </br>
	<input type="submit" name="submit" value="submit"/> </br>
Ejemplo n.º 13
0
function create_nails($name, $name_nail, $s, $f, $domain, $aimage)
{
    $s = new SaeStorage();
    $f = new SaeFetchurl();
    $img_data = $f->fetch($aimage);
    $img = new SaeImage();
    $img->setData($img_data);
    $img->resize(400);
    $new_data = $img->exec('jpg');
    if ($new_data) {
        $success = $s->write($domain, $name, $new_data);
        //写入用于显示的图片
    }
    if ($success) {
        //如果写入成功
        # code...
        $s_nail = new SaeStorage();
        $img_nail = new SaeImage();
        $img_nail->setData($img_data);
        $img_nail->resize(100);
        $new_data_nail = $img_nail->exec('jpg');
        $success_nail = $s_nail->write($domain, $name_nail, $new_data_nail);
        if ($success && $success_nail) {
            //如果写入同时成功
            $result = true;
        } else {
            $result = false;
        }
    }
    return $result;
}
     }
     exit;
 }
 // 地理位置,本地天气
 if ($form_MsgType == "location") {
     // 获取地理消息信息,经纬度,地图缩放比例,地址
     $from_Location_X = $postObj->Location_X;
     $from_Location_Y = $postObj->Location_Y;
     $from_Location_Scale = $postObj->Scale;
     $from_Location_Label = $postObj->Label;
     // 地址解析使用百度地图API的链接
     $map_api_url = "http://api.map.baidu.com/geocoder?";
     // 坐标类型
     $map_coord_type = "&coord_type=wgs84";
     // 建立抓取对象
     $f = new SaeFetchurl();
     // 抓取百度地址解析
     $geocoder = $f->fetch($map_api_url . $map_coord_type . "&location=" . $from_Location_X . "," . $from_Location_Y);
     // 如果抓取地址解析成功
     if ($f->errno() == 0) {
         // 匹配出城市
         preg_match_all("/\\<city\\>(.*?)\\<\\/city\\>/", $geocoder, $city);
         $city = str_replace(array("市", "县", "区"), array("", "", ""), $city[1][0]);
         // 通过新浪天气接口查询天气的链接
         $weather_api_url = "http://php.weather.sina.com.cn/xml.php?password=DJOYnieT8234jlsK";
         // 城市名转字符编码
         $city = "&city=" . urlencode(iconv("UTF-8", "GBK", $city));
         // 查询当天
         $day = "&day=0";
         // 抓取天气
         $weather = $f->fetch($weather_api_url . $city . $day);
Ejemplo n.º 15
0
 private function cropAvatar($path, $crop = null)
 {
     //如果不裁剪,则发生错误
     if (!$crop) {
         $this->error = '必须裁剪';
         return false;
     }
     //是sae则不需要获取全路径
     if (strtolower(APP_MODE) != 'sae') {
         //本地环境
         //获取头像的文件路径
         $fullPath = $this->getFullPath($path);
         //生成文件名后缀
         $postfix = substr(md5($crop), 0, 8);
         $savePath = preg_replace('/\\.[a-zA-Z0-9]*$/', '-' . $postfix . '$0', $fullPath);
         $returnPath = preg_replace('/\\.[a-zA-Z0-9]*$/', '-' . $postfix . '$0', $path);
         //解析crop参数
         $crop = explode(',', $crop);
         $x = $crop[0];
         $y = $crop[1];
         $width = $crop[2];
         $height = $crop[3];
         //载入临时头像
         $image = ImageWorkshop::initFromPath($fullPath);
         //如果宽度和高度近似相等,则令宽和高一样
         if (abs($height - $width) < $height * 0.01) {
             $height = min($height, $width);
             $width = $height;
         } else {
             $this->error = $height . '图像必须为正方形';
             return false;
         }
         //确认头像足够大
         if ($height < 256) {
             $this->error = '头像太小';
             return false;
         }
         //调用组件裁剪头像
         $image = ImageWorkshop::initFromPath($fullPath);
         $image->crop(ImageWorkshopLayer::UNIT_PIXEL, $width, $height, $x, $y);
         $image->save(dirname($savePath), basename($savePath));
         //返回新文件的路径
         return $returnPath;
     } else {
         //sae
         $fullPath = $path;
         $postfix = substr(md5($crop), 0, 8);
         $savePath = preg_replace('/\\.[a-zA-Z0-9]*$/', '-' . $postfix . '$0', $fullPath);
         $returnPath = preg_replace('/\\.[a-zA-Z0-9]*$/', '-' . $postfix . '$0', $path);
         //解析crop参数
         $crop = explode(',', $crop);
         $x = $crop[0];
         $y = $crop[1];
         $width = $crop[2];
         $height = $crop[3];
         //载入临时头像
         $f = new \SaeFetchurl();
         $img_data = $f->fetch($fullPath);
         $img = new \SaeImage();
         $img->setData($img_data);
         $img_attr = $img->getImageAttr();
         //生成将单位换算成为像素
         $x = $x * $img_attr[0];
         $y = $y * $img_attr[1];
         $width = $width * $img_attr[0];
         $height = $height * $img_attr[1];
         //如果宽度和高度近似相等,则令宽和高一样
         if (abs($height - $width) < $height * 0.01) {
             $height = min($height, $width);
             $width = $height;
         } else {
             $this->error = '图像必须为正方形';
             return false;
         }
         //确认头像足够大
         if ($height < 128) {
             $this->error = '头像太小';
             return false;
         }
         /*       dump('x='.$x);
                  dump('y='.$y);
                  dump('w='.$width);
                  dump('h='.$height);exit;*/
         $img->crop($x / $img_attr[0], ($x + $width) / $img_attr[0], $y / $img_attr[1], ($y + $height) / $img_attr[1]);
         $new_data = $img->exec();
         $storage = new \SaeStorage();
         $thumbFilePath = str_replace(C('UPLOAD_SAE_CONFIG.rootPath'), '', dirname($savePath) . '/' . basename($savePath));
         $thumbed = $storage->write(C('UPLOAD_SAE_CONFIG.domain'), $thumbFilePath, $new_data);
         //返回新文件的路径
         return $thumbed;
     }
 }
Ejemplo n.º 16
0
 public function fetchTemp($file, $suffix = "")
 {
     if (empty($suffix)) {
         $suffix = pathinfo($file, PATHINFO_EXTENSION);
     }
     $tmp = SAE_TMP_PATH . "tmp." . $suffix;
     $fetch = new SaeFetchurl();
     $fileContent = $fetch->fetch($file);
     file_put_contents($tmp, $fileContent);
     return $tmp;
 }
Ejemplo n.º 17
0
function pub_data()
{
    $f = new SaeFetchurl();
    return $f->fetch($GLOBALS['public_image_file']);
}
Ejemplo n.º 18
0
function xurl($xxurl)
{
    $f = new SaeFetchurl();
    $content = $f->fetch('http://xurl.cn/api.php?url=' . $xxurl);
    $data = object_array(json_decode($content));
    return $data['info'];
}
Ejemplo n.º 19
0
 public function fetchurl()
 {
     $f = new SaeFetchurl();
     echo $f->fetch('http://sina.cn');
 }
Ejemplo n.º 20
0
<?php

$con = mysql_connect(SAE_MYSQL_HOST_M . ":" . SAE_MYSQL_PORT, SAE_MYSQL_USER, SAE_MYSQL_PASS);
if (!$con) {
    die('Could not connect: ' . mysql_error());
}
mysql_select_db(SAE_MYSQL_DB, $con);
$result = mysql_query("SELECT * FROM Email");
while ($row = mysql_fetch_array($result)) {
    if ($row['Time'] == date(H)) {
        $id = $row['City'];
        $url = "http://m.weather.com.cn/data/" . $id . ".html";
        $f = new SaeFetchurl();
        $f->setMethod('get');
        $data = $f->fetch($url);
        $json = json_decode($data, TRUE);
        $mbody[1] = '今天是' . $json['weatherinfo']['date_y'] . '' . $json['weatherinfo']['week'];
        $mbody[2] = '1天后:' . $json['weatherinfo']['temp1'] . ' ' . $json['weatherinfo']['weather1'] . ' ' . $json['weatherinfo']['wind1'] . $json['weatherinfo']['fl1'];
        $mbody[3] = '2天后:' . $json['weatherinfo']['temp2'] . ' ' . $json['weatherinfo']['weather2'] . ' ' . $json['weatherinfo']['wind2'] . $json['weatherinfo']['fl2'];
        $mbody[4] = '3天后:' . $json['weatherinfo']['temp3'] . ' ' . $json['weatherinfo']['weather3'] . ' ' . $json['weatherinfo']['wind3'] . $json['weatherinfo']['fl3'];
        $mbody[5] = '4天后:' . $json['weatherinfo']['temp4'] . ' ' . $json['weatherinfo']['weather4'] . ' ' . $json['weatherinfo']['wind4'] . $json['weatherinfo']['fl4'];
        $mbody[6] = '5天后:' . $json['weatherinfo']['temp5'] . ' ' . $json['weatherinfo']['weather5'] . ' ' . $json['weatherinfo']['wind5'] . $json['weatherinfo']['fl5'];
        $mbody[7] = '6天后:' . $json['weatherinfo']['temp6'] . ' ' . $json['weatherinfo']['weather6'] . ' ' . $json['weatherinfo']['wind6'] . $json['weatherinfo']['fl6'];
        $mbody[17] = '微博:' . '淡淡清香弥漫世界';
        $mopt['from'] = '用户名密码@gmail.com';
        $mopt['smtp_host'] = 'smtp.gmail.com';
        $mopt['smtp_port'] = 587;
        $mopt['smtp_username'] = '******';
        $mopt['smtp_password'] = '******';
        $mopt['subject'] = $json['weatherinfo']['city'] . '天气预报';
        $mopt['content'] = $mbody[1] . '<br />' . $mbody[2] . '<br />' . $mbody[3] . '<br />' . $mbody[4] . '<br />' . $mbody[5] . '<br />' . $mbody[6] . '<br />' . $mbody[7] . '<br />' . $mbody[17];
Ejemplo n.º 21
0
 public function invoke($functionName, &$arguments = array(), $byRef = false, $resultMode = HproseResultMode::Normal)
 {
     $stream = new HproseStringStream(HproseTags::TagCall);
     $hproseWriter = new HproseWriter($stream);
     $hproseWriter->writeString($functionName, false);
     if (0 < count($arguments) || $byRef) {
         $hproseWriter->reset();
         $hproseWriter->writeList($arguments, false);
     }
     if ($byRef) {
         $hproseWriter->writeBoolean(true);
     }
     $stream->write(HproseTags::TagEnd);
     $request = $stream->toString();
     if ($this->filter) {
         $request = $this->filter->outputFilter($request);
     }
     $stream->close();
     $f = new SaeFetchurl();
     $cookie = $this->getCookie();
     if ($cookie != "") {
         $f->setHeader("Cookie", $cookie);
     }
     if ($this->keepAlive) {
         $f->setHeader("Connection", "keep-alive");
         $f->setHeader("Keep-Alive", $this->keepAliveTimeout);
     } else {
         $f->setHeader("Connection", "close");
     }
     foreach ($this->header as $name => $value) {
         $f->setHeader($name, $value);
     }
     $f->setMethod("post");
     $f->setPostData($request);
     $f->setConnectTimeout($this->timeout);
     $f->setSendTimeout($this->timeout);
     $f->setReadTimeout($this->timeout);
     $response = $f->fetch($this->url);
     if ($f->errno()) {
         throw new HproseException($f->errno() . ": " . $f->errmsg());
     }
     $http_response_header = $f->responseHeaders(false);
     $this->setCookie($http_response_header);
     if ($this->filter) {
         $response = $this->filter->inputFilter($response);
     }
     if ($resultMode == HproseResultMode::RawWithEndTag) {
         return $response;
     }
     if ($resultMode == HproseResultMode::Raw) {
         return substr($response, 0, -1);
     }
     $stream = new HproseStringStream($response);
     $hproseReader = new HproseReader($stream);
     $result = NULL;
     $error = NULL;
     while (($tag = $hproseReader->checkTags(array(HproseTags::TagResult, HproseTags::TagArgument, HproseTags::TagError, HproseTags::TagEnd))) !== HproseTags::TagEnd) {
         switch ($tag) {
             case HproseTags:
                 if ($resultMode == HproseResultMode::Serialized) {
                     $result = $hproseReader->readRaw()->toString();
                 } else {
                     $hproseReader->reset();
                     $result =& $hproseReader->unserialize();
                 }
                 break;
             case HproseTags:
                 $hproseReader->reset();
                 $args =& $hproseReader->readList();
                 for ($i = 0; $i < count($arguments); $i++) {
                     $arguments[$i] =& $args[$i];
                 }
                 break;
             case HproseTags:
                 $hproseReader->reset();
                 $error = new HproseException($hproseReader->readString());
                 break;
         }
     }
     if (!is_null($error)) {
         throw $error;
     }
     return $result;
 }
Ejemplo n.º 22
0
 function dfopen($url, $limit = 0, $post = '', $cookie = '', $bysocket = FALSE, $ip = '', $timeout = 15, $block = TRUE, $encodetype = 'URLENCODE')
 {
     //error_log("[uc_server]\r\nurl: $url\r\npost: $post\r\n\r\n", 3, 'c:/log/php_fopen.txt');
     $return = '';
     $matches = parse_url($url);
     $host = $matches['host'];
     $path = $matches['path'] ? $matches['path'] . ($matches['query'] ? '?' . $matches['query'] : '') : '/';
     $port = !empty($matches['port']) ? $matches['port'] : 80;
     $ch = curl_init();
     // set URL and other appropriate options
     curl_setopt($ch, CURLOPT_URL, $url);
     curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
     if ($post) {
         curl_setopt($ch, CURLOPT_POST, true);
         curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
     }
     curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER[HTTP_USER_AGENT]);
     //curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie);
     curl_setopt($ch, CURLOPT_COOKIE, $cookie);
     $return = curl_exec($ch);
     curl_close($ch);
     return $return;
     $f = new SaeFetchurl();
     if (is_array($post)) {
         $f->setPostData($post);
     }
     if (is_array($cookie)) {
         foreach ($cookie as $name => $value) {
             $f->setCookie($name, $value);
         }
     }
     $return = $f->fetch($url);
     return $return;
     if ($post) {
         $out = "POST {$path} HTTP/1.0\r\n";
         $out .= "Accept: */*\r\n";
         //$out .= "Referer: $boardurl\r\n";
         $out .= "Accept-Language: zh-cn\r\n";
         $boundary = $encodetype == 'URLENCODE' ? '' : ';' . substr($post, 0, trim(strpos($post, "\n")));
         $out .= $encodetype == 'URLENCODE' ? "Content-Type: application/x-www-form-urlencoded\r\n" : "Content-Type: multipart/form-data{$boundary}\r\n";
         $out .= "User-Agent: {$_SERVER['HTTP_USER_AGENT']}\r\n";
         $out .= "Host: {$host}:{$port}\r\n";
         $out .= 'Content-Length: ' . strlen($post) . "\r\n";
         $out .= "Connection: Close\r\n";
         $out .= "Cache-Control: no-cache\r\n";
         $out .= "Cookie: {$cookie}\r\n\r\n";
         $out .= $post;
     } else {
         $out = "GET {$path} HTTP/1.0\r\n";
         $out .= "Accept: */*\r\n";
         //$out .= "Referer: $boardurl\r\n";
         $out .= "Accept-Language: zh-cn\r\n";
         $out .= "User-Agent: {$_SERVER['HTTP_USER_AGENT']}\r\n";
         $out .= "Host: {$host}:{$port}\r\n";
         $out .= "Connection: Close\r\n";
         $out .= "Cookie: {$cookie}\r\n\r\n";
     }
     if (function_exists('fsockopen')) {
         $fp = @fsockopen($ip ? $ip : $host, $port, $errno, $errstr, $timeout);
     } elseif (function_exists('pfsockopen')) {
         $fp = @pfsockopen($ip ? $ip : $host, $port, $errno, $errstr, $timeout);
     } else {
         $fp = false;
     }
     if (!$fp) {
         return '';
     } else {
         stream_set_blocking($fp, $block);
         stream_set_timeout($fp, $timeout);
         @fwrite($fp, $out);
         $status = stream_get_meta_data($fp);
         if (!$status['timed_out']) {
             while (!feof($fp)) {
                 if (($header = @fgets($fp)) && ($header == "\r\n" || $header == "\n")) {
                     break;
                 }
             }
             $stop = false;
             while (!feof($fp) && !$stop) {
                 $data = fread($fp, $limit == 0 || $limit > 8192 ? 8192 : $limit);
                 $return .= $data;
                 if ($limit) {
                     $limit -= strlen($data);
                     $stop = $limit <= 0;
                 }
             }
         }
         @fclose($fp);
         return $return;
     }
 }
Ejemplo n.º 23
0
function getThumbImage($filename, $width = 100, $height = 'auto', $type = 0, $replace = false)
{
    $UPLOAD_URL = '';
    $UPLOAD_PATH = '';
    $filename = str_ireplace($UPLOAD_URL, '', $filename);
    //将URL转化为本地地址
    $info = pathinfo($filename);
    $oldFile = $info['dirname'] . DIRECTORY_SEPARATOR . $info['filename'] . '.' . $info['extension'];
    $thumbFile = $info['dirname'] . DIRECTORY_SEPARATOR . $info['filename'] . '_' . $width . '_' . $height . '.' . $info['extension'];
    $oldFile = str_replace('\\', '/', $oldFile);
    $thumbFile = str_replace('\\', '/', $thumbFile);
    $filename = ltrim($filename, '/');
    $oldFile = ltrim($oldFile, '/');
    $thumbFile = ltrim($thumbFile, '/');
    //兼容SAE的中心裁剪缩略
    if (strtolower(C('PICTURE_UPLOAD_DRIVER')) == 'sae') {
        $storage = new SaeStorage();
        $thumbFilePath = str_replace(C('UPLOAD_SAE_CONFIG.rootPath'), '', $thumbFile);
        if (!$storage->fileExists(C('UPLOAD_SAE_CONFIG.domain'), $thumbFilePath)) {
            $f = new SaeFetchurl();
            $img_data = $f->fetch($oldFile);
            $img = new SaeImage();
            $img->setData($img_data);
            $info_img = $img->getImageAttr();
            if ($height == "auto") {
                $height = $info_img[1] * $height / $info_img[0];
            }
            $w = $info_img[0];
            $h = $info_img[1];
            /* 居中裁剪 */
            //计算缩放比例
            $w_scale = $width / $w;
            if ($w_scale > 1) {
                $w_scale = 1 / $w_scale;
            }
            $h_scale = $height / $h;
            if ($h_scale > $w_scale) {
                //按照高来放缩
                $x1 = (1 - 1.0 * $width * $h / $w / $height) / 2;
                $x2 = 1 - $x1;
                $img->crop($x1, $x2, 0, 1);
                $img_temp = $img->exec();
                $img1 = new SaeImage();
                $img1->setData($img_temp);
                $img1->resizeRatio($h_scale);
            } else {
                $y1 = (1 - 1 * 1.0 / ($width * $h / $w / $height)) / 2;
                $y2 = 1 - $y1;
                $img->crop(0, 1, $y1, $y2);
                $img_temp = $img->exec();
                $img1 = new SaeImage();
                $img1->setData($img_temp);
                $img1->resizeRatio($w_scale);
            }
            $img1->improve();
            $new_data = $img1->exec();
            // 执行处理并返回处理后的二进制数据
            if ($new_data === false) {
                return $oldFile;
            }
            // 或者可以直接输出
            $thumbed = $storage->write(C('UPLOAD_SAE_CONFIG.domain'), $thumbFilePath, $new_data);
            $info['width'] = $width;
            $info['height'] = $height;
            $info['src'] = $thumbed;
            //图片处理失败时输出错误码和错误信息
        } else {
            $info['width'] = $width;
            $info['height'] = $height;
            $info['src'] = $storage->getUrl(C('UPLOAD_SAE_CONFIG.domain'), $thumbFilePath);
        }
        return $info;
    }
    //原图不存在直接返回
    if (!file_exists($UPLOAD_PATH . $oldFile)) {
        @unlink($UPLOAD_PATH . $thumbFile);
        $info['src'] = $oldFile;
        $info['width'] = intval($width);
        $info['height'] = intval($height);
        return $info;
        //缩图已存在并且  replace替换为false
    } elseif (file_exists($UPLOAD_PATH . $thumbFile) && !$replace) {
        $imageinfo = getimagesize($UPLOAD_PATH . $thumbFile);
        $info['src'] = $thumbFile;
        $info['width'] = intval($imageinfo[0]);
        $info['height'] = intval($imageinfo[1]);
        return $info;
        //执行缩图操作
    } else {
        $oldimageinfo = getimagesize($UPLOAD_PATH . $oldFile);
        $old_image_width = intval($oldimageinfo[0]);
        $old_image_height = intval($oldimageinfo[1]);
        if ($old_image_width <= $width && $old_image_height <= $height) {
            @unlink($UPLOAD_PATH . $thumbFile);
            @copy($UPLOAD_PATH . $oldFile, $UPLOAD_PATH . $thumbFile);
            $info['src'] = $thumbFile;
            $info['width'] = $old_image_width;
            $info['height'] = $old_image_height;
            return $info;
        } else {
            if ($height == "auto") {
                $height = $old_image_height * $width / $old_image_width;
            }
            if ($width == "auto") {
                $width = $old_image_width * $width / $old_image_height;
            }
            if (intval($height) == 0 || intval($width) == 0) {
                return 0;
            }
            require_once 'ThinkPHP/Library/Vendor/phpthumb/PhpThumbFactory.class.php';
            $thumb = PhpThumbFactory::create($UPLOAD_PATH . $filename);
            if ($type == 0) {
                $thumb->adaptiveResize($width, $height);
            } else {
                $thumb->resize($width, $height);
            }
            $res = $thumb->save($UPLOAD_PATH . $thumbFile);
            $info['src'] = $UPLOAD_PATH . $thumbFile;
            $info['width'] = $old_image_width;
            $info['height'] = $old_image_height;
            return $info;
            //内置库缩略
            /*  $image = new \Think\Image();
                $image->open($UPLOAD_PATH . $filename);
                //dump($image);exit;
                $image->thumb($width, $height, $type);
                $image->save($UPLOAD_PATH . $thumbFile);
                //缩图失败
                if (!$image) {
                    $thumbFile = $oldFile;
                }
                $info['width'] = $width;
                $info['height'] = $height;
                $info['src'] = $thumbFile;
                return $info;*/
        }
    }
}
Ejemplo n.º 24
0
 public function cropPicture($uid, $crop = null, $ext = 'jpg')
 {
     //如果不裁剪,则发生错误
     if (!$crop) {
         $this->error('必须裁剪');
     }
     $path = "/Uploads/Avatar/" . $uid . "/original." . $ext;
     //获取文件路径
     $fullPath = substr($path, 0, 1) == '/' ? '.' . $path : $path;
     $savePath = str_replace('original', 'crop', $fullPath);
     $returnPath = str_replace('original', 'crop', $path);
     $returnPath = substr($returnPath, 0, 1) == '/' ? '.' . $returnPath : $returnPath;
     //解析crop参数
     $crop = explode(',', $crop);
     $x = $crop[0];
     $y = $crop[1];
     $width = $crop[2];
     $height = $crop[3];
     //是sae则不需要获取全路径
     if (strtolower(C('PICTURE_UPLOAD_DRIVER')) == 'local') {
         //本地环境
         $image = ImageWorkshop::initFromPath($fullPath);
         //生成将单位换算成为像素
         $x = $x * $image->getWidth();
         $y = $y * $image->getHeight();
         $width = $width * $image->getWidth();
         $height = $height * $image->getHeight();
         //如果宽度和高度近似相等,则令宽和高一样
         if (abs($height - $width) < $height * 0.01) {
             $height = min($height, $width);
             $width = $height;
         }
         //调用组件裁剪头像
         $image = ImageWorkshop::initFromPath($fullPath);
         $image->crop(ImageWorkshopLayer::UNIT_PIXEL, $width, $height, $x, $y);
         $image->save(dirname($savePath), basename($savePath));
         //返回新文件的路径
         return $returnPath;
     } elseif (strtolower(C('PICTURE_UPLOAD_DRIVER')) == 'sae') {
         //sae
         //载入临时头像
         $f = new \SaeFetchurl();
         $img_data = $f->fetch($fullPath);
         $img = new \SaeImage();
         $img->setData($img_data);
         $img_attr = $img->getImageAttr();
         //生成将单位换算成为像素
         $x = $x * $img_attr[0];
         $y = $y * $img_attr[1];
         $width = $width * $img_attr[0];
         $height = $height * $img_attr[1];
         //如果宽度和高度近似相等,则令宽和高一样
         if (abs($height - $width) < $height * 0.01) {
             $height = min($height, $width);
             $width = $height;
         }
         $img->crop($x / $img_attr[0], ($x + $width) / $img_attr[0], $y / $img_attr[1], ($y + $height) / $img_attr[1]);
         $new_data = $img->exec();
         $storage = new \SaeStorage();
         $thumbFilePath = str_replace(C('UPLOAD_SAE_CONFIG.rootPath'), '', dirname($savePath) . '/' . basename($savePath));
         $thumbed = $storage->write(C('UPLOAD_SAE_CONFIG.domain'), $thumbFilePath, $new_data);
         //返回新文件的路径
         return $thumbed;
     } elseif (strtolower(C('PICTURE_UPLOAD_DRIVER')) == 'qiniu') {
         $imageInfo = file_get_contents($fullPath . '?imageInfo');
         $imageInfo = json_decode($imageInfo);
         //生成将单位换算成为像素
         $x = $x * $imageInfo->width;
         $y = $y * $imageInfo->height;
         $width = $width * $imageInfo->width;
         $height = $height * $imageInfo->height;
         $new_img = $fullPath . '?imageMogr2/crop/!' . $width . 'x' . $height . 'a' . $x . 'a' . $y;
         //返回新文件的路径
         return $new_img;
     }
 }
Ejemplo n.º 25
0
<?php

if (isset($_REQUEST['i'])) {
    $fetcher = new SaeFetchurl();
    header('Content-Type: application/json;charset=utf-8');
    echo '[';
    $content = $fetcher->fetch("http://www.weather.com.cn/data/sk/{$_REQUEST['i']}.html");
    echo $content;
    echo ',';
    $content = $fetcher->fetch("http://m.weather.com.cn/data/{$_REQUEST['i']}.html");
    echo $content;
    echo ']';
}
Ejemplo n.º 26
0
<?php

header("Content-Type: text/html; charset=utf-8");
//建立抓取对象
$fetch = new SaeFetchurl();
//通过新浪天气接口查询天气链接
//example http://php.weather.sina.com.cn/xml.php?city=%B1%B1%BE%A9&password=DJOYnieT8234jlsK&day=0
$weather_api_url = "http://php.weather.sina.com.cn/xml.php?";
//改变编码
$city = $_POST['city'];
//echo $city;
$city = urlencode(iconv("UTF-8", "GBK", $city));
$city = "city=" . $city;
//echo $city;
//抓取当天天气
$weather = $fetch->fetch($weather_api_url . $city . "&password=DJOYnieT8234jlsK&day=0");
//echo $weather_api_url.$city."&password=DJOYnieT8234jlsK&day=0";
//抓取到天气
if ($fetch->errno() == 0 && strstr($weather, "Weather")) {
    //正则表达式获取数据
    preg_match_all("/\\<city\\>(.*?)\\<\\/city\\>/", $weather, $w_city);
    preg_match_all("/\\<status2\\>(.*?)\\<\\/status2\\>/", $weather, $w_status2);
    preg_match_all("/\\<status1\\>(.*?)\\<\\/status1\\>/", $weather, $w_status1);
    preg_match_all("/\\<temperature2\\>(.*?)\\<\\/temperature2\\>/", $weather, $w_temperature2);
    preg_match_all("/\\<temperature1\\>(.*?)\\<\\/temperature1\\>/", $weather, $w_temperature1);
    preg_match_all("/\\<direction1\\>(.*?)\\<\\/direction1\\>/", $weather, $w_direction1);
    preg_match_all("/\\<direction2\\>(.*?)\\<\\/direction2\\>/", $weather, $w_direction2);
    preg_match_all("/\\<power1\\>(.*?)\\<\\/power1\\>/", $weather, $w_power1);
    preg_match_all("/\\<power2\\>(.*?)\\<\\/power2\\>/", $weather, $w_power2);
    //如果天气变化一致
    if ($w_status2 == $w_status1) {
Ejemplo n.º 27
0
function tbs($cookie = "")
{
    $f = new SaeFetchurl();
    $f->setCookie("BDUSS", $cookie);
    $content = $f->fetch("http://tieba.baidu.com/dc/common/tbs");
    $tbs = explode('"', $content);
    return $tbs[3];
}
Ejemplo n.º 28
-2
 public function actionUpdateHeadimg()
 {
     $model = $this->loadModel(Yii::app()->user->id);
     if (isset($_POST['Member'])) {
         $model->headimg = CUploadedFile::getInstance($model, 'headimg');
         $this->performAjaxValidation($model, array('headimg'));
         if ($model->validate(array('headimg'))) {
             if (empty($model->headimg)) {
                 header('Content-Type: text/html; charset=utf-8;');
                 echo "<script language='javascript'>alert('上传文件不能为空');window.location.href='updateHeadimg';</script>";
                 exit;
             }
             list($usec, $sec) = explode(" ", microtime());
             $usec = substr($usec, 2, 2);
             $newFileName = 'headimg' . $sec . $usec . '.jpg';
             $uploadimage = new SaeStorage();
             $uploadimage->upload('headimg', $newFileName, $model->headimg->tempName);
             $newFile = "http://918s-headimg.stor.sinaapp.com/" . $newFileName;
             $f = new SaeFetchurl();
             $img_data = $f->fetch($newFile);
             $img = new SaeImage();
             $img->setData($img_data);
             if ($_POST['w'] && $_POST['h']) {
                 //用户选中截图工具,按照对应坐标进行截图
                 $x1 = $_POST['x1'] / 200;
                 $w = ($_POST['x1'] + $_POST['w']) / 200;
                 $y1 = $_POST['y1'] / 300;
                 $h = ($_POST['y1'] + $_POST['h']) / 300;
                 $img->crop($x1, $w, $y1, $h);
                 $img->resize(100, 100);
             } else {
                 //用户直接提交,直接对图片进行缩放
                 $img->resize(100, 100);
             }
             $data = $img->exec();
             $uploadimage->write('headimg', $newFileName, $data);
             $model->headimg = $newFileName;
             if ($model->saveAttributes(array('headimg'))) {
                 $this->redirect(array('/member/index'));
             }
         }
     }
     $this->render('updateHeadimg', array('model' => $model));
 }