使用php-cs-fixer更新代码格式

master
Rhilip 5 years ago
parent 7a41449855
commit 7315524056
  1. 21
      app/Class/Function.php
  2. 103
      app/Class/IFile.php
  3. 13
      app/Class/Oauth.php
  4. 9
      app/Class/Rpc.php
  5. 192
      app/Class/TransmissionRPC.php
  6. 15
      app/Class/qBittorrent.php
  7. 87
      app/Class/uTorrent.php

@ -2,7 +2,8 @@
/** /**
* 调试函数 * 调试函数
*/ */
function p($data, $echo=true){ function p($data, $echo=true)
{
$str='******************************'."\n"; $str='******************************'."\n";
// 如果是boolean或者null直接显示文字;否则print // 如果是boolean或者null直接显示文字;否则print
if (is_bool($data)) { if (is_bool($data)) {
@ -131,9 +132,9 @@ function download($url, $cookies, $useragent, $method = 'GET')
if ($method === 'POST') { if ($method === 'POST') {
curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_POST, true);
} }
if(stripos($url, 'https://') !== FALSE) { if (stripos($url, 'https://') !== false) {
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_SSLVERSION, 1); curl_setopt($ch, CURLOPT_SSLVERSION, 1);
} }
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
@ -159,7 +160,8 @@ function download($url, $cookies, $useragent, $method = 'GET')
* @param string $from 文件大小 * @param string $from 文件大小
* @return int 单位MB * @return int 单位MB
*/ */
function convertToMB($from){ function convertToMB($from)
{
$number=substr($from, 0, -2); $number=substr($from, 0, -2);
switch (strtoupper(substr($from, -2))) { switch (strtoupper(substr($from, -2))) {
case "KB": case "KB":
@ -206,7 +208,8 @@ function convertToMB($from){
) )
* @return bool 或 string false不过滤 * @return bool 或 string false不过滤
*/ */
function filter($site = '', $torrent = array()){ function filter($site = '', $torrent = array())
{
global $configALL; global $configALL;
$config = $configALL[$site]; $config = $configALL[$site];
$filter = array(); $filter = array();
@ -293,7 +296,8 @@ function evenFilter($var)
* 发布员签名 * 发布员签名
* 注意:同时配置iyuu.cn与secret时,优先使用secret。 * 注意:同时配置iyuu.cn与secret时,优先使用secret。
*/ */
function sign( $timestamp ){ function sign($timestamp)
{
global $configALL; global $configALL;
// 爱语飞飞 // 爱语飞飞
$token = isset($configALL['iyuu.cn']) && $configALL['iyuu.cn'] ? $configALL['iyuu.cn'] : ''; $token = isset($configALL['iyuu.cn']) && $configALL['iyuu.cn'] ? $configALL['iyuu.cn'] : '';
@ -307,7 +311,8 @@ function sign( $timestamp ){
* token算法:IYUU + uid + T + sha1(openid+time+盐) * token算法:IYUU + uid + T + sha1(openid+time+盐)
* @param string $token 用户请求token * @param string $token 用户请求token
*/ */
function getUid($token){ function getUid($token)
{
//验证是否IYUU开头,strpos($token,'T')<15,token总长度小于60(40+10+5) //验证是否IYUU开头,strpos($token,'T')<15,token总长度小于60(40+10+5)
return (strlen($token)<60)&&(strpos($token, 'IYUU')===0)&&(strpos($token, 'T')<15) ? substr($token, 4, strpos($token, 'T')-4): false; return (strlen($token)<60)&&(strpos($token, 'IYUU')===0)&&(strpos($token, 'T')<15) ? substr($token, 4, strpos($token, 'T')-4): false;
} }

@ -23,7 +23,7 @@ class IFile
* 'a' 写入方式打开,将文件指针指向文件末尾。如果文件不存在则尝试创建之。 * 'a' 写入方式打开,将文件指针指向文件末尾。如果文件不存在则尝试创建之。
* 'a+' 读写方式打开,将文件指针指向文件末尾。如果文件不存在则尝试创建之。 * 'a+' 读写方式打开,将文件指针指向文件末尾。如果文件不存在则尝试创建之。
*/ */
function __construct($fileName,$mode='r') public function __construct($fileName, $mode='r')
{ {
$dirName = dirname($fileName); $dirName = dirname($fileName);
$baseName = basename($fileName); $baseName = basename($fileName);
@ -32,8 +32,7 @@ class IFile
self::mkdir($dirName); self::mkdir($dirName);
$this->resource = fopen($fileName, $mode.'b'); $this->resource = fopen($fileName, $mode.'b');
if($this->resource) if ($this->resource) {
{
flock($this->resource, LOCK_EX); flock($this->resource, LOCK_EX);
} }
} }
@ -45,8 +44,7 @@ class IFile
public function read() public function read()
{ {
$content = null; $content = null;
while(!feof($this->resource)) while (!feof($this->resource)) {
{
$content.= fread($this->resource, 1024); $content.= fread($this->resource, 1024);
} }
return $content; return $content;
@ -70,20 +68,14 @@ class IFile
*/ */
public static function clearDir($dir) public static function clearDir($dir)
{ {
if($dir[0] != '.' && is_dir($dir) && is_writable($dir)) if ($dir[0] != '.' && is_dir($dir) && is_writable($dir)) {
{
$dirRes = opendir($dir); $dirRes = opendir($dir);
while( false !== ($fileName = readdir($dirRes)) ) while (false !== ($fileName = readdir($dirRes))) {
{ if ($fileName[0] !== '.') {
if($fileName[0] !== '.')
{
$fullpath = $dir.'/'.$fileName; $fullpath = $dir.'/'.$fileName;
if(is_file($fullpath)) if (is_file($fullpath)) {
{
self::unlink($fullpath); self::unlink($fullpath);
} } else {
else
{
self::clearDir($fullpath); self::clearDir($fullpath);
rmdir($fullpath); rmdir($fullpath);
} }
@ -91,9 +83,7 @@ class IFile
} }
closedir($dirRes); closedir($dirRes);
return true; return true;
} } else {
else
{
return false; return false;
} }
} }
@ -105,12 +95,12 @@ class IFile
*/ */
public static function getInfo($fileName) public static function getInfo($fileName)
{ {
if(is_file($fileName)) if (is_file($fileName)) {
return stat($fileName); return stat($fileName);
} else {
else
return null; return null;
} }
}
/** /**
* @brief 创建文件夹 * @brief 创建文件夹
@ -139,16 +129,12 @@ class IFile
copy($from, $to); copy($from, $to);
if(is_file($to)) if (is_file($to)) {
{ if ($mode == 'x') {
if($mode == 'x')
{
self::unlink($from); self::unlink($from);
} }
return true; return true;
} } else {
else
{
return false; return false;
} }
} }
@ -160,13 +146,12 @@ class IFile
*/ */
public static function unlink($fileName) public static function unlink($fileName)
{ {
if(is_file($fileName) && is_writable($fileName)) if (is_file($fileName) && is_writable($fileName)) {
{
return unlink($fileName); return unlink($fileName);
} } else {
else
return false; return false;
} }
}
/** /**
* @brief 删除$dir文件夹 或者 其下所有文件 * @brief 删除$dir文件夹 或者 其下所有文件
@ -176,24 +161,18 @@ class IFile
*/ */
public static function rmdir($dir, $recursive = false) public static function rmdir($dir, $recursive = false)
{ {
if(is_dir($dir) && is_writable($dir)) if (is_dir($dir) && is_writable($dir)) {
{
//强制删除 //强制删除
if($recursive == true) if ($recursive == true) {
{
self::clearDir($dir); self::clearDir($dir);
return self::rmdir($dir, false); return self::rmdir($dir, false);
} }
//非强制删除 //非强制删除
else else {
{ if (rmdir($dir)) {
if(rmdir($dir))
{
return true; return true;
} } else {
else
{
return false; return false;
} }
} }
@ -209,34 +188,26 @@ class IFile
public static function getFileType($fileName) public static function getFileType($fileName)
{ {
$filetype = null; $filetype = null;
if(!is_file($fileName)) if (!is_file($fileName)) {
{
return false; return false;
} }
$fileRes = fopen($fileName, "rb"); $fileRes = fopen($fileName, "rb");
if(!$fileRes) if (!$fileRes) {
{
return false; return false;
} }
$bin= fread($fileRes, 2); $bin= fread($fileRes, 2);
fclose($fileRes); fclose($fileRes);
if($bin != null) if ($bin != null) {
{
$strInfo = unpack("C2chars", $bin); $strInfo = unpack("C2chars", $bin);
$typeCode = intval($strInfo['chars1'].$strInfo['chars2']); $typeCode = intval($strInfo['chars1'].$strInfo['chars2']);
$typelist = self::getTypeList(); $typelist = self::getTypeList();
foreach($typelist as $val) foreach ($typelist as $val) {
{ if (strtolower($val[0]) == strtolower($typeCode)) {
if(strtolower($val[0]) == strtolower($typeCode)) if ($val[0] == 8075) {
{
if($val[0] == 8075)
{
return array('zip','docx','xlsx'); return array('zip','docx','xlsx');
} } else {
else
{
return $val[1]; return $val[1];
} }
} }
@ -283,14 +254,11 @@ class IFile
*/ */
public static function isEmptyDir($dir) public static function isEmptyDir($dir)
{ {
if(is_dir($dir)) if (is_dir($dir)) {
{
$isEmpty = true; $isEmpty = true;
$dirRes = opendir($dir); $dirRes = opendir($dir);
while(false !== ($fileName = readdir($dirRes))) while (false !== ($fileName = readdir($dirRes))) {
{ if ($fileName!='.' && $fileName!='..') {
if($fileName!='.' && $fileName!='..')
{
$isEmpty = false; $isEmpty = false;
break; break;
} }
@ -322,10 +290,9 @@ class IFile
/** /**
* @brief 析构函数,释放文件连接句柄 * @brief 析构函数,释放文件连接句柄
*/ */
function __destruct() public function __destruct()
{
if(is_resource($this->resource))
{ {
if (is_resource($this->resource)) {
fclose($this->resource); fclose($this->resource);
} }
} }

@ -3,7 +3,9 @@
* IYUU用户注册、认证 * IYUU用户注册、认证
*/ */
use Curl\Curl; use Curl\Curl;
class Oauth{
class Oauth
{
// 合作的站点 // 合作的站点
public static $sites = ['ourbits']; public static $sites = ['ourbits'];
// 爱语飞飞token // 爱语飞飞token
@ -17,7 +19,8 @@ class Oauth{
/** /**
* 初始化配置 * 初始化配置
*/ */
public static function init(){ public static function init()
{
global $configALL; global $configALL;
foreach (self::$sites as $name) { foreach (self::$sites as $name) {
if (isset($configALL[$name]['passkey']) && $configALL[$name]['passkey'] && isset($configALL[$name]['id']) && $configALL[$name]['id']) { if (isset($configALL[$name]['passkey']) && $configALL[$name]['passkey'] && isset($configALL[$name]['id']) && $configALL[$name]['id']) {
@ -35,7 +38,8 @@ class Oauth{
/** /**
* 从配置文件内读取爱语飞飞token作为鉴权参数 * 从配置文件内读取爱语飞飞token作为鉴权参数
*/ */
public static function getSign(){ public static function getSign()
{
global $configALL; global $configALL;
// 爱语飞飞 // 爱语飞飞
$token = isset($configALL['iyuu.cn']) && $configALL['iyuu.cn'] ? $configALL['iyuu.cn'] : ''; $token = isset($configALL['iyuu.cn']) && $configALL['iyuu.cn'] ? $configALL['iyuu.cn'] : '';
@ -51,7 +55,8 @@ class Oauth{
* 作用:在服务器端实现微信用户与合作站点用户id的关联 * 作用:在服务器端实现微信用户与合作站点用户id的关联
* 参数:爱语飞飞token + 合作站点用户id + sha1(合作站点密钥passkey) + 合作站点标识 * 参数:爱语飞飞token + 合作站点用户id + sha1(合作站点密钥passkey) + 合作站点标识
*/ */
public static function login($apiUrl = ''){ public static function login($apiUrl = '')
{
$is_oauth = self::init(); $is_oauth = self::init();
if ($is_oauth) { if ($is_oauth) {
$curl = new Curl(); $curl = new Curl();

@ -55,7 +55,8 @@ class Rpc
/** /**
* 初始化 * 初始化
*/ */
public static function init($site = '', $method = 'GET'){ public static function init($site = '', $method = 'GET')
{
global $configALL; global $configALL;
self::$site = $site; self::$site = $site;
@ -91,8 +92,7 @@ class Rpc
echo "clients_".$k." 用户名或密码未配置,已跳过 \n\n"; echo "clients_".$k." 用户名或密码未配置,已跳过 \n\n";
continue; continue;
} }
try try {
{
switch ($v['type']) { switch ($v['type']) {
case 'transmission': case 'transmission':
self::$links[$k]['rpc'] = new TransmissionRPC($v['host'], $v['username'], $v['password']); self::$links[$k]['rpc'] = new TransmissionRPC($v['host'], $v['username'], $v['password']);
@ -145,8 +145,7 @@ class Rpc
} }
break; break;
case 1: //负载均衡模式 case 1: //负载均衡模式
try try {
{
$is_url = false; $is_url = false;
if ((strpos($torrent, 'http://')===0) || (strpos($torrent, 'https://')===0) || (strpos($torrent, 'magnet:?xt=urn:btih:')===0)) { if ((strpos($torrent, 'http://')===0) || (strpos($torrent, 'https://')===0) || (strpos($torrent, 'magnet:?xt=urn:btih:')===0)) {
$is_url = true; $is_url = true;

@ -29,8 +29,9 @@
/** /**
* A friendly little version check... * A friendly little version check...
*/ */
if ( version_compare( PHP_VERSION, TransmissionRPC::MIN_PHPVER, '<' ) ) if (version_compare(PHP_VERSION, TransmissionRPC::MIN_PHPVER, '<')) {
die("The TransmissionRPC class requires PHP version {TransmissionRPC::TRANSMISSIONRPC_MIN_PHPVER} or above." . PHP_EOL); die("The TransmissionRPC class requires PHP version {TransmissionRPC::TRANSMISSIONRPC_MIN_PHPVER} or above." . PHP_EOL);
}
/** /**
* Transmission bittorrent client/daemon RPC communication class * Transmission bittorrent client/daemon RPC communication class
@ -133,7 +134,9 @@ class TransmissionRPC
*/ */
public function start($ids) public function start($ids)
{ {
if ( !is_array( $ids ) ) $ids = array( $ids ); // Convert $ids to an array if only a single id was passed if (!is_array($ids)) {
$ids = array( $ids );
} // Convert $ids to an array if only a single id was passed
$request = array( "ids" => $ids ); $request = array( "ids" => $ids );
return $this->request("torrent-start", $request); return $this->request("torrent-start", $request);
} }
@ -145,7 +148,9 @@ class TransmissionRPC
*/ */
public function stop($ids) public function stop($ids)
{ {
if ( !is_array( $ids ) ) $ids = array( $ids ); // Convert $ids to an array if only a single id was passed if (!is_array($ids)) {
$ids = array( $ids );
} // Convert $ids to an array if only a single id was passed
$request = array( "ids" => $ids ); $request = array( "ids" => $ids );
return $this->request("torrent-stop", $request); return $this->request("torrent-stop", $request);
} }
@ -157,7 +162,9 @@ class TransmissionRPC
*/ */
public function reannounce($ids) public function reannounce($ids)
{ {
if ( !is_array( $ids ) ) $ids = array( $ids ); // Convert $ids to an array if only a single id was passed if (!is_array($ids)) {
$ids = array( $ids );
} // Convert $ids to an array if only a single id was passed
$request = array( "ids" => $ids ); $request = array( "ids" => $ids );
return $this->request("torrent-reannounce", $request); return $this->request("torrent-reannounce", $request);
} }
@ -169,7 +176,9 @@ class TransmissionRPC
*/ */
public function verify($ids) public function verify($ids)
{ {
if ( !is_array( $ids ) ) $ids = array( $ids ); // Convert $ids to an array if only a single id was passed if (!is_array($ids)) {
$ids = array( $ids );
} // Convert $ids to an array if only a single id was passed
$request = array( "ids" => $ids ); $request = array( "ids" => $ids );
return $this->request("torrent-verify", $request); return $this->request("torrent-verify", $request);
} }
@ -215,8 +224,12 @@ class TransmissionRPC
*/ */
public function get($ids = array(), $fields = array()) public function get($ids = array(), $fields = array())
{ {
if ( !is_array( $ids ) ) $ids = array( $ids ); // Convert $ids to an array if only a single id was passed if (!is_array($ids)) {
if ( count( $fields ) == 0 ) $fields = array( "id", "name", "status", "doneDate", "haveValid", "totalSize" ); // Defaults $ids = array( $ids );
} // Convert $ids to an array if only a single id was passed
if (count($fields) == 0) {
$fields = array( "id", "name", "status", "doneDate", "haveValid", "totalSize" );
} // Defaults
$request = array( $request = array(
"fields" => $fields, "fields" => $fields,
"ids" => $ids "ids" => $ids
@ -250,8 +263,12 @@ class TransmissionRPC
public function set($ids = array(), $arguments = array()) public function set($ids = array(), $arguments = array())
{ {
// See https://github.com/transmission/transmission/blob/2.9x/extras/rpc-spec.txt for available fields // See https://github.com/transmission/transmission/blob/2.9x/extras/rpc-spec.txt for available fields
if ( !is_array( $ids ) ) $ids = array( $ids ); // Convert $ids to an array if only a single id was passed if (!is_array($ids)) {
if ( !isset( $arguments['ids'] ) ) $arguments['ids'] = $ids; // Any $ids given in $arguments overrides the method parameter $ids = array( $ids );
} // Convert $ids to an array if only a single id was passed
if (!isset($arguments['ids'])) {
$arguments['ids'] = $ids;
} // Any $ids given in $arguments overrides the method parameter
return $this->request("torrent-set", $arguments); return $this->request("torrent-set", $arguments);
} }
@ -282,7 +299,9 @@ class TransmissionRPC
*/ */
public function add_file($torrent_location, $save_path = '', $extra_options = array()) public function add_file($torrent_location, $save_path = '', $extra_options = array())
{ {
if(!empty($save_path)) $extra_options['download-dir'] = $save_path; if (!empty($save_path)) {
$extra_options['download-dir'] = $save_path;
}
$extra_options['filename'] = $torrent_location; $extra_options['filename'] = $torrent_location;
return $this->request("torrent-add", $extra_options); return $this->request("torrent-add", $extra_options);
@ -321,7 +340,9 @@ class TransmissionRPC
*/ */
public function remove($ids, $delete_local_data = false) public function remove($ids, $delete_local_data = false)
{ {
if ( !is_array( $ids ) ) $ids = array( $ids ); // Convert $ids to an array if only a single id was passed if (!is_array($ids)) {
$ids = array( $ids );
} // Convert $ids to an array if only a single id was passed
$request = array( $request = array(
"ids" => $ids, "ids" => $ids,
"delete-local-data" => $delete_local_data "delete-local-data" => $delete_local_data
@ -338,7 +359,9 @@ class TransmissionRPC
*/ */
public function move($ids, $target_location, $move_existing_data = true) public function move($ids, $target_location, $move_existing_data = true)
{ {
if ( !is_array( $ids ) ) $ids = array( $ids ); // Convert $ids to an array if only a single id was passed if (!is_array($ids)) {
$ids = array( $ids );
} // Convert $ids to an array if only a single id was passed
$request = array( $request = array(
"ids" => $ids, "ids" => $ids,
"location" => $target_location, "location" => $target_location,
@ -374,7 +397,9 @@ class TransmissionRPC
*/ */
public function rename($ids, $path, $name) public function rename($ids, $path, $name)
{ {
if ( !is_array( $ids ) ) $ids = array( $ids ); // Convert $id to an array if only a single id was passed if (!is_array($ids)) {
$ids = array( $ids );
} // Convert $id to an array if only a single id was passed
if (count($ids) !== 1) { if (count($ids) !== 1) {
throw new TransmissionRPCException('A single id is accepted', TransmissionRPCException::E_INVALIDARG); throw new TransmissionRPCException('A single id is accepted', TransmissionRPCException::E_INVALIDARG);
} }
@ -427,32 +452,44 @@ class TransmissionRPC
public function getStatusString($intstatus) public function getStatusString($intstatus)
{ {
if ($this->rpc_version < 14) { if ($this->rpc_version < 14) {
if( $intstatus == self::RPC_LT_14_TR_STATUS_CHECK_WAIT ) if ($intstatus == self::RPC_LT_14_TR_STATUS_CHECK_WAIT) {
return "Waiting to verify local files"; return "Waiting to verify local files";
if( $intstatus == self::RPC_LT_14_TR_STATUS_CHECK ) }
if ($intstatus == self::RPC_LT_14_TR_STATUS_CHECK) {
return "Verifying local files"; return "Verifying local files";
if( $intstatus == self::RPC_LT_14_TR_STATUS_DOWNLOAD ) }
if ($intstatus == self::RPC_LT_14_TR_STATUS_DOWNLOAD) {
return "Downloading"; return "Downloading";
if( $intstatus == self::RPC_LT_14_TR_STATUS_SEED ) }
if ($intstatus == self::RPC_LT_14_TR_STATUS_SEED) {
return "Seeding"; return "Seeding";
if( $intstatus == self::RPC_LT_14_TR_STATUS_STOPPED ) }
if ($intstatus == self::RPC_LT_14_TR_STATUS_STOPPED) {
return "Stopped"; return "Stopped";
}
} else { } else {
if( $intstatus == self::TR_STATUS_CHECK_WAIT ) if ($intstatus == self::TR_STATUS_CHECK_WAIT) {
return "Waiting to verify local files"; return "Waiting to verify local files";
if( $intstatus == self::TR_STATUS_CHECK ) }
if ($intstatus == self::TR_STATUS_CHECK) {
return "Verifying local files"; return "Verifying local files";
if( $intstatus == self::TR_STATUS_DOWNLOAD ) }
if ($intstatus == self::TR_STATUS_DOWNLOAD) {
return "Downloading"; return "Downloading";
if( $intstatus == self::TR_STATUS_SEED ) }
if ($intstatus == self::TR_STATUS_SEED) {
return "Seeding"; return "Seeding";
if( $intstatus == self::TR_STATUS_STOPPED ) }
if ($intstatus == self::TR_STATUS_STOPPED) {
return "Stopped"; return "Stopped";
if( $intstatus == self::TR_STATUS_SEED_WAIT ) }
if ($intstatus == self::TR_STATUS_SEED_WAIT) {
return "Queued for seeding"; return "Queued for seeding";
if( $intstatus == self::TR_STATUS_DOWNLOAD_WAIT ) }
if ($intstatus == self::TR_STATUS_DOWNLOAD_WAIT) {
return "Queued for download"; return "Queued for download";
} }
}
return "Unknown"; return "Unknown";
} }
@ -472,19 +509,27 @@ class TransmissionRPC
*/ */
protected function cleanRequestData($array) protected function cleanRequestData($array)
{ {
if ( !is_array( $array ) || count( $array ) == 0 ) return null; // Nothing to clean if (!is_array($array) || count($array) == 0) {
return null;
} // Nothing to clean
setlocale(LC_NUMERIC, 'en_US.utf8'); // Override the locale - if the system locale is wrong, then 12.34 will encode as 12,34 which is invalid JSON setlocale(LC_NUMERIC, 'en_US.utf8'); // Override the locale - if the system locale is wrong, then 12.34 will encode as 12,34 which is invalid JSON
foreach ( $array as $index => $value ) foreach ($array as $index => $value) {
{ if (is_object($value)) {
if( is_object( $value ) ) $array[$index] = $value->toArray(); // Convert objects to arrays so they can be JSON encoded $array[$index] = $value->toArray();
if( is_array( $value ) ) $array[$index] = $this->cleanRequestData( $value ); // Recursion } // Convert objects to arrays so they can be JSON encoded
if( empty( $value ) && $value !== 0 ) // Remove empty members if (is_array($value)) {
{ $array[$index] = $this->cleanRequestData($value);
} // Recursion
if (empty($value) && $value !== 0) { // Remove empty members
unset($array[$index]); unset($array[$index]);
continue; // Skip the rest of the tests - they may re-add the element. continue; // Skip the rest of the tests - they may re-add the element.
} }
if( is_numeric( $value ) ) $array[$index] = $value+0; // Force type-casting for proper JSON encoding (+0 is a cheap way to maintain int/float/etc) if (is_numeric($value)) {
if( is_bool( $value ) ) $array[$index] = ( $value ? 1 : 0); // Store boolean values as 0 or 1 $array[$index] = $value+0;
} // Force type-casting for proper JSON encoding (+0 is a cheap way to maintain int/float/etc)
if (is_bool($value)) {
$array[$index] = ($value ? 1 : 0);
} // Store boolean values as 0 or 1
if (is_string($value)) { if (is_string($value)) {
if (mb_detect_encoding($value, "auto") !== 'UTF-8') { if (mb_detect_encoding($value, "auto") !== 'UTF-8') {
$array[$index] = mb_convert_encoding($value, "UTF-8"); $array[$index] = mb_convert_encoding($value, "UTF-8");
@ -507,23 +552,26 @@ class TransmissionRPC
// Prepare and cast object to array // Prepare and cast object to array
$return_as_array = false; $return_as_array = false;
$array = $object; $array = $object;
if ( !is_array( $array ) ) $array = (array) $array; if (!is_array($array)) {
foreach ( $array as $index => $value ) $array = (array) $array;
{ }
if( is_array( $array[$index] ) || is_object( $array[$index] ) ) foreach ($array as $index => $value) {
{ if (is_array($array[$index]) || is_object($array[$index])) {
$array[$index] = $this->cleanResultObject($array[$index]); // Recursion $array[$index] = $this->cleanResultObject($array[$index]); // Recursion
} }
if ( strstr( $index, '-' ) ) if (strstr($index, '-')) {
{
$valid_index = str_replace('-', '_', $index); $valid_index = str_replace('-', '_', $index);
$array[$valid_index] = $array[$index]; $array[$valid_index] = $array[$index];
unset($array[$index]); unset($array[$index]);
$index = $valid_index; $index = $valid_index;
} }
// Might be an array, check index for digits, if so, an array should be returned // Might be an array, check index for digits, if so, an array should be returned
if ( ctype_digit( (string) $index ) ) { $return_as_array = true; } if (ctype_digit((string) $index)) {
if ( empty( $value ) ) unset( $array[$index] ); $return_as_array = true;
}
if (empty($value)) {
unset($array[$index]);
}
} }
// Return array cast to object // Return array cast to object
return $return_as_array ? $array : (object) $array; return $return_as_array ? $array : (object) $array;
@ -539,17 +587,21 @@ class TransmissionRPC
protected function request($method, $arguments = array()) protected function request($method, $arguments = array())
{ {
// Check the parameters // Check the parameters
if ( !is_scalar( $method ) ) if (!is_scalar($method)) {
throw new TransmissionRPCException('Method name has no scalar value', TransmissionRPCException::E_INVALIDARG); throw new TransmissionRPCException('Method name has no scalar value', TransmissionRPCException::E_INVALIDARG);
if ( !is_array( $arguments ) ) }
if (!is_array($arguments)) {
throw new TransmissionRPCException('Arguments must be given as array', TransmissionRPCException::E_INVALIDARG); throw new TransmissionRPCException('Arguments must be given as array', TransmissionRPCException::E_INVALIDARG);
}
$arguments = $this->cleanRequestData($arguments); // Sanitize input $arguments = $this->cleanRequestData($arguments); // Sanitize input
// Grab the X-Transmission-Session-Id if we don't have it already // Grab the X-Transmission-Session-Id if we don't have it already
if( !$this->session_id ) if (!$this->session_id) {
if( !$this->GetSessionID() ) if (!$this->GetSessionID()) {
throw new TransmissionRPCException('Unable to acquire X-Transmission-Session-Id', TransmissionRPCException::E_SESSIONID); throw new TransmissionRPCException('Unable to acquire X-Transmission-Session-Id', TransmissionRPCException::E_SESSIONID);
}
}
$data = array( $data = array(
'method' => $method, 'method' => $method,
@ -576,7 +628,9 @@ class TransmissionRPC
$content = curl_exec($ch); $content = curl_exec($ch);
curl_close($ch); curl_close($ch);
if (!$content) $content = json_encode(array('result' => 'failed')); if (!$content) {
$content = json_encode(array('result' => 'failed'));
}
return $this->return_as_array ? json_decode($content, true) : $this->cleanResultObject(json_decode($content)); // Return the sanitized result return $this->return_as_array ? json_decode($content, true) : $this->cleanResultObject(json_decode($content)); // Return the sanitized result
} }
/** /**
@ -587,8 +641,9 @@ class TransmissionRPC
*/ */
public function GetSessionID() public function GetSessionID()
{ {
if( !$this->url ) if (!$this->url) {
throw new TransmissionRPCException("Class must be initialized before GetSessionID() can be called.", TransmissionRPCException::E_INVALIDARG); throw new TransmissionRPCException("Class must be initialized before GetSessionID() can be called.", TransmissionRPCException::E_INVALIDARG);
}
// Setup the context // Setup the context
$contextopts = $this->default_context_opts; // Start with the defaults $contextopts = $this->default_context_opts; // Start with the defaults
@ -597,34 +652,40 @@ class TransmissionRPC
$this->session_id = null; $this->session_id = null;
// Setup authentication (if provided) // Setup authentication (if provided)
if ( $this->username && $this->password ) if ($this->username && $this->password) {
$contextopts['http']['header'] = sprintf("Authorization: Basic %s\r\n", base64_encode($this->username.':'.$this->password)); $contextopts['http']['header'] = sprintf("Authorization: Basic %s\r\n", base64_encode($this->username.':'.$this->password));
}
if( $this->debug ) echo "TRANSMISSIONRPC_DEBUG:: GetSessionID():: Stream context created with options:". if ($this->debug) {
echo "TRANSMISSIONRPC_DEBUG:: GetSessionID():: Stream context created with options:".
PHP_EOL . print_r($contextopts, true); PHP_EOL . print_r($contextopts, true);
}
$context = stream_context_create($contextopts); // Create the context for this request $context = stream_context_create($contextopts); // Create the context for this request
if ( ! $fp = @fopen( $this->url, 'r', false, $context ) ) // Open a filepointer to the data, and use fgets to get the result if (! $fp = @fopen($this->url, 'r', false, $context)) { // Open a filepointer to the data, and use fgets to get the result
throw new TransmissionRPCException('Unable to connect to '.$this->url, TransmissionRPCException::E_CONNECTION); throw new TransmissionRPCException('Unable to connect to '.$this->url, TransmissionRPCException::E_CONNECTION);
}
// Check the response (headers etc) // Check the response (headers etc)
$stream_meta = stream_get_meta_data($fp); $stream_meta = stream_get_meta_data($fp);
fclose($fp); fclose($fp);
if( $this->debug ) echo "TRANSMISSIONRPC_DEBUG:: GetSessionID():: Stream meta info: ". if ($this->debug) {
echo "TRANSMISSIONRPC_DEBUG:: GetSessionID():: Stream meta info: ".
PHP_EOL . print_r($stream_meta, true); PHP_EOL . print_r($stream_meta, true);
if( $stream_meta['timed_out'] ) }
if ($stream_meta['timed_out']) {
throw new TransmissionRPCException("Timed out connecting to {$this->url}", TransmissionRPCException::E_CONNECTION); throw new TransmissionRPCException("Timed out connecting to {$this->url}", TransmissionRPCException::E_CONNECTION);
if( substr( $stream_meta['wrapper_data'][0], 9, 3 ) == "401" ) }
if (substr($stream_meta['wrapper_data'][0], 9, 3) == "401") {
throw new TransmissionRPCException("Invalid username/password.", TransmissionRPCException::E_AUTHENTICATION); throw new TransmissionRPCException("Invalid username/password.", TransmissionRPCException::E_AUTHENTICATION);
elseif( substr( $stream_meta['wrapper_data'][0], 9, 3 ) == "409" ) // This is what we're hoping to find } elseif (substr($stream_meta['wrapper_data'][0], 9, 3) == "409") { // This is what we're hoping to find
{
// Loop through the returned headers and extract the X-Transmission-Session-Id // Loop through the returned headers and extract the X-Transmission-Session-Id
foreach( $stream_meta['wrapper_data'] as $header ) foreach ($stream_meta['wrapper_data'] as $header) {
{ if (strpos($header, 'X-Transmission-Session-Id: ') === 0) {
if( strpos( $header, 'X-Transmission-Session-Id: ' ) === 0 ) if ($this->debug) {
{ echo "TRANSMISSIONRPC_DEBUG:: GetSessionID():: Session-Id header: ".
if( $this->debug ) echo "TRANSMISSIONRPC_DEBUG:: GetSessionID():: Session-Id header: ".
PHP_EOL . print_r($header, true); PHP_EOL . print_r($header, true);
}
$this->session_id = trim(substr($header, 27)); $this->session_id = trim(substr($header, 27));
break; break;
} }
@ -698,11 +759,10 @@ class TransmissionRPCException extends Exception
public function __construct($message = null, $code = 0, Exception $previous = null) public function __construct($message = null, $code = 0, Exception $previous = null)
{ {
// PHP version 5.3.0 and above support Exception linking // PHP version 5.3.0 and above support Exception linking
if ( version_compare( PHP_VERSION, '5.3.0', '>=' ) ) if (version_compare(PHP_VERSION, '5.3.0', '>=')) {
parent::__construct($message, $code, $previous); parent::__construct($message, $code, $previous);
else } else {
parent::__construct($message, $code); parent::__construct($message, $code);
} }
} }
}
?>

@ -1,5 +1,6 @@
<?php <?php
use Curl\Curl; use Curl\Curl;
/** /**
* https://github.com/qbittorrent/qBittorrent/wiki/Web-API-Documentation * https://github.com/qbittorrent/qBittorrent/wiki/Web-API-Documentation
*/ */
@ -130,7 +131,9 @@ class qBittorrent
*/ */
public function add($torrent_url, $save_path = '', $extra_options = array()) public function add($torrent_url, $save_path = '', $extra_options = array())
{ {
if(!empty($save_path)) $extra_options['savepath'] = $save_path; if (!empty($save_path)) {
$extra_options['savepath'] = $save_path;
}
$extra_options['urls'] = $torrent_url; $extra_options['urls'] = $torrent_url;
#$extra_options['skip_checking'] = 'true'; //跳校验 #$extra_options['skip_checking'] = 'true'; //跳校验
// 关键 上传文件流 multipart/form-data【严格按照api文档编写】 // 关键 上传文件流 multipart/form-data【严格按照api文档编写】
@ -144,7 +147,9 @@ class qBittorrent
public function add_metainfo($torrent_metainfo, $save_path = '', $extra_options = array()) public function add_metainfo($torrent_metainfo, $save_path = '', $extra_options = array())
{ {
if(!empty($save_path)) $extra_options['savepath'] = $save_path; if (!empty($save_path)) {
$extra_options['savepath'] = $save_path;
}
$extra_options['torrents'] = $torrent_metainfo; $extra_options['torrents'] = $torrent_metainfo;
#$extra_options['skip_checking'] = 'true'; //跳校验 #$extra_options['skip_checking'] = 'true'; //跳校验
// 关键 上传文件流 multipart/form-data【严格按照api文档编写】 // 关键 上传文件流 multipart/form-data【严格按照api文档编写】
@ -250,7 +255,8 @@ class qBittorrent
* 拼接种子urls multipart/form-data * 拼接种子urls multipart/form-data
* https://github.com/qbittorrent/qBittorrent/wiki/Web-API-Documentation#add-new-torrent * https://github.com/qbittorrent/qBittorrent/wiki/Web-API-Documentation#add-new-torrent
*/ */
private function buildUrls($param){ private function buildUrls($param)
{
$this->delimiter = uniqid(); $this->delimiter = uniqid();
$eol = "\r\n"; $eol = "\r\n";
$data = ''; $data = '';
@ -267,7 +273,8 @@ class qBittorrent
* 拼接种子上传文件流 multipart/form-data * 拼接种子上传文件流 multipart/form-data
* https://github.com/qbittorrent/qBittorrent/wiki/Web-API-Documentation#add-new-torrent * https://github.com/qbittorrent/qBittorrent/wiki/Web-API-Documentation#add-new-torrent
*/ */
private function buildData($param){ private function buildData($param)
{
$this->delimiter = uniqid(); $this->delimiter = uniqid();
$eol = "\r\n"; $eol = "\r\n";
$data = ''; $data = '';

@ -29,7 +29,8 @@ define("UTORRENT_STATUS_STARTED", 1);
define("UTORRENT_STATUS_CHECKED", 2); define("UTORRENT_STATUS_CHECKED", 2);
define("UTORRENT_STATUS_START_AFTER_CHECK", 4); define("UTORRENT_STATUS_START_AFTER_CHECK", 4);
class uTorrent { class uTorrent
{
// class static variables // class static variables
private static $base = "%s/gui/%s"; private static $base = "%s/gui/%s";
@ -42,7 +43,8 @@ class uTorrent {
protected $guid; protected $guid;
// constructor // constructor
function __construct($host = "", $user = "", $pass = "") { public function __construct($host = "", $user = "", $pass = "")
{
$this->host = rtrim($host, '/'); $this->host = rtrim($host, '/');
$this->user = $user; $this->user = $user;
$this->pass = $pass; $this->pass = $pass;
@ -54,7 +56,8 @@ class uTorrent {
} }
// performs request // performs request
private function makeRequest($request, $decode = true, $options = array()) { private function makeRequest($request, $decode = true, $options = array())
{
$request = preg_replace('/^\?/', '?token='.$this->token . '&', $request); $request = preg_replace('/^\?/', '?token='.$this->token . '&', $request);
$ch = curl_init(); $ch = curl_init();
@ -71,12 +74,14 @@ class uTorrent {
} }
// implodes given parameter with glue, whether it is an array or not // implodes given parameter with glue, whether it is an array or not
private function paramImplode($glue, $param) { private function paramImplode($glue, $param)
{
return $glue.implode($glue, is_array($param) ? $param : array($param)); return $glue.implode($glue, is_array($param) ? $param : array($param));
} }
// gets token, returns true on success // gets token, returns true on success
private function getToken() { private function getToken()
{
$url = sprintf(self::$base, $this->host, 'token.html'); $url = sprintf(self::$base, $this->host, 'token.html');
$ch = curl_init(); $ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_URL, $url);
@ -101,7 +106,8 @@ class uTorrent {
} }
// returns the uTorrent build number // returns the uTorrent build number
public function getBuild(){ public function getBuild()
{
$json = $this->makeRequest("?"); $json = $this->makeRequest("?");
return $json['build']; return $json['build'];
} }
@ -109,13 +115,15 @@ class uTorrent {
// returns an array of files for the specified torrent hash // returns an array of files for the specified torrent hash
// TODO: // TODO:
// - (when implemented in API) allow multiple hashes to be specified // - (when implemented in API) allow multiple hashes to be specified
public function getFiles($hash) { public function getFiles($hash)
{
$json = $this->makeRequest("?action=getfiles&hash=".$hash); $json = $this->makeRequest("?action=getfiles&hash=".$hash);
return $json['files']; return $json['files'];
} }
// returns an array of all labels // returns an array of all labels
public function getLabels(){ public function getLabels()
{
$json = $this->makeRequest("?list=1"); $json = $this->makeRequest("?list=1");
return $json['label']; return $json['label'];
} }
@ -123,19 +131,22 @@ class uTorrent {
// returns an array of the properties for the specified torrent hash // returns an array of the properties for the specified torrent hash
// TODO: // TODO:
// - (when implemented in API) allow multiple hashes to be specified // - (when implemented in API) allow multiple hashes to be specified
public function getProperties($hash) { public function getProperties($hash)
{
$json = $this->makeRequest("?action=getprops&hash=".$hash); $json = $this->makeRequest("?action=getprops&hash=".$hash);
return $json['props']; return $json['props'];
} }
// returns an array of all settings // returns an array of all settings
public function getSettings() { public function getSettings()
{
$json = $this->makeRequest("?action=getsettings"); $json = $this->makeRequest("?action=getsettings");
return $json['settings']; return $json['settings'];
} }
// returns an array of all torrent jobs and related information // returns an array of all torrent jobs and related information
public function getTorrents() { public function getTorrents()
{
$json = $this->makeRequest("?list=1"); $json = $this->makeRequest("?list=1");
return $json['torrents']; return $json['torrents'];
} }
@ -144,7 +155,8 @@ class uTorrent {
* Get all the RSS favourites/filters * Get all the RSS favourites/filters
* @return model\Filter[] * @return model\Filter[]
*/ */
public function getRSSFilters() { public function getRSSFilters()
{
$json = $this->makeRequest("?list=1"); $json = $this->makeRequest("?list=1");
$filters = array(); $filters = array();
foreach ($json['rssfilters'] as $filter) { foreach ($json['rssfilters'] as $filter) {
@ -157,7 +169,8 @@ class uTorrent {
* Update an RSS filter as retrieved from getRSSFilters * Update an RSS filter as retrieved from getRSSFilters
* @param \uTorrent\model\Filter $filter * @param \uTorrent\model\Filter $filter
*/ */
public function setRSSFilter(model\Filter $filter) { public function setRSSFilter(model\Filter $filter)
{
$request = array_merge(array('action' => 'filter-update'), $filter->toParams()); $request = array_merge(array('action' => 'filter-update'), $filter->toParams());
return $this->makeRequest('?'.http_build_query($request)); return $this->makeRequest('?'.http_build_query($request));
} }
@ -168,7 +181,8 @@ class uTorrent {
* @param \uTorrent\model\Filter $filter * @param \uTorrent\model\Filter $filter
* @return int ID of the new filter * @return int ID of the new filter
*/ */
public function addRSSFilter(model\Filter $filter) { public function addRSSFilter(model\Filter $filter)
{
$filter->filterId = -1; $filter->filterId = -1;
$resp = $this->setRSSFilter($filter); $resp = $this->setRSSFilter($filter);
if (!empty($resp['filter_ident'])) { if (!empty($resp['filter_ident'])) {
@ -179,77 +193,90 @@ class uTorrent {
} }
// returns true if WebUI server is online and enabled, false otherwise // returns true if WebUI server is online and enabled, false otherwise
public function is_online() { public function is_online()
{
return is_array($this->makeRequest("?")); return is_array($this->makeRequest("?"));
} }
// sets the properties for the specified torrent hash // sets the properties for the specified torrent hash
// TODO: // TODO:
// - allow multiple hashes, properties, and values to be set simultaneously // - allow multiple hashes, properties, and values to be set simultaneously
public function setProperties($hash, $property, $value) { public function setProperties($hash, $property, $value)
{
$this->makeRequest("?action=setprops&hash=".$hash."&s=".$property."&v=".$value, false); $this->makeRequest("?action=setprops&hash=".$hash."&s=".$property."&v=".$value, false);
} }
// sets the priorities for the specified files in the specified torrent hash // sets the priorities for the specified files in the specified torrent hash
public function setPriority($hash, $files, $priority) { public function setPriority($hash, $files, $priority)
{
$this->makeRequest("?action=setprio&hash=".$hash."&p=".$priority.$this->paramImplode("&f=", $files), false); $this->makeRequest("?action=setprio&hash=".$hash."&p=".$priority.$this->paramImplode("&f=", $files), false);
} }
// sets the settings // sets the settings
// TODO: // TODO:
// - allow multiple settings and values to be set simultaneously // - allow multiple settings and values to be set simultaneously
public function setSetting($setting, $value) { public function setSetting($setting, $value)
{
$this->makeRequest("?action=setsetting&s=".$setting."&v=".$value, false); $this->makeRequest("?action=setsetting&s=".$setting."&v=".$value, false);
} }
// add a file to the list // add a file to the list
public function torrentAdd($filename, &$estring = false) { public function torrentAdd($filename, &$estring = false)
{
$split = explode(":", $filename, 2); $split = explode(":", $filename, 2);
if (count($split) > 1 && (stristr("|http|https|file|magnet|", "|".$split[0]."|") !== false)) { if (count($split) > 1 && (stristr("|http|https|file|magnet|", "|".$split[0]."|") !== false)) {
$this->makeRequest("?action=add-url&s=".urlencode($filename), false); $this->makeRequest("?action=add-url&s=".urlencode($filename), false);
} } elseif (file_exists($filename)) {
elseif (file_exists($filename)) {
$json = $this->makeRequest("?action=add-file", true, array(CURLOPT_POSTFIELDS => array("torrent_file" => "@".realpath($filename)))); $json = $this->makeRequest("?action=add-file", true, array(CURLOPT_POSTFIELDS => array("torrent_file" => "@".realpath($filename))));
if (isset($json['error'])) { if (isset($json['error'])) {
if ($estring !== false) $estring = $json['error']; if ($estring !== false) {
$estring = $json['error'];
}
return false; return false;
} }
return true; return true;
} else {
if ($estring !== false) {
$estring = "File doesn't exist!";
} }
else {
if ($estring !== false) $estring = "File doesn't exist!";
return false; return false;
} }
} }
// force start the specified torrent hashes // force start the specified torrent hashes
public function torrentForceStart($hash) { public function torrentForceStart($hash)
{
$this->makeRequest("?action=forcestart".$this->paramImplode("&hash=", $hash), false); $this->makeRequest("?action=forcestart".$this->paramImplode("&hash=", $hash), false);
} }
// pause the specified torrent hashes // pause the specified torrent hashes
public function torrentPause($hash) { public function torrentPause($hash)
{
$this->makeRequest("?action=pause".$this->paramImplode("&hash=", $hash), false); $this->makeRequest("?action=pause".$this->paramImplode("&hash=", $hash), false);
} }
// recheck the specified torrent hashes // recheck the specified torrent hashes
public function torrentRecheck($hash) { public function torrentRecheck($hash)
{
$this->makeRequest("?action=recheck".$this->paramImplode("&hash=", $hash), false); $this->makeRequest("?action=recheck".$this->paramImplode("&hash=", $hash), false);
} }
// start the specified torrent hashes // start the specified torrent hashes
public function torrentStart($hash) { public function torrentStart($hash)
{
$this->makeRequest("?action=start".$this->paramImplode("&hash=", $hash), false); $this->makeRequest("?action=start".$this->paramImplode("&hash=", $hash), false);
} }
// stop the specified torrent hashes // stop the specified torrent hashes
public function torrentStop($hash) { public function torrentStop($hash)
{
$this->makeRequest("?action=stop".$this->paramImplode("&hash=", $hash), false); $this->makeRequest("?action=stop".$this->paramImplode("&hash=", $hash), false);
} }
// remove the specified torrent hashes (and data, if $data is set to true) // remove the specified torrent hashes (and data, if $data is set to true)
public function torrentRemove($hash, $data = false) { public function torrentRemove($hash, $data = false)
{
$this->makeRequest("?action=".($data ? "removedata" : "remove").$this->paramImplode("&hash=", $hash), false); $this->makeRequest("?action=".($data ? "removedata" : "remove").$this->paramImplode("&hash=", $hash), false);
} }
} }

Loading…
Cancel
Save