function is_storage_ok() { $s = new SaeStorage(); $status = $s->write('public', '.dilicms_install_test', ''); $status and $s->delete('public', '.dilicms_install_test'); return $status; }
public static function putFileContent($filename, $content) { if (OpenConfig::SAE_MODE) { $s = new SaeStorage(); $s->write(OpenConfig::SAE_DOMAIN, $filename, $content); } else { $data = file_put_contents($filename, $content); } }
function s_write($path, $content) { if (IS_SAE) { $_s = new SaeStorage(); $_f = _s_get_path($path); return $_s->write($_f['domain'], $_f['filename'], $content); } else { return file_put_contents($path, $content); } }
function SaeStorageAppend($FilePath, $AppendContent) { $storage = new SaeStorage(); $domain = Sae_Storage_Domain_Name; $result = $storage->read($domain, $FilePath); if ($result === false) { return false; } $FileContent = $result . $AppendContent; $size = -1; //长度限制 //$attr = array('encoding'=>'gzip');//文件属性(gzip压缩) //$compress = true;//文件是否gzip压缩 $attr = array(); $compress = false; $result = $storage->write($domain, $FilePath, $FileContent, $size, $attr, $compress); return $result; }
} /** * 保存指定文件 * @param array $file 保存的文件信息 * @param boolean $replace 同名文件是否覆盖 * @return boolean 保存状态,true-成功,false-失败 */ public function save(&$file, $replace = true) { $filename = ltrim($this->rootPath . '/' . $file['save_path'] . $file['save_name'], '/'); $st = new \SaeStorage(); /* 不覆盖同名文件 */ if (!$replace && $st->fileExists($this->domain, $filename)) { $this->error = '存在同名文件' . $file['savename']; return false; } /* 移动文件 */ if (!$st->upload($this->domain, $filename, $file['tmp_name'])) { $this->error = '文件上传保存错误![' . $st->errno() . ']:' . $st->errmsg();
public static function thumb($image, $thumbname, $domain = 'public', $maxWidth = 200, $maxHeight = 50, $interlace = true) { // 获取原图信息 $info = self::getImageInfo($image); if ($info !== false) { $srcWidth = $info['width']; $srcHeight = $info['height']; $type = strtolower($info['type']); $interlace = $interlace ? 1 : 0; unset($info); $scale = min($maxWidth / $srcWidth, $maxHeight / $srcHeight); // 计算缩放比例 if ($scale >= 1) { // 超过原图大小不再缩略 $width = $srcWidth; $height = $srcHeight; } else { // 缩略图尺寸 $width = (int) ($srcWidth * $scale); $height = (int) ($srcHeight * $scale); } //sae平台上图片处理 if (class_exists('SaeStorage')) { $saeStorage = new SaeStorage(); $saeImage = new SaeImage(); $saeImage->setData(file_get_contents($image)); $saeImage->resize($width, $height); $thumbname = str_replace(array('../', './'), '', $thumbname); return $saeStorage->write($domain, $thumbname, $saeImage->exec()); } // 载入原图 $createFun = 'ImageCreateFrom' . ($type == 'jpg' ? 'jpeg' : $type); $srcImg = $createFun($image); //创建缩略图 if ($type != 'gif' && function_exists('imagecreatetruecolor')) { $thumbImg = imagecreatetruecolor($width, $height); } else { $thumbImg = imagecreate($width, $height); } // 复制图片 if (function_exists("ImageCopyResampled")) { imagecopyresampled($thumbImg, $srcImg, 0, 0, 0, 0, $width, $height, $srcWidth, $srcHeight); } else { imagecopyresized($thumbImg, $srcImg, 0, 0, 0, 0, $width, $height, $srcWidth, $srcHeight); } if ('gif' == $type || 'png' == $type) { $background_color = imagecolorallocate($thumbImg, 0, 255, 0); // 指派一个绿色 imagecolortransparent($thumbImg, $background_color); // 设置为透明色,若注释掉该行则输出绿色的图 } // 对jpeg图形设置隔行扫描 if ('jpg' == $type || 'jpeg' == $type) { imageinterlace($thumbImg, $interlace); } $dir = dirname($thumbname); if (!is_dir($dir)) { @mkdir($dir, 0777, true); } // 生成图片 $imageFun = 'image' . ($type == 'jpg' ? 'jpeg' : $type); $imageFun($thumbImg, $thumbname); imagedestroy($thumbImg); imagedestroy($srcImg); return $thumbname; } return false; }
static function upload_topic($pic_name, $change = 0, $oldpic = null) { define('DOMAIN', 'upload'); //要上传的storage名称定义 $temp = 'temp'; $s = new SaeStorage(); $poc = array('_big.jpg', '_midde.jpg', '_small.jpg', '.jpg'); foreach ($poc as $p) { $pic = $pic_name . $p; $img = $s->read($temp, $pic); if ($s->write(DOMAIN, $pic, $img) == false) { echo "图片写入失败!请重新上传,如果还是失败请联系客服!但是不要放弃对咱们原创的希望"; var_dump($s->errno(), $s->errmsg()); } unset($pic); unset($pics); unset($img); } self::delete_topic($pic_name); if ($change == 1) { self::delete_topic($oldpic, 'jpg', 'upload'); } unset($s); return 1; }
for ($i = 0; $i < 5; $i++) { $b = $kv->set('servers', $newfile); if ($b) { break; } } $tlen = $len = strlen($newfile); if ($tlen > 200 - $oflen) { $tlen = 200 - $oflen; } $servers = substr($newfile, 0, $tlen); $servers = $version . $official . $servers; require 'settings.php'; $storage = new SaeStorage($access_key, $secret_key); for ($i = 0; $i < 5; $i++) { $b = $storage->write($domain, 'servers', $servers); if ($b) { break; } } if ($len > 200 - $oflen) { $full = substr($newfile, 200 - $oflen); $full = $version . $full; for ($i = 0; $i < 5; $i++) { $b = $storage->write($domain, 'full', $full); if ($b) { break; } } } echo '0';
/** * * {@inheritDoc} * @see \Illuminate\Contracts\Filesystem\Filesystem::put() */ public function put($path, $contents, $visibility = null) { list($domain, $path) = $this->parser($path); return $this->storage->write($domain, $path, $contents); }
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; } }
} if ($t) { $data = '该用户名已被注册,请重新输入'; } else { if ($u) { $mysql->runSql("UPDATE info SET alias='{$alias}' WHERE FromUserName='******'"); $data = '更改成功!'; } else { $mysql->runSql("INSERT INTO info(FromUserName,alias) VALUES ('{$openid}','{$alias}')"); $data = '注册成功!'; } } } elseif (preg_match('#(/:)#i', $content)) { $data = $biaoqing[rand(0, count($biaoqing) - 1)]; } elseif (preg_match('#^(simi:)(.+)#i', $content, $matches)) { $s->write('simsimi', 'simi.txt', $matches[2]); $data = '更改成功!'; } elseif ($content == 'stack') { $res = stackoverflow(); $data = array(array('title' => 'Stack Overflow', 'cover' => $web . '/img/meizi/' . mt_rand(0, 9) . '.jpg')); for ($i = 0; $i < count($data); $i++) { if ($res[$i]) { array_push($data, array('title' => str_replace('-', ' ', $res[$i]['title']), 'note' => 'votes:' . $res[$i]['vote'] . ' answers:' . $res[$i]['answer'] . ' views:' . $res[$i]['view'], 'link' => 'http://stackoverflow.com/questions/' . $res[$i]['id'])); } } } elseif (preg_match('#^(md5:)(.+)#i', $content, $matches)) { $data = md5($matches[2]); } elseif ($content == 'bilibili') { $res = bilibili(); $data = array(array('title' => 'Bilibili', 'cover' => $web . '/img/bili/' . mt_rand(0, 10) . '.jpg')); for ($i = 0; $i < count($data); $i++) {
function matchEngine($content) { global $reg_arr, $biaoqing; foreach ($reg_arr as $key => $value) { if (preg_match($key, $content, $matches)) { switch ($value) { case 'dream': $data = dream($matches[2]); break; case 'translate': $data = translateAPI($matches[2]); break; case 'biaoqing': $data = $biaoqing[rand(0, count($biaoqing) - 1)]; break; case 'changeSimsimiKey': $s = new SaeStorage(); $s->write('simsimi', 'simi.txt', $matches[2]); $data = '更改成功!'; break; case 'md5': $data = md5($matches[2]); break; case 'qrcode': $qrcode = 'http://chart.apis.google.com/chart?cht=qr&chs=400x400&choe=UTF-8&chl=' . $matches[2]; $data = array(array('title' => $matches[2], 'cover' => $qrcode, 'link' => $qrcode)); break; case 'bingSearch': $bingweb = bing($matches[2], 'Web'); $bingimage = bing($matches[2], 'Image'); $data = array(array('title' => $matches[2], 'note' => '', 'cover' => $bingimage[0], 'link' => '')); //max:7 for ($i = 0; $i < 5; $i++) { array_push($data, array('title' => $bingweb[$i]['title'] . "\n" . '------------------------------------------', 'note' => $bingweb[$i]['description'], 'cover' => '', 'link' => $bingweb[$i]['url'])); } break; case 'wiki': $wiki = wiki($matches[2], $lng); $data = array(); for ($i = 0; $i < 5; $i++) { array_push($data, array('title' => $wiki[$i]['title'] . "\n" . '------------------------------------------', 'note' => $wiki[$i]['snippet'], 'cover' => '', 'link' => 'http://zh.wikipedia.org/wiki/' . $wiki[$i]['title'])); } break; case 'doubanMovie1': $m = doubanMovies($matches[2]); $data = array(array('title' => $m[0]['title'], 'note' => $m[0]['year'] . ' ' . $m[0]['average'], 'cover' => $m[0]['images']->large, 'link' => $m[0]['alt'])); for ($i = 1; $i <= 5; $i++) { array_push($data, array('title' => $m[$i]['title'], 'note' => '又名:' . $m[$i]['original_title'] . "\n" . '上映日期:' . $m[$i]['year'] . "\n" . '评价:' . $m[$i]['average'], 'cover' => $m[$i]['images']->small, 'link' => $m[$i]['alt'])); } break; case 'doubanMovie2': $m = doubanMovies($matches[2]); $movie = doubanMovie($m[0]['id']); $xinxi = '又名:'; foreach ($movie['aka'] as $value) { $xinxi .= $value . '/'; } $xinxi .= "\n" . '上映日期:' . $movie['year'] . "\n" . '制片国家:'; foreach ($movie['countries'] as $value) { $xinxi .= $value . '/'; } $xinxi .= "\n" . '类型:'; foreach ($movie['genres'] as $value) { $xinxi .= $value . '/'; } $xinxi .= "\n" . '评价:' . $movie['average']; $data = array(array('title' => $movie['title'], 'cover' => $movie['images'], 'link' => $movie['mobile_url']), array('note' => $xinxi, 'link' => $movie['mobile_url']), array('title' => '简介', 'note' => $movie['summary'], 'link' => $movie['mobile_url']), array('title' => '导演', 'note' => $movie['directors'][0]->name, 'cover' => $movie['directors'][0]->avatars->small, 'link' => $movie['directors'][0]->alt), array('title' => '主演', 'note' => $movie['casts'][0]->name, 'cover' => $movie['casts'][0]->avatars->small, 'link' => $movie['casts'][0]->alt)); break; case 'doubanBook1': $b = doubanBooks($matches[2]); $data = array(array('title' => $b[0]['title'], 'note' => $b[0]['author'][0] . ' ' . $b[0]['average'], 'cover' => $b[0]['images']->large, 'link' => $b[0]['alt'])); for ($i = 1; $i <= 4; $i++) { array_push($data, array('title' => $b[$i]['title'], 'note' => '作者:' . $b[$i]['author'][0] . "\n" . '出版社:' . $b[$i]['publisher'] . "\n" . '出版日期:' . $b[$i]['pubdate'] . "\n" . '价格:' . $b[$i]['price'] . "\n" . '评价:' . $b[$i]['average'] . "\n" . '导言:' . $b[$i]['summary'], 'cover' => $b[$i]['images']->small, 'link' => $b[$i]['alt'])); } break; case 'doubanBook2': $b = doubanBooks($matches[2]); $bk = doubanBook($b[0]['id']); $data = array(array('title' => $bk['title'], 'cover' => $bk['images'], 'link' => $bk['alt']), array('note' => '作者:' . $bk['author'][0] . "\n" . '出版社:' . $bk['publisher'] . "\n" . '出版日期:' . $bk['pubdate'] . "\n" . '价格:' . $bk['price'] . "\n" . '评价:' . $bk['average'], 'link' => $bk['alt']), array('title' => '导言:', 'note' => $bk['summary'], 'link' => $bk['alt'])); break; case 'doubanMusic1': $m = doubanMusics($matches[2]); $data = array(array('title' => $m[0]['title'], 'note' => $m[0]['average'], 'cover' => $m[0]['image'], 'link' => $m[0]['alt'])); for ($i = 1; $i <= 4; $i++) { array_push($data, array('title' => $m[$i]['title'], 'note' => '作者:' . $m[$i]['author'][0]->name . "\n" . '出版社:' . $m[$i]['publisher'][0] . "\n" . '出版日期:' . $m[$i]['pubdate'][0] . "\n" . '表演者:' . $m[$i]['singer'][0] . "\n" . '评价:' . $m[$i]['average'] . "\n" . '类型:' . $m[$i]['version'][0], 'cover' => $m[$i]['image'], 'link' => $m[$i]['alt'])); } break; case 'doubanMusic2': $m = doubanMusics($matches[2]); $mu = doubanMusic($m[0]['id']); $data = array(array('title' => $mu['title'], 'cover' => $mu['image'], 'link' => $mu['mobile_link']), array('note' => '表演者:' . $mu['singer'][0] . "\n" . '专辑类型:' . $mu['version'][0] . "\n" . '发行时间:' . $mu['pubdate'][0] . "\n" . '作者:' . $mu['author'][0]->name . "\n" . '出版者:' . $mu['publisher'][0] . "\n" . '评价:' . $mu['average'], 'link' => $mu['mobile_link']), array('title' => '简介:', 'note' => $mu['summary'], 'link' => $mu['mobile_link'])); break; case 'moments1': $moment = $matches[2]; $time = time(); $date = date("Y-m-d H:i:s", time()); $mysql = new SaeMysql(); $res = $mysql->getData("SELECT alias FROM info WHERE FromUserName='******'"); $alias = $res[0]['alias']; if (!$alias) { $data = '由于你是第一次发送动态,请按照以下格式回复基本信息:' . "\n" . '昵称:+你的昵称'; } else { $mysql->runSql("INSERT INTO moments(FromUserName,alias,moment,time,date) VALUES ('{$openid}','{$alias}','{$moment}',{$time},'{$date}')"); $data = "发送成功,你可以现在上传一张图片作为配图,当然也可以不上传啦。回复[动态]查看"; } break; case 'moments2': $alias = $matches[2]; $mysql = new SaeMysql(); $res = $mysql->getData("SELECT * FROM info"); $num = 0; while ($res[$num]) { if ($alias == $res[$num]['alias'] || $alias == '小u' || $alias == 'urinx') { $t = 1; } elseif ($openid == $res[$num]['FromUserName']) { $u = 1; } $num++; } if ($t) { $data = '该用户名已被注册,请重新输入'; } else { if ($u) { $mysql->runSql("UPDATE info SET alias='{$alias}' WHERE FromUserName='******'"); $data = '更改成功!'; } else { $mysql->runSql("INSERT INTO info(FromUserName,alias) VALUES ('{$openid}','{$alias}')"); $data = '注册成功!'; } } break; default: # code... break; } } } return $data; }
function s_write($filepath, $content) { $_s = new SaeStorage(); //初始化Storage对象 $_f = _s_get_path($filepath); return $_s->write($_f['domain'], $_f['filename'], $content); }
/** * 将图片资源保存到storage * @returns string storage中图片的URL */ public function save() { //给文件名添加随机的后缀,防止重复 $random = mt_rand(); $filename = substr(str_replace("/", "", parse_url($this->url, PHP_URL_PATH)), -10) . $random . ".jpg"; //just for test //$stor = new SaeStorage("n353jmy031","zwwkm3wjxmmkxkhwzlyjhxz3lh2xkyj3zhx014lh"); /* imagepng这样的函数不支持wrapper,用临时文件解决 imageX 第二个参数指定filename,将文件保存到一个地址而不是输出到浏览器 使用sae storage的wrapper来保存图片 file_put_contents("saestor://n/test.txt", "haha"); 保存为临时文件 $bool = imagejpeg($img, SAE_TMP_PATH . $filename); imagedestroy($img); $this-log("保存的文件名:" . $filename); 从临时文件里取出,保存到storage里 file_put_contents("saestor://wechatimg/$filename", file_get_contents(SAE_TMP_PATH . $filename));*/ /* * 新的文件保存方法 用缓存来实现,这个方法应该会快很多,因为减少了两个特别慢的函数 */ $domain = "wechatimg"; $stor = new SaeStorage(); ob_start(); imagejpeg($this->img); $imgstr = ob_get_contents(); $bool = $stor->write($domain, $filename, $imgstr); ob_end_clean(); imagedestroy($this->img); if (!$bool) { $this->log("保存文件失败"); } $this->newUrl = $stor->getUrl($domain, $filename); return $this->newUrl; }
$logo_ten_year_img = file_get_contents('../res/images/logo_ten_year110.png'); $logo_zfb_img = file_get_contents('../res/images/logo_zfb100.png'); $text_bg_img = file_get_contents('../res/images/text_back350.png'); //清空$img数据 $img->clean(); //设定要用于合成的三张图片(如果重叠,排在后面的图片会盖住排在前面的图片) $img->setData(array(array($new_data, 0, 0, 1, SAE_TOP_LEFT), array($logo_ten_year_img, -10, 10, 1, SAE_BOTTOM_RIGHT), array($logo_zfb_img, -10, -10, 1, SAE_TOP_RIGHT), array($text_bg_img, 0, -47, 1, SAE_TOP_LEFT))); //执行合成 $img->composite($size[0], $size[1]); //输出图片 $new_data = $img->exec('jpg'); if ($new_data === false) { exit_status('error', 'p2:' . $img->errmsg()); } $s = new SaeStorage(); $result = $s->write('rank', $file_name, $new_data); if (!$result) { exit_status('fail', $result); } $url = $s->getUrl('rank', $file_name); exit_status('ok', $url); } else { exit_status('fail', 'no file accept!'); } // Helper functions function exit_status($status, $data) { echo json_encode(array('status' => $status, 'data' => $data)); exit; } function get_extension($file_name)
/** * 用户更新头像 * * 使用标准Form表单上传,头像文件名为file,只接受jpg格式的文件 * * @param string token , 必填 * @return user array * @author EasyChen */ public function user_update_avatar() { if ($_FILES['file']['error'] != 0) { return self::send_error(OP_API_UPLOAD_ERROR, 'UPLOAD ERROR ' . $_FILES['file']['error']); } $tmp_image_name = SAE_TMP_PATH . md5(time() . rand(1, 99999)) . '.tmp.jpg'; jpeg_up($_FILES['file']['tmp_name'], $tmp_image_name); include_once AROOT . 'lib/thumbnail.class.php'; $file_thumb_name = 'avatar-' . uid() . '.jpg'; $tmp_file = SAE_TMP_PATH . $file_thumb_name; include_once AROOT . 'lib/icon.class.php'; $icon = new Icon(); $icon->path = $tmp_image_name; $icon->size = 100; $icon->dest = $tmp_file; $icon->createIcon(); if (on_sae()) { $s = new SaeStorage(); if (!($thumb_url = $s->write('upload', $file_thumb_name, file_get_contents($tmp_file)))) { return self::send_error(OP_API_STORAGE_ERROR, 'SAVE ERROR ' . $s->errmsg()); } } else { $local_storage = AROOT . 'static' . DS . 'upload' . DS . 'avatar' . DS; $local_storage_url = c('site_url') . DS . 'static' . DS . 'upload' . DS . 'avatar' . DS; $thumb_path = $local_storage . $file_thumb_name; $thumb_url = $local_storage_url . $file_thumb_name; if (!copy($tmp_file, $thumb_path)) { return self::send_error(OP_API_STORAGE_ERROR, 'SAVE ERROR '); } } $sql = "UPDATE `user` SET `avatar_small` = '" . s($thumb_url) . "' WHERE `id` = '" . intval(uid()) . "' LIMIT 1"; run_sql($sql); if (mysql_errno() != 0) { return self::send_error(OP_API_DB_ERROR, __('API_MESSAGE_DATABASE_ERROR') . mysql_error()); } else { return self::send_result(get_user_info_by_id(intval(uid()))); } }
/** * 远程抓取 * @param $uri * @param $config */ public function getRemoteImage2($uri, $config) { //忽略抓取时间限制 set_time_limit(0); //ue_separate_ue ue用于传递数据分割符号 $imgUrls = explode("ue_separate_ue", $uri); $tmpNames = array(); foreach ($imgUrls as $imgUrl) { //http开头验证 if (strpos($imgUrl, "http") !== 0) { array_push($tmpNames, "https error"); continue; } //sae环境 不兼容 if (!defined('SAE_TMP_PATH')) { //获取请求头 $heads = get_headers($imgUrl); //死链检测 if (!(stristr($heads[0], "200") && stristr($heads[0], "OK"))) { array_push($tmpNames, "get_headers error"); continue; } } //格式验证(扩展名验证和Content-Type验证) $fileType = strtolower(strrchr($imgUrl, '.')); if (!in_array($fileType, $config['allowFiles']) || stristr($heads['Content-Type'], "image")) { array_push($tmpNames, "Content-Type error"); continue; } //打开输出缓冲区并获取远程图片 ob_start(); $context = stream_context_create(array('http' => array('follow_location' => false))); //请确保php.ini中的fopen wrappers已经激活 readfile($imgUrl, false, $context); $img = ob_get_contents(); ob_end_clean(); //大小验证 $uriSize = strlen($img); //得到图片大小 $allowSize = 1024 * $config['maxSize']; if ($uriSize > $allowSize) { array_push($tmpNames, "maxSize error"); continue; } $savePath = $config['savePath']; if (!defined('SAE_TMP_PATH')) { //非SAE //创建保存位置 if (!file_exists($savePath)) { mkdir($savePath, 0777, true); } //写入文件 $tmpName = $savePath . rand(1, 10000) . time() . strrchr($imgUrl, '.'); try { File::writeFile($tmpName, $img, "a"); array_push($tmpNames, __ROOT__ . '/' . $tmpName); } catch (\Exception $e) { array_push($tmpNames, "error"); } } else { //SAE $Storage = new \SaeStorage(); $domain = get_opinion('SaeStorage'); $destFileName = 'remote/' . date('Y') . '/' . date('m') . '/' . rand(1, 10000) . time() . strrchr($imgUrl, '.'); $result = $Storage->write($domain, $destFileName, $img, -1); Log::write('$destFileName:' . $destFileName); if ($result) { array_push($tmpNames, $result); } else { array_push($tmpNames, "not supported"); } } } /** * 返回数据格式 * { * 'url' : '新地址一ue_separate_ue新地址二ue_separate_ue新地址三', * 'srcUrl': '原始地址一ue_separate_ue原始地址二ue_separate_ue原始地址三', * 'tip' : '状态提示' * } */ //save file info here $return_data['url'] = implode("ue_separate_ue", $tmpNames); $return_data['tip'] = '远程图片抓取成功!'; $return_data['srcUrl'] = $uri; $this->ajaxReturn($return_data); // echo "{'url':'" . implode("ue_separate_ue", $tmpNames) . "','tip':'远程图片抓取成功!','srcUrl':'" . $uri . "'}"; }
echo "正在执行导入操作:"; while ($SQL = GetNextSQL()) { $SQL = str_replace("`ecs_", "`" . TABLE_PREFIX, $SQL); // echo $SQL."<BR/>"; if (!$mysql->runSql($SQL)) { echo "执行出错:" . $mysql->errmsg() . ""; echo "SQL语句为:" . $SQL . ""; exit; } } echo "导入完成<br/>"; echo "<h1>安装成功</h1>"; echo "点击<a href='/admin'>/admin</a> 进入后台,管理员帐号为admin 密码为123<br/><br/><h2>注意</h2>为确保安全请登入后台后修改密码!并使用svn删除/install目录!"; @fclose($fp); $s = new SaeStorage(); $s->write(SAESTOR_NAME, "saestor_" . $_SERVER['HTTP_APPVERSION'] . "/data/install.lock", '1'); } else { echo "<h1>错误</h1>"; echo "ecshop4sae.sql文件不存在!"; } } else { // echo "<h1>未完成环境初始化</h1>"; echo "<h3>请先完成SAE的相关环境初始化,包括storage,memcache,mysql等,请参考根目录下的readme.txt文件或者使用sae应用商店一键安装。</h3>"; } } //从文件中逐条取SQL function GetNextSQL() { global $fp; $sql = "";
/** * 文件写入 * @param string $filename 文件名 * @param string $content 文件内容 * @param string $type 其他参数 * @return bool */ function file_write($filename, $content, $type = '') { switch (strtoupper(C('FILE_UPLOAD_TYPE'))) { case 'SAE': $s = new SaeStorage(); $arr = explode('/', ltrim($filename, './')); $domain = array_shift($arr); $save_path = implode('/', $arr); return $s->write($domain, $save_path, $content); break; case 'FTP': $storage = new \Common\Plugin\Ftp(); return $storage->put($filename, $content); break; default: return \Think\Storage::put($filename, $content, $type); } }
function sp_file_write($file, $content) { if (sp_is_sae()) { $s = new SaeStorage(); $arr = explode('/', ltrim($file, './')); $domain = array_shift($arr); $save_path = implode('/', $arr); return $s->write($domain, $save_path, $content); } else { try { $fp2 = @fopen($file, "w"); fwrite($fp2, $content); fclose($fp2); return true; } catch (Exception $e) { return false; } } }
public function storage() { $s = new SaeStorage(); $s->write('Public', 'example/thebook', 'bookcontent'); //写入文件 $ret = $s->read('Public', 'example/thebook'); //读取文件 dump($ret); $ret = $s->getUrl('Public', 'example/thebook'); //获得地址 dump($ret); }
<?php define('PATH', 'http://hosts.52zz.gq/download/'); set_time_limit(0); // 设置允许超时 $path = file_get_contents(PATH); // 提取文件目录 preg_match('/20[0-9]{6}.txt/', $path, $matches); // 找最新的hosts文件 $hosts = file_get_contents(PATH . $matches[0]); echo '<title>' . $matches[0] . '</title>'; echo '<pre>' . $hosts . '</pre>'; // 提取hosts文件 $content = $hosts; // 由于SAE不支持文件IO操作,写入到SAE Storage中 use sinacloud\sae\Storage; $s = new Storage(); $domain = 'storage'; $destFileName = 'hosts.txt'; $attr = array('encoding' => 'gzip'); $storage = new SaeStorage($ak, $sk); $result = $storage->write($domain, $destFileName, $content, -1, $attr, true);
private function base64ToImage($base64Data) { $img = base64_decode($base64Data); $this->fileName = "img" . time() . rand(1, 10000) . ".png"; $this->fullName = $this->getFolder() . '/' . $this->fileName; if (!defined('SAE_TMP_PATH')) { if (!file_put_contents($this->fullName, $img)) { $this->stateInfo = $this->getStateInfo("IO"); return; } } else { $st = new SaeStorage(SAE_ACCESSKEY, SAE_SECRETKEY); $url = $st->write('upload', $this->fullName, $img); if (!$url) { $this->stateInfo = $this->getStateInfo("IO"); return; } else { $this->fullName = $url; } } $this->oriName = ""; $this->fileSize = strlen($img); $this->fileType = ".png"; }
/** * 收到图片消息时触发,回复由收到的图片组成的图文消息 * * @return voi */ protected function onImage() { $picurl = $this->getRequest('PicUrl'); $saveurl = time() . '.png'; $s = new SaeStorage(); $img = file_get_contents($picurl); //括号中的为远程"\"#FF0000\"">图片地址 $storage_url = $s->write('pictures', $saveurl, $img); $BackMsg = "感谢您提供的图片。"; $this->mysql->saveIntoPic($this->getRequest('ToUserName'), $this->getRequest('FromUserName'), $this->getRequest('CreateTime'), $this->getRequest('MsgType'), $this->getRequest('PicUrl'), $this->getRequest('MediaId'), $this->getRequest('MsgId'), $storage_url, $BackMsg); $this->responseText("感谢您提供的图片。"); }
<?php /** * All rights reserved. * 环境检测 * @author wangxin <*****@*****.**> * @time 2011/3/9 17:24 * @version Id: 0.9 */ define('DAGGER_PATH_ROOT', rtrim(dirname(__FILE__), '/') . '/../'); include DAGGER_PATH_ROOT . "config/SysInitConfig.php"; include DAGGER_PATH_ROOT . "libs/DaggerSysInitConfig.php"; include DAGGER_PATH_CONFIG . "DBConfig.php"; if (DAGGER_PLATFORM == 'sae') { $s = new SaeStorage(); if ($s->write('data', '_test.test', 'test!')) { $str .= '<div class="text_green">storage-domian检测成功</div>'; $s->delete('data', '_test.test'); } else { $str .= '<div class="text_red">需要创建一个storage-domian:data</div>'; } if (@file_put_contents('saemc://_test.test', 'test!')) { $str .= '<div class="text_green">Memcache检测成功</div>'; } else { $str .= '<div class="text_red">需要开启SAE的Memcache</div>'; } } else { $str = '<div>基本环境检测:</div>'; //PHP版本检测 if (substr(phpversion(), 0, 1) < 5) { $str .= '<div class="text_red">PHP版本检测失败,PHP版本必须 >= 5...</div>';
/** * 修改文件处理函数 * * @access public * @param array $content 老文件 * @param array $file 新上传的文件 * @return mixed */ public static function modifyHandle($content, $file) { if (empty($file['name'])) { return false; } $fileName = preg_split("(\\/|\\|:)", $file['name']); $file['name'] = array_pop($fileName); //获取扩展名 $ext = ''; $part = explode('.', $file['name']); if (($length = count($part)) > 1) { $ext = strtolower($part[$length - 1]); } if ($content['attachment']->type != $ext) { return false; } //获取文件名 $fileName = $content['attachment']->path; $path = $path . '/' . $fileName; //add for mkdir $stor = new SaeStorage(); $options = Typecho_Widget::widget('Widget_Options'); $SaeStorageDomain = $options->plugin('SaeUpload')->saestoragedomain; if (isset($file['tmp_name'])) { //移动上传文件 if (!($path = $stor->upload($SaeStorageDomain, $fileName, $file['tmp_name']))) { return false; } } else { if (isset($file['bits'])) { //直接写入文件 if (!($path = $stor->write($SaeStorageDomain, $fileName, $file['bits']))) { return false; } } else { return false; } } if (!isset($file['size'])) { $attr = $stor->getAttr($SaeStorageDomain, $fileName, array('length')); $file['size'] = $attr['length']; } //返回相对存储路径 return array('name' => $content['attachment']->name, 'path' => $content['attachment']->path, 'size' => $file['size'], 'type' => $content['attachment']->type, 'mime' => $content['attachment']->mime); }
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;*/ } } }
/** * 将头像保存到本地 * @param $url * @param $oid * @param $uid * autor:xjw129xjt */ protected function saveAvatar($url, $oid, $uid, $type) { if (is_sae()) { $s = new \SaeStorage(); $img = file_get_contents($url); //括号中的为远程图片地址 $url_sae = $s->write(C('UPLOAD_SAE_CONFIG.domain'), '/Avatar/' . $type . 'Avatar/' . $oid . '.jpg', $img); $data['path'] = $url_sae; } else { mkdir('./Uploads/Avatar/' . $type . 'Avatar', 0777, true); $img = file_get_contents($url); $filename = './Uploads/Avatar/' . $type . 'Avatar/' . $oid . '.jpg'; file_put_contents($filename, $img); $data['path'] = $type . 'Avatar/' . $oid . '.jpg'; } $data['uid'] = $uid; $data['create_time'] = time(); $data['status'] = 1; $data['is_temp'] = 0; D('avatar')->add($data); }
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; } }
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)); }