functions.php 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346
  1. <?php
  2. namespace Qiniu;
  3. use Qiniu\Config;
  4. if (!defined('QINIU_FUNCTIONS_VERSION')) {
  5. define('QINIU_FUNCTIONS_VERSION', Config::SDK_VER);
  6. /**
  7. * 计算文件的crc32检验码:
  8. *
  9. * @param $file string 待计算校验码的文件路径
  10. *
  11. * @return string 文件内容的crc32校验码
  12. */
  13. function crc32_file($file)
  14. {
  15. $hash = hash_file('crc32b', $file);
  16. $array = unpack('N', pack('H*', $hash));
  17. return sprintf('%u', $array[1]);
  18. }
  19. /**
  20. * 计算输入流的crc32检验码
  21. *
  22. * @param $data string 待计算校验码的字符串
  23. *
  24. * @return string 输入字符串的crc32校验码
  25. */
  26. function crc32_data($data)
  27. {
  28. $hash = hash('crc32b', $data);
  29. $array = unpack('N', pack('H*', $hash));
  30. return sprintf('%u', $array[1]);
  31. }
  32. /**
  33. * 对提供的数据进行urlsafe的base64编码。
  34. *
  35. * @param string $data 待编码的数据,一般为字符串
  36. *
  37. * @return string 编码后的字符串
  38. * @link http://developer.qiniu.com/docs/v6/api/overview/appendix.html#urlsafe-base64
  39. */
  40. function base64_urlSafeEncode($data)
  41. {
  42. $find = array('+', '/');
  43. $replace = array('-', '_');
  44. return str_replace($find, $replace, base64_encode($data));
  45. }
  46. /**
  47. * 对提供的urlsafe的base64编码的数据进行解码
  48. *
  49. * @param string $str 待解码的数据,一般为字符串
  50. *
  51. * @return string 解码后的字符串
  52. */
  53. function base64_urlSafeDecode($str)
  54. {
  55. $find = array('-', '_');
  56. $replace = array('+', '/');
  57. return base64_decode(str_replace($find, $replace, $str));
  58. }
  59. /**
  60. * 二维数组根据某个字段排序
  61. * @param array $array 要排序的数组
  62. * @param string $key 要排序的键
  63. * @param string $sort 排序类型 SORT_ASC SORT_DESC
  64. * return array 排序后的数组
  65. */
  66. function arraySort($array, $key, $sort = SORT_ASC)
  67. {
  68. $keysValue = array();
  69. foreach ($array as $k => $v) {
  70. $keysValue[$k] = $v[$key];
  71. }
  72. array_multisort($keysValue, $sort, $array);
  73. return $array;
  74. }
  75. /**
  76. * Wrapper for JSON decode that implements error detection with helpful
  77. * error messages.
  78. *
  79. * @param string $json JSON data to parse
  80. * @param bool $assoc When true, returned objects will be converted
  81. * into associative arrays.
  82. * @param int $depth User specified recursion depth.
  83. *
  84. * @return mixed
  85. * @throws \InvalidArgumentException if the JSON cannot be parsed.
  86. * @link http://www.php.net/manual/en/function.json-decode.php
  87. */
  88. function json_decode($json, $assoc = false, $depth = 512)
  89. {
  90. static $jsonErrors = array(
  91. JSON_ERROR_DEPTH => 'JSON_ERROR_DEPTH - Maximum stack depth exceeded',
  92. JSON_ERROR_STATE_MISMATCH => 'JSON_ERROR_STATE_MISMATCH - Underflow or the modes mismatch',
  93. JSON_ERROR_CTRL_CHAR => 'JSON_ERROR_CTRL_CHAR - Unexpected control character found',
  94. JSON_ERROR_SYNTAX => 'JSON_ERROR_SYNTAX - Syntax error, malformed JSON',
  95. JSON_ERROR_UTF8 => 'JSON_ERROR_UTF8 - Malformed UTF-8 characters, possibly incorrectly encoded'
  96. );
  97. if (empty($json)) {
  98. return null;
  99. }
  100. $data = \json_decode($json, $assoc, $depth);
  101. if (JSON_ERROR_NONE !== json_last_error()) {
  102. $last = json_last_error();
  103. throw new \InvalidArgumentException(
  104. 'Unable to parse JSON data: '
  105. . (isset($jsonErrors[$last])
  106. ? $jsonErrors[$last]
  107. : 'Unknown error')
  108. );
  109. }
  110. return $data;
  111. }
  112. /**
  113. * 计算七牛API中的数据格式
  114. *
  115. * @param string $bucket 待操作的空间名
  116. * @param string $key 待操作的文件名
  117. *
  118. * @return string 符合七牛API规格的数据格式
  119. * @link https://developer.qiniu.com/kodo/api/data-format
  120. */
  121. function entry($bucket, $key = null)
  122. {
  123. $en = $bucket;
  124. if ($key !== null) {
  125. $en = $bucket . ':' . $key;
  126. }
  127. return base64_urlSafeEncode($en);
  128. }
  129. function decodeEntry($entry)
  130. {
  131. $en = base64_urlSafeDecode($entry);
  132. $en = explode(':', $en);
  133. if (count($en) == 1) {
  134. return array($en[0], null);
  135. }
  136. return array($en[0], $en[1]);
  137. }
  138. /**
  139. * array 辅助方法,无值时不set
  140. *
  141. * @param array $array 待操作array
  142. * @param string $key key
  143. * @param string $value value 为null时 不设置
  144. *
  145. * @return array 原来的array,便于连续操作
  146. */
  147. function setWithoutEmpty(&$array, $key, $value)
  148. {
  149. if (!empty($value)) {
  150. $array[$key] = $value;
  151. }
  152. return $array;
  153. }
  154. /**
  155. * 缩略图链接拼接
  156. *
  157. * @param string $url 图片链接
  158. * @param int $mode 缩略模式
  159. * @param int $width 宽度
  160. * @param int $height 长度
  161. * @param string $format 输出类型
  162. * @param int $quality 图片质量
  163. * @param int $interlace 是否支持渐进显示
  164. * @param int $ignoreError 忽略结果
  165. * @return string
  166. * @link http://developer.qiniu.com/code/v6/api/kodo-api/image/imageview2.html
  167. * @author Sherlock Ren <sherlock_ren@icloud.com>
  168. */
  169. function thumbnail(
  170. $url,
  171. $mode,
  172. $width,
  173. $height,
  174. $format = null,
  175. $quality = null,
  176. $interlace = null,
  177. $ignoreError = 1
  178. ) {
  179. static $imageUrlBuilder = null;
  180. if (is_null($imageUrlBuilder)) {
  181. $imageUrlBuilder = new \Qiniu\Processing\ImageUrlBuilder;
  182. }
  183. return call_user_func_array(array($imageUrlBuilder, 'thumbnail'), func_get_args());
  184. }
  185. /**
  186. * 图片水印
  187. *
  188. * @param string $url 图片链接
  189. * @param string $image 水印图片链接
  190. * @param numeric $dissolve 透明度
  191. * @param string $gravity 水印位置
  192. * @param numeric $dx 横轴边距
  193. * @param numeric $dy 纵轴边距
  194. * @param numeric $watermarkScale 自适应原图的短边比例
  195. * @link http://developer.qiniu.com/code/v6/api/kodo-api/image/watermark.html
  196. * @return string
  197. * @author Sherlock Ren <sherlock_ren@icloud.com>
  198. */
  199. function waterImg(
  200. $url,
  201. $image,
  202. $dissolve = 100,
  203. $gravity = 'SouthEast',
  204. $dx = null,
  205. $dy = null,
  206. $watermarkScale = null
  207. ) {
  208. static $imageUrlBuilder = null;
  209. if (is_null($imageUrlBuilder)) {
  210. $imageUrlBuilder = new \Qiniu\Processing\ImageUrlBuilder;
  211. }
  212. return call_user_func_array(array($imageUrlBuilder, 'waterImg'), func_get_args());
  213. }
  214. /**
  215. * 文字水印
  216. *
  217. * @param string $url 图片链接
  218. * @param string $text 文字
  219. * @param string $font 文字字体
  220. * @param string $fontSize 文字字号
  221. * @param string $fontColor 文字颜色
  222. * @param numeric $dissolve 透明度
  223. * @param string $gravity 水印位置
  224. * @param numeric $dx 横轴边距
  225. * @param numeric $dy 纵轴边距
  226. * @link http://developer.qiniu.com/code/v6/api/kodo-api/image/watermark.html#text-watermark
  227. * @return string
  228. * @author Sherlock Ren <sherlock_ren@icloud.com>
  229. */
  230. function waterText(
  231. $url,
  232. $text,
  233. $font = '黑体',
  234. $fontSize = 0,
  235. $fontColor = null,
  236. $dissolve = 100,
  237. $gravity = 'SouthEast',
  238. $dx = null,
  239. $dy = null
  240. ) {
  241. static $imageUrlBuilder = null;
  242. if (is_null($imageUrlBuilder)) {
  243. $imageUrlBuilder = new \Qiniu\Processing\ImageUrlBuilder;
  244. }
  245. return call_user_func_array(array($imageUrlBuilder, 'waterText'), func_get_args());
  246. }
  247. /**
  248. * 从uptoken解析accessKey和bucket
  249. *
  250. * @param $upToken
  251. * @return array(ak,bucket,err=null)
  252. */
  253. function explodeUpToken($upToken)
  254. {
  255. $items = explode(':', $upToken);
  256. if (count($items) != 3) {
  257. return array(null, null, "invalid uptoken");
  258. }
  259. $accessKey = $items[0];
  260. $putPolicy = json_decode(base64_urlSafeDecode($items[2]));
  261. $scope = $putPolicy->scope;
  262. $scopeItems = explode(':', $scope);
  263. $bucket = $scopeItems[0];
  264. return array($accessKey, $bucket, null);
  265. }
  266. // polyfill ucwords for `php version < 5.4.32` or `5.5.0 <= php version < 5.5.16`
  267. if (version_compare(phpversion(), "5.4.32") < 0 ||
  268. (
  269. version_compare(phpversion(), "5.5.0") >= 0 &&
  270. version_compare(phpversion(), "5.5.16") < 0
  271. )
  272. ) {
  273. function ucwords($str, $delimiters = " \t\r\n\f\v")
  274. {
  275. $delims = preg_split('//u', $delimiters, -1, PREG_SPLIT_NO_EMPTY);
  276. foreach ($delims as $delim) {
  277. $str = implode($delim, array_map('ucfirst', explode($delim, $str)));
  278. }
  279. return $str;
  280. }
  281. } else {
  282. function ucwords($str, $delimiters)
  283. {
  284. return \ucwords($str, $delimiters);
  285. }
  286. }
  287. /**
  288. * 将 parse_url 的结果转换回字符串
  289. * TODO: add unit test
  290. *
  291. * @param $parsed_url - parse_url 的结果
  292. * @return string
  293. */
  294. function unparse_url($parsed_url)
  295. {
  296. $scheme = isset($parsed_url['scheme']) ? $parsed_url['scheme'] . '://' : '';
  297. $host = isset($parsed_url['host']) ? $parsed_url['host'] : '';
  298. $port = isset($parsed_url['port']) ? ':' . $parsed_url['port'] : '';
  299. $user = isset($parsed_url['user']) ? $parsed_url['user'] : '';
  300. $pass = isset($parsed_url['pass']) ? ':' . $parsed_url['pass'] : '';
  301. $pass = ($user || $pass) ? "$pass@" : '';
  302. $path = isset($parsed_url['path']) ? $parsed_url['path'] : '';
  303. $query = isset($parsed_url['query']) ? '?' . $parsed_url['query'] : '';
  304. $fragment = isset($parsed_url['fragment']) ? '#' . $parsed_url['fragment'] : '';
  305. return "$scheme$user$pass$host$port$path$query$fragment";
  306. }
  307. }