Browse Source

提交代码

xs_yanfei 6 years ago
parent
commit
8edfeb916a
100 changed files with 15890 additions and 0 deletions
  1. 171 0
      bin/build_sqls.php
  2. 295 0
      bin/build_test.php
  3. 8 0
      bin/phalapi-buildsqls
  4. 9 0
      bin/phalapi-buildtest
  5. 34 0
      composer.json
  6. 2151 0
      composer.lock
  7. BIN
      composer.phar
  8. 65 0
      config/app.php
  9. 32 0
      config/coin.php
  10. 50 0
      config/dbs.php
  11. 53 0
      config/di.php
  12. 30 0
      config/sys.php
  13. 13 0
      data/phalapi.sql
  14. 9 0
      language/de/common.php
  15. 6 0
      language/en/common.php
  16. 7 0
      language/fr/common.php
  17. 14 0
      language/zh_cn/common.php
  18. 6 0
      language/zh_tw/common.php
  19. 13 0
      public/.htaccess
  20. 1 0
      public/.idea/.name
  21. 3 0
      public/.idea/copyright/profiles_settings.xml
  22. 6 0
      public/.idea/encodings.xml
  23. 16 0
      public/.idea/misc.xml
  24. 8 0
      public/.idea/modules.xml
  25. 8 0
      public/.idea/public.iml
  26. 6 0
      public/.idea/vcs.xml
  27. 146 0
      public/.idea/workspace.xml
  28. 41 0
      public/docs.php
  29. 0 0
      public/eos.txt
  30. 7 0
      public/examples/upload.html
  31. BIN
      public/favicon.ico
  32. 10 0
      public/index.php
  33. 28 0
      public/init.php
  34. 33 0
      public/test.php
  35. 130 0
      runtime/log/201809/20180903.log
  36. 140 0
      runtime/log/201809/20180904.log
  37. 95 0
      runtime/log/201809/20180905.log
  38. 0 0
      runtime/log/201809/20180906.log
  39. 1120 0
      runtime/log/201809/20180908.log
  40. 40 0
      runtime/log/201809/20180909.log
  41. 0 0
      runtime/log/201809/20180910.log
  42. 0 0
      runtime/log/201809/20180912.log
  43. 8 0
      runtime/log/201809/20180913.log
  44. 0 0
      runtime/log/201809/20180914.log
  45. 107 0
      runtime/log/201809/20180915.log
  46. 24 0
      runtime/log/201809/20180916.log
  47. 67 0
      runtime/log/201809/20180917.log
  48. 0 0
      runtime/log/201809/20180918.log
  49. 0 0
      runtime/log/201809/20180919.log
  50. 0 0
      runtime/log/201809/20180920.log
  51. 9 0
      runtime/log/201809/20180926.log
  52. 0 0
      runtime/log/201809/20180927.log
  53. 0 0
      runtime/log/201810/20181012.log
  54. 193 0
      sdk/C_Sharp/PhalApiClient/PhalApiClient.cs
  55. 24 0
      sdk/C_Sharp/PhalApiClient/PhalApiClientFilter.cs
  56. 25 0
      sdk/C_Sharp/PhalApiClient/PhalApiClientParser.cs
  57. 24 0
      sdk/C_Sharp/PhalApiClient/PhalApiClientParserJson.cs
  58. 51 0
      sdk/C_Sharp/PhalApiClient/PhalApiClientResponse.cs
  59. 144 0
      sdk/Go/PhalApiClient/PhalApiClient.go
  60. 22 0
      sdk/Go/main.go
  61. 175 0
      sdk/JAVA/README.md
  62. 218 0
      sdk/JAVA/net/phalapi/sdk/PhalApiClient.java
  63. 19 0
      sdk/JAVA/net/phalapi/sdk/PhalApiClientFilter.java
  64. 17 0
      sdk/JAVA/net/phalapi/sdk/PhalApiClientParser.java
  65. 24 0
      sdk/JAVA/net/phalapi/sdk/PhalApiClientParserJson.java
  66. 45 0
      sdk/JAVA/net/phalapi/sdk/PhalApiClientResponse.java
  67. 130 0
      sdk/JS/demo.html
  68. 105 0
      sdk/JS/js/SDK/PhalApi.js
  69. 4 0
      sdk/JS/js/SDK/jquery.min.js
  70. 14 0
      sdk/Objective-C/PhalApiClient/AFNPhalApiClient/AFNPhalApiClient.h
  71. 101 0
      sdk/Objective-C/PhalApiClient/AFNPhalApiClient/AFNPhalApiClient.m
  72. 70 0
      sdk/Objective-C/PhalApiClient/AFNPhalApiClient/Vendor/AFNetworking-2.6.1/AFHTTPRequestOperation.h
  73. 206 0
      sdk/Objective-C/PhalApiClient/AFNPhalApiClient/Vendor/AFNetworking-2.6.1/AFHTTPRequestOperation.m
  74. 326 0
      sdk/Objective-C/PhalApiClient/AFNPhalApiClient/Vendor/AFNetworking-2.6.1/AFHTTPRequestOperationManager.h
  75. 284 0
      sdk/Objective-C/PhalApiClient/AFNPhalApiClient/Vendor/AFNetworking-2.6.1/AFHTTPRequestOperationManager.m
  76. 253 0
      sdk/Objective-C/PhalApiClient/AFNPhalApiClient/Vendor/AFNetworking-2.6.1/AFHTTPSessionManager.h
  77. 323 0
      sdk/Objective-C/PhalApiClient/AFNPhalApiClient/Vendor/AFNetworking-2.6.1/AFHTTPSessionManager.m
  78. 207 0
      sdk/Objective-C/PhalApiClient/AFNPhalApiClient/Vendor/AFNetworking-2.6.1/AFNetworkReachabilityManager.h
  79. 262 0
      sdk/Objective-C/PhalApiClient/AFNPhalApiClient/Vendor/AFNetworking-2.6.1/AFNetworkReachabilityManager.m
  80. 46 0
      sdk/Objective-C/PhalApiClient/AFNPhalApiClient/Vendor/AFNetworking-2.6.1/AFNetworking.h
  81. 142 0
      sdk/Objective-C/PhalApiClient/AFNPhalApiClient/Vendor/AFNetworking-2.6.1/AFSecurityPolicy.h
  82. 311 0
      sdk/Objective-C/PhalApiClient/AFNPhalApiClient/Vendor/AFNetworking-2.6.1/AFSecurityPolicy.m
  83. 344 0
      sdk/Objective-C/PhalApiClient/AFNPhalApiClient/Vendor/AFNetworking-2.6.1/AFURLConnectionOperation.h
  84. 792 0
      sdk/Objective-C/PhalApiClient/AFNPhalApiClient/Vendor/AFNetworking-2.6.1/AFURLConnectionOperation.m
  85. 473 0
      sdk/Objective-C/PhalApiClient/AFNPhalApiClient/Vendor/AFNetworking-2.6.1/AFURLRequestSerialization.h
  86. 1425 0
      sdk/Objective-C/PhalApiClient/AFNPhalApiClient/Vendor/AFNetworking-2.6.1/AFURLRequestSerialization.m
  87. 311 0
      sdk/Objective-C/PhalApiClient/AFNPhalApiClient/Vendor/AFNetworking-2.6.1/AFURLResponseSerialization.h
  88. 825 0
      sdk/Objective-C/PhalApiClient/AFNPhalApiClient/Vendor/AFNetworking-2.6.1/AFURLResponseSerialization.m
  89. 554 0
      sdk/Objective-C/PhalApiClient/AFNPhalApiClient/Vendor/AFNetworking-2.6.1/AFURLSessionManager.h
  90. 1171 0
      sdk/Objective-C/PhalApiClient/AFNPhalApiClient/Vendor/AFNetworking-2.6.1/AFURLSessionManager.m
  91. 131 0
      sdk/Objective-C/PhalApiClient/PhalApiClient.h
  92. 226 0
      sdk/Objective-C/PhalApiClient/PhalApiClient.m
  93. 22 0
      sdk/Objective-C/PhalApiClient/PhalApiClientFilter.h
  94. 24 0
      sdk/Objective-C/PhalApiClient/PhalApiClientFilter.m
  95. 97 0
      sdk/Objective-C/PhalApiClient/README.md
  96. 112 0
      sdk/Objective-C/XSHttpTool/AFNetworking/AFDownloadRequestOperation/AFDownloadRequestOperation.h
  97. 327 0
      sdk/Objective-C/XSHttpTool/AFNetworking/AFDownloadRequestOperation/AFDownloadRequestOperation.m
  98. 66 0
      sdk/Objective-C/XSHttpTool/AFNetworking/AFHTTPRequestOperation.h
  99. 206 0
      sdk/Objective-C/XSHttpTool/AFNetworking/AFHTTPRequestOperation.m
  100. 0 0
      sdk/Objective-C/XSHttpTool/AFNetworking/AFHTTPRequestOperationManager.h

+ 171 - 0
bin/build_sqls.php

@@ -0,0 +1,171 @@
+<?php
+/**
+ * 根据配置自动生成SQL建表语句
+ *
+ * @author dogstar <chanzonghuang@gmail.com> 2015-02-04 
+ */
+
+define('CUR_PATH', dirname(__FILE__));
+
+if ($argc < 3) {
+    echo "\n";
+    echo colorfulString("Usage:\n", 'WARNING');
+    echo "   $argv[0] <dbs_config> <table> [engine] [sqls_folder]\n";
+    echo "\n";
+
+    echo colorfulString("Options:\n", 'WARNING');
+    echo colorfulString('    dbs_config', 'NOTE'), "        Require. Path to ./Config/dbs.php\n";
+    echo colorfulString('    table', 'NOTE'), "             Require. Table name\n";
+    echo colorfulString('    engine', 'NOTE'), "            NOT require. Database engine, default is Innodb\n";
+    echo colorfulString('    sqls_folder', 'NOTE'), "       NOT require. Data foler, default is API_ROOT/data";
+    echo "\n";
+
+    echo colorfulString("Demo:\n", 'WARNING');
+    echo "    $argv[0] ../Config/dbs.php User\n";
+    echo "\n";
+
+    echo colorfulString("Tips:\n", 'WARNING');
+    echo "    This will output the sql directly, enjoy yourself!\n";
+    echo "\n";
+
+    //echo "\n", implode("\n", array_keys($dbsConfig['tables'])), "\n\n";
+    exit(1);
+}
+
+$dbsConfigFile = trim($argv[1]);
+$tableName = trim($argv[2]);
+$engine = isset($argv[3]) ? $argv[3] : 'InnoDB';
+$dataFoler = isset($argv[4]) ? $argv[4] : CUR_PATH . '/../data'; 
+
+if (!file_exists($dbsConfigFile)) {
+    echo colorfulString("Error: file $dbsConfigFile not exists!\n\n", 'FAILURE');
+    exit();
+}
+
+$dbsConfig = include($dbsConfigFile);
+
+if (empty($dbsConfig) || empty($dbsConfig['servers']) || empty($dbsConfig['tables'])
+    || !is_array($dbsConfig['servers']) || !is_array($dbsConfig['tables'])) {
+        echo colorfulString("Error: db config is incorrect, it should be format as: 
+
+<?php
+
+return array(
+    /**
+     * avaiable db servers
+     */
+
+    'servers' => array(
+        'db_X' => array(
+            'host'      => 'localhost',             //数据库域名
+            'name'      => 'phalapi',               //数据库名字
+            'user'      => 'root',                  //数据库用户名
+            'password'  => '',	                    //数据库密码
+            'port'      => '3306',                  //数据库端口
+            'charset'   => 'UTF8',                  //数据库字符集
+        ),
+    ),
+    /**
+     * custom table map
+     */
+    'tables' => array(
+        'demo' => array(
+            'prefix' => 'weili_',
+            'key' => 'id',
+            'map' => array(
+                array('start' => 0, 'end' => 2, 'db' => 'db_X'),
+            ),
+        ),
+    ),
+);
+
+", 'FAILURE');
+    exit();
+    }
+
+$tableMap = isset($dbsConfig['tables'][$tableName]) ? $dbsConfig['tables'][$tableName] : $dbsConfig['tables']['__default__'];
+if (empty($tableMap)) {
+    echo colorfulString("Error: no table map for $tableName !\n\n", 'FAILURE');
+    exit();
+}
+
+$tableMap['prefix'] = isset($tableMap['prefix']) ? trim($tableMap['prefix']) : '';
+$tableMap['key'] = isset($tableMap['key']) ? trim($tableMap['key']) : 'id';
+$tableMap['map'] = isset($tableMap['map']) ? $tableMap['map'] : array();
+
+if (empty($tableMap['map'])) {
+    echo colorfulString("Error: miss map for table $tableName !\n\n", 'FAILURE');
+    exit();
+}
+
+$sqlFilePath = $dataFoler . '/' . $tableName . '.sql';
+if (!file_exists($sqlFilePath)) {
+    echo colorfulString("Error: sql file $sqlFilePath not exists!\n\n", 'FAILURE');
+    exit();
+}
+
+$sqlContent = file_get_contents($sqlFilePath);
+$sqlContent = trim($sqlContent);
+
+$outputSql = '';
+
+foreach ($tableMap['map'] as $mapItem) {
+    $dbName = isset($mapItem['db']) ? $mapItem['db'] : 'db';
+    if (!isset($dbsConfig['servers'][$dbName])) {
+        echo colorfulString("Error: no such db server as db = $dbName !\n\n", 'FAILURE');
+        exit();
+    }
+
+    $outputSql .= "
+/**
+ * DB: {$dbsConfig['servers'][$dbName]['host']}  {$dbsConfig['servers'][$dbName]['name']}
+ */
+";
+
+    $charset = isset($dbsConfig['servers'][$dbName]['charset']) 
+        ? $dbsConfig['servers'][$dbName]['charset'] : 'utf8';
+
+    if (isset($mapItem['start']) && isset($mapItem['end'])) {
+        for ($i = $mapItem['start']; $i <= $mapItem['end']; $i ++) {
+            $outputSql .= genSql(
+                $tableMap['prefix'] . $tableName . '_' . $i, 
+                $tableMap['key'], 
+                $sqlContent, 
+                $engine,
+                $charset
+            );
+        }
+    } else {
+        $outputSql .= genSql($tableMap['prefix'] . $tableName, $tableMap['key'], $sqlContent, $engine, $charset);
+    }
+}
+
+
+echo $outputSql;
+
+function colorfulString($text, $type = NULL) {
+    $colors = array(
+        'WARNING'   => '1;33',
+        'NOTE'      => '1;36',
+        'SUCCESS'   => '1;32',
+        'FAILURE'   => '1;35',
+    );
+
+    if (empty($type) || !isset($colors[$type])){
+        return $text;
+    }
+
+    return "\033[" . $colors[$type] . "m" . $text . "\033[0m";
+}
+
+function genSql($tableName, $tableKey, $sqlContent, $engine, $charset) {
+    return sprintf("
+CREATE TABLE `%s` (
+    `%s` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
+    %s
+    `ext_data` text COMMENT 'json data here',
+     PRIMARY KEY (`%s`)
+ ) ENGINE=%s DEFAULT CHARSET=%s;
+            
+", $tableName, $tableKey, $sqlContent, $tableKey, $engine, $charset);
+}

+ 295 - 0
bin/build_test.php

@@ -0,0 +1,295 @@
+<?php
+/**
+ * 单元测试骨架代码自动生成脚本
+ * 主要是针对当前项目系列生成相应的单元测试代码,提高开发效率
+ *
+ * 用法:
+ * Usage: php ./build_test.php <file_path> <class_name> [bootstrap] [author = dogstar]
+ *
+ * 1、针对全部public的函数进行单元测试
+ * 2、可根据@testcase注释自动生成测试用例
+ *
+ * 备注:另可使用phpunit-skelgen进行骨架代码生成
+ *
+ * @author: dogstar 20170708
+ * @version: 5.1.1
+ */
+
+if ($argc < 3) {
+    echo "\n";
+    echo colorfulString("Usage:\n", 'WARNING');
+    echo "    php $argv[0] <file_path> <class_name> [bootstrap] [author]\n";
+    echo "\n";
+
+    echo colorfulString("Options:\n", 'WARNING');
+    echo colorfulString('    file_path', 'NOTE'), "         Require. Path to the PHP source code file\n";
+    echo colorfulString('    class_name', 'NOTE'), "        Require. The class name need to be tested\n";
+    echo colorfulString('    bootstrap', 'NOTE'), "         NOT require. Path to the bootsrap file, usually is test_env.php\n";
+    echo colorfulString('    author', 'NOTE'), "            NOT require. Your great name here, default is dogstar\n";
+    echo "\n";
+
+    echo colorfulString("Demo:\n", 'WARNING');
+    echo "    $argv[0] ./Demo.php Demo > Demo_Test.php\n";
+    echo "    $argv[0] ./Demo.php Demo > Demo_Test.php\n";
+    echo "    $argv[0] ./src/Request.php PhalApi\\\\Reqeust > Request_Test.php\n";
+    echo "\n";
+
+    echo colorfulString("Tips:\n", 'WARNING');
+    echo "    This will output the code directly, you can save them to test file like with _Test.php suffix.\n";
+    echo "\n";
+
+    die();
+}
+
+$filePath = $argv[1];
+$className = $argv[2];
+$bootstrap = isset($argv[3]) ? $argv[3] : null;
+$author = isset($argv[4]) ? $argv[4] : 'dogstar';
+
+// 尝试加载composer autoload
+$autoloadFiles = array(
+    dirname(__FILE__) . '/../vendor/autoload.php',
+    dirname(__FILE__) . '/../../../vendor/autoload.php',
+);
+foreach ($autoloadFiles as $file) {
+    if (file_exists($file)) {
+        require_once $file;
+    }
+}
+
+// 引入启动文件
+if (!empty($bootstrap)) {
+    require_once $bootstrap;
+}
+
+// 引入源代码
+require_once $filePath;
+
+if (!class_exists($className)) {
+    echo colorfulString("Error: cannot find class($className). \n\n", 'FAILURE');
+    die();
+}
+
+$reflector = new ReflectionClass($className);
+
+$methods = $reflector->getMethods(ReflectionMethod::IS_PUBLIC);
+
+date_default_timezone_set('Asia/Shanghai');
+$objName = lcfirst(str_replace(array('_', '\\'), array('', ''), $className));
+
+/** ------------------- 生成通用的单元测试代码 ------------------ **/
+
+$code = "<?php
+
+";
+
+if (file_exists(dirname(__FILE__) . '/test_env.php')) {
+    $code .= "require_once dirname(__FILE__) . '/bootstrap.php';
+";
+} else {
+    $code .= "//require_once dirname(__FILE__) . '/bootstrap.php';
+";
+}
+
+$initWay = "new $className()";
+if (method_exists($className, '__construct')) {
+    $constructMethod = new ReflectionMethod($className, '__construct');
+    if (!$constructMethod->isPublic()) {
+        if (is_callable(array($className, 'getInstance'))) {
+            $initWay = "$className::getInstance()";
+        } else if(is_callable(array($className, 'newInstance'))) {
+            $initWay = "$className::newInstance()";
+        } else {
+            $initWay = 'NULL';
+        }
+    }
+}
+
+$code .= "
+if (!class_exists('" . (strpos($className, '\\') !== false ? str_replace('\\', '\\\\', $className) : $className) . "')) {
+    require dirname(__FILE__) . '/$filePath';
+}
+
+/**
+ * PhpUnderControl_" . str_replace('_', '', $className) . "_Test
+ *
+ * 针对 $filePath $className 类的PHPUnit单元测试
+ *
+ * @author: $author " . date('Ymd') . "
+ */
+
+class PhpUnderControl_" . str_replace(array('_', '\\'), array('', ''), $className) . "_Test extends \PHPUnit_Framework_TestCase
+{
+    public \$$objName;
+
+    protected function setUp()
+    {
+        parent::setUp();
+
+        \$this->$objName = $initWay;
+    }
+
+    protected function tearDown()
+    {
+        // 输出本次单元测试所执行的SQL语句
+        // var_dump(\PhalApi\DI()->tracer->getSqls());
+
+        // 输出本次单元测试所涉及的追踪埋点
+        // var_dump(\PhalApi\DI()->tracer->getSqls());
+    }
+
+";
+
+foreach ($methods as $method) {
+    if($method->class != $className) continue;
+
+    $fun = $method->name;
+    $Fun = ucfirst($fun);
+
+    if (strlen($Fun) > 2 && substr($Fun, 0, 2) == '__') continue;
+
+    $rMethod = new ReflectionMethod($className, $method->name);
+    $params = $rMethod->getParameters();
+    $isStatic = $rMethod->isStatic();
+    $isConstructor = $rMethod->isConstructor();
+
+    if($isConstructor) continue;
+
+    $initParamStr = '';
+    $callParamStr = '';
+    foreach ($params as $param) {
+        $default = '';
+
+        $rp = new ReflectionParameter(array($className, $fun), $param->name);
+        if ($rp->isOptional()) {
+            $default = $rp->getDefaultValue();
+        }
+        if (is_string($default)) {
+            $default = "'$default'";
+        } else if (is_array($default)) {
+            $default = var_export($default, true);
+        } else if (is_bool($default)) {
+            $default = $default ? 'true' : 'false';
+        } else if ($default === null) {
+            $default = 'null';
+        } else {
+            $default = "''";
+        }
+
+        $initParamStr .= "
+        \$" . $param->name . " = $default;";
+        $callParamStr .= '$' . $param->name . ', ';
+    }
+    $callParamStr = empty($callParamStr) ? $callParamStr : substr($callParamStr, 0, -2);
+
+    /** ------------------- 根据@return对结果类型的简单断言 ------------------ **/
+    $returnAssert = '';
+
+    $docComment = $rMethod->getDocComment();
+    $docCommentArr = explode("\n", $docComment);
+    foreach ($docCommentArr as $comment) {
+        if (strpos($comment, '@return') == false) {
+            continue;
+        }
+        $returnCommentArr = explode(' ', strrchr($comment, '@return'));
+        if (count($returnCommentArr) >= 2) {
+            switch (strtolower($returnCommentArr[1])) {
+            case 'bool':
+            case 'boolean':
+                $returnAssert = '$this->assertTrue(is_bool($rs));';
+                break;
+            case 'int':
+                $returnAssert = '$this->assertTrue(is_int($rs));';
+                break;
+            case 'integer':
+                $returnAssert = '$this->assertTrue(is_integer($rs));';
+                break;
+            case 'string':
+                $returnAssert = '$this->assertTrue(is_string($rs));';
+                break;
+            case 'object':
+                $returnAssert = '$this->assertTrue(is_object($rs));';
+                break;
+            case 'array':
+                $returnAssert = '$this->assertTrue(is_array($rs));';
+                break;
+            case 'float':
+                $returnAssert = '$this->assertTrue(is_float($rs));';
+                break;
+            }
+
+            break;
+        }
+    }
+
+    /** ------------------- 基本的单元测试代码生成 ------------------ **/
+    $code .= "
+    /**
+     * @group test$Fun
+     */ 
+    public function test$Fun()
+    {"
+    . (empty($initParamStr) ? '' : "$initParamStr\n") 
+    . "\n        "
+    . ($isStatic ? "\$rs = $className::$fun($callParamStr);" : "\$rs = \$this->$objName->$fun($callParamStr);") 
+    . (empty($returnAssert) ? '' : "\n\n        " . $returnAssert . "\n") 
+    . "
+    }
+";
+
+    /** ------------------- 根据@testcase 生成测试代码 ------------------ **/
+    $caseNum = 0;
+    foreach ($docCommentArr as $comment) {
+        if (strpos($comment, '@testcase') == false) {
+            continue;
+        }
+
+        $returnCommentArr = explode(' ', strrchr($comment, '@testcase'));
+        if (count($returnCommentArr) > 1) {
+            $expRs = $returnCommentArr[1];
+
+            //去掉@testcase和期望的结果
+            array_shift($returnCommentArr);
+            array_shift($returnCommentArr);
+
+            $callParamStrInCase = !empty($returnCommentArr) ? implode(' ', $returnCommentArr) : '';
+
+            $code .= "
+    /**
+     * @group test$Fun
+     */ 
+    public function test{$Fun}Case{$caseNum}()
+    {"
+        . "\n        "
+        . ($isStatic ? "\$rs = $className::$fun($callParamStrInCase);" : "\$rs = \$this->$objName->$fun($callParamStrInCase);") 
+        . "\n\n        \$this->assertEquals({$expRs}, \$rs);" 
+        . "
+    }
+";
+            $caseNum ++;
+
+        }
+    }
+}
+
+$code .= "
+}";
+
+echo $code;
+echo "\n";
+
+function colorfulString($text, $type = NULL) {
+    $colors = array(
+        'WARNING'   => '1;33',
+        'NOTE'      => '1;36',
+        'SUCCESS'   => '1;32',
+        'FAILURE'   => '1;35',
+    );
+
+    if (empty($type) || !isset($colors[$type])){
+        return $text;
+    }
+
+    return "\033[" . $colors[$type] . "m" . $text . "\033[0m";
+}
+

+ 8 - 0
bin/phalapi-buildsqls

@@ -0,0 +1,8 @@
+#!/usr/bin/env php
+<?php
+/**
+ * chmod +x ./phalapi-buildsqls
+ * ln -s /path/to/phalapi-buildsqls /usr/bin/phalapi-buildsqls
+ */
+require_once dirname(__FILE__) . '/build_sqls.php';
+

+ 9 - 0
bin/phalapi-buildtest

@@ -0,0 +1,9 @@
+#!/usr/bin/env php
+<?php
+/**
+ * chmod +x ./phalapi-buildtest
+ * ln -s /path/to/phalapi-buildtest /usr/bin/phalapi-buildtest
+ */
+
+require_once dirname(__FILE__) . '/build_test.php';
+

+ 34 - 0
composer.json

@@ -0,0 +1,34 @@
+{
+    "name": "phalapi/phalapi",
+    "description": "PhalApi v2.x,一个PHP轻量级开源接口框架,致力于快速开发接口服务。",
+    "type": "project",
+    "keywords": ["api"],
+    "homepage": "http://www.phalapi.net",
+    "license" : "GPL-3.0+",
+    "minimum-stability": "dev",
+    "authors": [
+        {
+            "name": "Dogstar Huang",
+            "email": "chanzonghuang@gmail.com",
+            "homepage" : "http://my.oschina.net/dogstar",
+            "role": "Developer"
+        }
+    ],
+    "require": {
+        "php": ">=5.3.3",
+        "phalapi/kernal": "2.2.*",
+        "phalapi/qrcode": "dev-master",
+        "phalapi/task": "dev-master",
+        "zulucrypto/stellar-api": "dev-master",
+        "phpninjas/mnemonics": "dev-master"
+    },
+    "autoload": {
+        "files": [
+            "src/app/functions.php"
+            ],
+        "psr-4": {
+            "App\\": "src/app"
+        }
+    }
+
+}

File diff suppressed because it is too large
+ 2151 - 0
composer.lock


BIN
composer.phar


+ 65 - 0
config/app.php

@@ -0,0 +1,65 @@
+<?php
+/**
+ * 请在下面放置任何您需要的应用配置
+ *
+ * @license     http://www.phalapi.net/license GPL 协议
+ * @link        http://www.phalapi.net/
+ * @author dogstar <chanzonghuang@gmail.com> 2017-07-13
+ */
+
+return array(
+
+    /**
+     * 应用接口层的统一参数
+     */
+    'apiCommonRules' => array(
+        //'sign' => array('name' => 'sign', 'require' => true),
+    ),
+    /**
+     * 钱包服务器配置
+     */
+    'walletseervers' => array(
+        'getmenero' => array(
+            'host' => '',
+            'user' => '',
+            'password'=>'',
+            'port'=>''
+        ),
+    ),
+    /**
+     * 支持钱包列表
+     * 钱包服务器配置
+     */
+    'walletlist' => array(
+        'monero',
+        'monero' => array(
+            'host' => '47.98.168.8',
+            'user' => 'monero',
+            'password'=>'pig520!@#asdaa',
+            'port'=>'18082',
+            'path'=>'json_rpc',
+            'auth'=>CURLAUTH_DIGEST,
+        ),
+        'bitcoin',
+        'bitcoin' => array(
+            'host' => '47.98.168.8',
+            'user' => 'btcuser',
+            'password'=>'btcuser',
+            'port'=>'8332',
+            'path'=>'',
+            'auth'=>CURLAUTH_BASIC,
+        ),
+    ),
+    /**
+     * 接口服务白名单,格式:接口服务类名.接口服务方法名
+     *
+     * 示例:
+     * - *.*         通配,全部接口服务,慎用!
+     * - Site.*      Api_Default接口类的全部方法
+     * - *.Index     全部接口类的Index方法
+     * - Site.Index  指定某个接口服务,即Api_Default::Index()
+     */
+    'service_whitelist' => array(
+        'Site.Index',
+    ),
+);

+ 32 - 0
config/coin.php

@@ -0,0 +1,32 @@
+<?php
+/**
+ * Desc: xxx
+ * Author: wfs
+ * Date: 2018/9/3 0003
+ */
+return array(
+    'ltc' => array(
+        'rpc_user'   => 'userrpc',
+        'rpc_pass' => 'userpassword',
+        'rpc_ip'=> '13.250.95.139',
+        'rpc_port'  => '28332',
+        'create'  => 'App\Api\Ltc',
+        'send'  => 'App\Api\Ltc',
+        'recharge'  => 'App\Api\Ltc',
+        'once_amount'=> '1000',
+        'address'=> 'MRUC38EbNR9duKG9QTHBdNc44MRikr5ZR9',
+        'account'=> 'yanfei',
+    ),
+    'bch' => array(
+        'rpc_user'   => 'userrpc',
+        'rpc_pass' => 'userpassword',
+        'rpc_ip'=> '127.0.0.1',
+        'rpc_port'  => '8332',
+        'create'  => 'App\Api\Bch',
+        'send'  => 'App\Api\Bch',
+        'recharge'  => 'App\Api\Bch',
+        'once_amount'=> '1000',
+        'address'=> 'qzx23ktsgx382ac04d90wew5fttwkrte2qk2l55un6',
+        'account'=> 'yanfei',
+    )
+);

+ 50 - 0
config/dbs.php

@@ -0,0 +1,50 @@
+<?php
+/**
+ * 分库分表的自定义数据库路由配置
+ * 
+ * @license     http://www.phalapi.net/license GPL 协议
+ * @link        http://www.phalapi.net/
+ * @author: dogstar <chanzonghuang@gmail.com> 2015-02-09
+ */
+
+return array(
+    /**
+     * DB数据库服务器集群
+     */
+    'servers' => array(
+        'db_master' => array(                       //服务器标记
+            'type'      => 'mysql',                 //数据库类型,暂时只支持:mysql, sqlserver
+            'host'      => '127.0.0.1',             //数据库域名
+            'name'      => 'phppai',               //数据库名字
+            'user'      => 'root',                  //数据库用户名
+            'password'  => 'root',	                    //数据库密码
+            'port'      => 3306,                    //数据库端口
+            'charset'   => 'UTF8',                  //数据库字符集
+        ),
+    ),
+
+    /**
+     * 自定义路由表
+     */
+    'tables' => array(
+        //通用路由
+        '__default__' => array(
+            'prefix' => '',
+            'key' => 'id',
+            'map' => array(
+                array('db' => 'db_master'),
+            ),
+        ),
+
+        /**
+        'demo' => array(                                                //表名
+            'prefix' => 'tbl_',                                         //表名前缀
+            'key' => 'id',                                              //表主键名
+            'map' => array(                                             //表路由配置
+                array('db' => 'db_master'),                               //单表配置:array('db' => 服务器标记)
+                array('start' => 0, 'end' => 2, 'db' => 'db_master'),     //分表配置:array('start' => 开始下标, 'end' => 结束下标, 'db' => 服务器标记)
+            ),
+        ),
+         */
+    ),
+);

+ 53 - 0
config/di.php

@@ -0,0 +1,53 @@
+<?php
+/**
+ * DI依赖注入配置文件
+ * 
+ * @license     http://www.phalapi.net/license GPL 协议
+ * @link        http://www.phalapi.net/
+ * @author      dogstar <chanzonghuang@gmail.com> 2017-07-13
+ */
+
+use PhalApi\Loader;
+use PhalApi\Config\FileConfig;
+use PhalApi\Logger;
+use PhalApi\Logger\FileLogger;
+use PhalApi\Database\NotORMDatabase;
+
+/** ---------------- 基本注册 必要服务组件 ---------------- **/
+
+$di = \PhalApi\DI();
+
+// 配置
+$di->config = new FileConfig(API_ROOT . '/config');
+
+// 调试模式,$_GET['__debug__']可自行改名
+$di->debug = !empty($_GET['__debug__']) ? true : $di->config->get('sys.debug');
+
+// 日记纪录
+$di->logger = new FileLogger(API_ROOT . '/runtime', Logger::LOG_LEVEL_DEBUG | Logger::LOG_LEVEL_INFO | Logger::LOG_LEVEL_ERROR);
+
+// 数据操作 - 基于NotORM
+$di->notorm = new NotORMDatabase($di->config->get('dbs'), $di->debug);
+
+// JSON中文输出
+// $di->response = new \PhalApi\Response\JsonResponse(JSON_UNESCAPED_UNICODE);
+
+/** ---------------- 定制注册 可选服务组件 ---------------- **/
+
+// 签名验证服务
+// $di->filter = new \PhalApi\Filter\SimpleMD5Filter();
+
+// 缓存 - Memcache/Memcached
+// $di->cache = function () {
+//     return new \PhalApi\Cache\MemcacheCache(\PhalApi\DI()->config->get('sys.mc'));
+// };
+
+// 支持JsonP的返回
+// if (!empty($_GET['callback'])) {
+//     $di->response = new \PhalApi\Response\JsonpResponse($_GET['callback']);
+// }
+
+// 生成二维码扩展,参考示例:?s=App.Examples_QrCode.Png
+// $di->qrcode = function() {
+//     return new \PhalApi\QrCode\Lite();
+// };

+ 30 - 0
config/sys.php

@@ -0,0 +1,30 @@
+<?php 
+/**
+ * 以下配置为系统级的配置,通常放置不同环境下的不同配置
+ * 
+ * @license     http://www.phalapi.net/license GPL 协议
+ * @link        http://www.phalapi.net/
+ * @author dogstar <chanzonghuang@gmail.com> 2017-07-13
+ */
+
+return array(
+	/**
+	 * 默认环境配置
+	 */
+	'debug' => false,
+
+	/**
+	 * MC缓存服务器参考配置
+	 */
+	 'mc' => array(
+        'host' => '127.0.0.1',
+        'port' => 11211,
+	 ),
+
+    /**
+     * 加密
+     */
+    'crypt' => array(
+        'mcrypt_iv' => '12345678',      //8位
+    ),
+);

+ 13 - 0
data/phalapi.sql

@@ -0,0 +1,13 @@
+
+DROP TABLE IF EXISTS `tbl_curd`;
+CREATE TABLE `tbl_curd` (
+  `id` int(10) NOT NULL AUTO_INCREMENT,
+  `title` varchar(20) DEFAULT NULL,
+  `content` text,
+  `state` tinyint(4) DEFAULT NULL,
+  `post_date` datetime DEFAULT NULL,
+  PRIMARY KEY (`id`)
+) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;
+
+INSERT INTO `tbl_curd` VALUES ('1', 'PhalApi', '欢迎使用PhalApi 2.x 版本!', '0', '2017-07-08 12:09:43');
+INSERT INTO `tbl_curd` VALUES ('2', '版本更新', '主要改用composer和命名空间,并遵循psr-4规范。', '1', '2017-07-08 12:10:58');

+ 9 - 0
language/de/common.php

@@ -0,0 +1,9 @@
+<?php
+// 德语 de - de 德标
+// 德语 de - at 奥地利
+// 德语 de - ch 瑞士
+// 德语 de - ru 俄罗斯(欧境)
+return array(
+	'Hi {name}, welcome to use PhalApi!' => '{name}Hallo, Willkommen PhalApi!',
+	'user not exists' => 'Der nutzer gibt es nicht',
+);

+ 6 - 0
language/en/common.php

@@ -0,0 +1,6 @@
+<?php
+
+return array(
+	'Hello {name}, Welcome to use PhalApi!' => 'Hello {name}, Welcome to use PhalApi!',
+    'user not exists' => 'user not exists',
+);

+ 7 - 0
language/fr/common.php

@@ -0,0 +1,7 @@
+<?php
+// 法语 fr - fr 法标
+// 法语 fr - lu 卢森堡
+return array(
+	'Hi {name}, welcome to use PhalApi!' => '{name}Bonjour, bienvenue PhalApi!',
+	'user not exists' => "L'utilisateur n'existe pas",
+);

+ 14 - 0
language/zh_cn/common.php

@@ -0,0 +1,14 @@
+<?php
+/**
+ * 翻译说明:
+ *
+ * 1、带大括号的保留原来写法,如:{name},会被系统动态替换
+ * 2、没在以下出现的,可以自行追加
+ *
+ * @author dogstar <chanzonghuang@gmail.com> 2015-02-09
+ */
+
+return array(
+	'Hi {name}, welcome to use PhalApi!' => '{name}您好,欢迎使用PhalApi!',
+    'user not exists' => '用户不存在',
+);

+ 6 - 0
language/zh_tw/common.php

@@ -0,0 +1,6 @@
+<?php
+
+return array(
+	'Hi {name}, welcome to use PhalApi!' => '{name}您好,歡迎使用PhalApi!',
+	'user not exists' => '用戶不存在',
+);

+ 13 - 0
public/.htaccess

@@ -0,0 +1,13 @@
+<IfModule mod_rewrite.c>
+    RewriteEngine on
+    RewriteBase /
+
+    RewriteCond %{HTTP_HOST} ^dev.phalapi.net$
+
+    RewriteCond %{REQUEST_FILENAME} !-f
+    RewriteCond %{REQUEST_FILENAME} !-d
+
+    RewriteCond %{REQUEST_URI} !^/phalapi/public/
+    RewriteRule ^(.*)$ /phalapi/public/$1
+    RewriteRule ^(/)?$ index.php [L]
+</IfModule>

+ 1 - 0
public/.idea/.name

@@ -0,0 +1 @@
+public

+ 3 - 0
public/.idea/copyright/profiles_settings.xml

@@ -0,0 +1,3 @@
+<component name="CopyrightManager">
+  <settings default="" />
+</component>

+ 6 - 0
public/.idea/encodings.xml

@@ -0,0 +1,6 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<project version="4">
+  <component name="Encoding">
+    <file url="PROJECT" charset="UTF-8" />
+  </component>
+</project>

+ 16 - 0
public/.idea/misc.xml

@@ -0,0 +1,16 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<project version="4">
+  <component name="ProjectLevelVcsManager" settingsEditedManually="false">
+    <OptionsSetting value="true" id="Add" />
+    <OptionsSetting value="true" id="Remove" />
+    <OptionsSetting value="true" id="Checkout" />
+    <OptionsSetting value="true" id="Update" />
+    <OptionsSetting value="true" id="Status" />
+    <OptionsSetting value="true" id="Edit" />
+    <ConfirmationsSetting value="0" id="Add" />
+    <ConfirmationsSetting value="0" id="Remove" />
+  </component>
+  <component name="SvnBranchConfigurationManager">
+    <option name="mySupportsUserInfoFilter" value="true" />
+  </component>
+</project>

+ 8 - 0
public/.idea/modules.xml

@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<project version="4">
+  <component name="ProjectModuleManager">
+    <modules>
+      <module fileurl="file://$PROJECT_DIR$/.idea/public.iml" filepath="$PROJECT_DIR$/.idea/public.iml" />
+    </modules>
+  </component>
+</project>

+ 8 - 0
public/.idea/public.iml

@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<module type="WEB_MODULE" version="4">
+  <component name="NewModuleRootManager">
+    <content url="file://$MODULE_DIR$" />
+    <orderEntry type="inheritedJdk" />
+    <orderEntry type="sourceFolder" forTests="false" />
+  </component>
+</module>

+ 6 - 0
public/.idea/vcs.xml

@@ -0,0 +1,6 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<project version="4">
+  <component name="VcsDirectoryMappings">
+    <mapping directory="$PROJECT_DIR$" vcs="svn" />
+  </component>
+</project>

+ 146 - 0
public/.idea/workspace.xml

@@ -0,0 +1,146 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<project version="4">
+  <component name="ChangeListManager">
+    <list default="true" id="f56ef79e-4873-440c-b9f6-e85690adefb1" name="Default" comment="" />
+    <ignored path="public.iws" />
+    <ignored path=".idea/workspace.xml" />
+    <option name="EXCLUDED_CONVERTED_TO_IGNORED" value="true" />
+    <option name="TRACKING_ENABLED" value="true" />
+    <option name="SHOW_DIALOG" value="false" />
+    <option name="HIGHLIGHT_CONFLICTS" value="true" />
+    <option name="HIGHLIGHT_NON_ACTIVE_CHANGELIST" value="false" />
+    <option name="LAST_RESOLUTION" value="IGNORE" />
+  </component>
+  <component name="ChangesViewManager" flattened_view="true" show_ignored="false" />
+  <component name="CreatePatchCommitExecutor">
+    <option name="PATCH_PATH" value="" />
+  </component>
+  <component name="ExecutionTargetManager" SELECTED_TARGET="default_target" />
+  <component name="FavoritesManager">
+    <favorites_list name="public" />
+  </component>
+  <component name="JsBuildToolGruntFileManager" detection-done="true" />
+  <component name="JsBuildToolPackageJson" detection-done="true" />
+  <component name="JsGulpfileManager">
+    <detection-done>true</detection-done>
+  </component>
+  <component name="PhpWorkspaceProjectConfiguration" backward_compatibility_performed="true" />
+  <component name="ProjectFrameBounds">
+    <option name="x" value="1696" />
+    <option name="y" value="-1" />
+    <option name="width" value="1640" />
+    <option name="height" value="1010" />
+  </component>
+  <component name="ProjectLevelVcsManager" settingsEditedManually="false">
+    <OptionsSetting value="true" id="Add" />
+    <OptionsSetting value="true" id="Remove" />
+    <OptionsSetting value="true" id="Checkout" />
+    <OptionsSetting value="true" id="Update" />
+    <OptionsSetting value="true" id="Status" />
+    <OptionsSetting value="true" id="Edit" />
+    <ConfirmationsSetting value="0" id="Add" />
+    <ConfirmationsSetting value="0" id="Remove" />
+  </component>
+  <component name="ProjectView">
+    <navigator currentView="ProjectPane" proportions="" version="1">
+      <flattenPackages />
+      <showMembers />
+      <showModules />
+      <showLibraryContents />
+      <hideEmptyPackages />
+      <abbreviatePackageNames />
+      <autoscrollToSource />
+      <autoscrollFromSource />
+      <sortByType />
+      <manualOrder />
+      <foldersAlwaysOnTop value="true" />
+    </navigator>
+    <panes>
+      <pane id="ProjectPane">
+        <subPane>
+          <PATH>
+            <PATH_ELEMENT>
+              <option name="myItemId" value="public" />
+              <option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.ProjectViewProjectNode" />
+            </PATH_ELEMENT>
+          </PATH>
+          <PATH>
+            <PATH_ELEMENT>
+              <option name="myItemId" value="public" />
+              <option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.ProjectViewProjectNode" />
+            </PATH_ELEMENT>
+            <PATH_ELEMENT>
+              <option name="myItemId" value="public" />
+              <option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.PsiDirectoryNode" />
+            </PATH_ELEMENT>
+          </PATH>
+          <PATH>
+            <PATH_ELEMENT>
+              <option name="myItemId" value="public" />
+              <option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.ProjectViewProjectNode" />
+            </PATH_ELEMENT>
+            <PATH_ELEMENT>
+              <option name="myItemId" value="public" />
+              <option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.PsiDirectoryNode" />
+            </PATH_ELEMENT>
+            <PATH_ELEMENT>
+              <option name="myItemId" value="examples" />
+              <option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.PsiDirectoryNode" />
+            </PATH_ELEMENT>
+          </PATH>
+        </subPane>
+      </pane>
+      <pane id="Scratches" />
+      <pane id="Scope" />
+    </panes>
+  </component>
+  <component name="PropertiesComponent">
+    <property name="settings.editor.selected.configurable" value="configurable.group.tools" />
+    <property name="settings.editor.splitter.proportion" value="0.2" />
+    <property name="WebServerToolWindowFactoryState" value="false" />
+    <property name="last_opened_file_path" value="$PROJECT_DIR$/.." />
+  </component>
+  <component name="ShelveChangesManager" show_recycled="false" />
+  <component name="SvnConfiguration" cleanupOnStartRun="true">
+    <configuration>C:\Users\Administrator\AppData\Roaming\Subversion</configuration>
+  </component>
+  <component name="TaskManager">
+    <task active="true" id="Default" summary="Default task">
+      <changelist id="f56ef79e-4873-440c-b9f6-e85690adefb1" name="Default" comment="" />
+      <created>1536574062703</created>
+      <option name="number" value="Default" />
+      <updated>1536574062703</updated>
+    </task>
+    <servers />
+  </component>
+  <component name="ToolWindowManager">
+    <frame x="1696" y="-1" width="1640" height="1010" extended-state="0" />
+    <editor active="false" />
+    <layout>
+      <window_info id="Project" active="true" anchor="left" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="true" show_stripe_button="true" weight="0.25316456" sideWeight="0.5" order="0" side_tool="false" content_ui="combo" />
+      <window_info id="TODO" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.33" sideWeight="0.5" order="6" side_tool="false" content_ui="tabs" />
+      <window_info id="Event Log" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.33" sideWeight="0.5" order="-1" side_tool="true" content_ui="tabs" />
+      <window_info id="Database" active="false" anchor="right" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.33" sideWeight="0.5" order="-1" side_tool="false" content_ui="tabs" />
+      <window_info id="Version Control" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.33" sideWeight="0.5" order="-1" side_tool="false" content_ui="tabs" />
+      <window_info id="Structure" active="false" anchor="left" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.25" sideWeight="0.5" order="1" side_tool="false" content_ui="tabs" />
+      <window_info id="Terminal" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.33" sideWeight="0.5" order="-1" side_tool="false" content_ui="tabs" />
+      <window_info id="Favorites" active="false" anchor="left" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.33" sideWeight="0.5" order="-1" side_tool="true" content_ui="tabs" />
+      <window_info id="Cvs" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.25" sideWeight="0.5" order="4" side_tool="false" content_ui="tabs" />
+      <window_info id="Hierarchy" active="false" anchor="right" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.25" sideWeight="0.5" order="2" side_tool="false" content_ui="combo" />
+      <window_info id="Message" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.33" sideWeight="0.5" order="0" side_tool="false" content_ui="tabs" />
+      <window_info id="Commander" active="false" anchor="right" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.4" sideWeight="0.5" order="0" side_tool="false" content_ui="tabs" />
+      <window_info id="Find" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.33" sideWeight="0.5" order="1" side_tool="false" content_ui="tabs" />
+      <window_info id="Inspection" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.4" sideWeight="0.5" order="5" side_tool="false" content_ui="tabs" />
+      <window_info id="Run" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.33" sideWeight="0.5" order="2" side_tool="false" content_ui="tabs" />
+      <window_info id="Ant Build" active="false" anchor="right" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.25" sideWeight="0.5" order="1" side_tool="false" content_ui="tabs" />
+      <window_info id="Debug" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.4" sideWeight="0.5" order="3" side_tool="false" content_ui="tabs" />
+    </layout>
+  </component>
+  <component name="VcsContentAnnotationSettings">
+    <option name="myLimit" value="2678400000" />
+  </component>
+  <component name="XDebuggerManager">
+    <breakpoint-manager />
+    <watches-manager />
+  </component>
+</project>

+ 41 - 0
public/docs.php

@@ -0,0 +1,41 @@
+<?php
+/**
+ * PhalApi在线接口列表文档 - 自动生成
+ *
+ * - 对Api_系列的接口,进行罗列
+ * - 按service进行字典排序
+ * - 支持多级目录扫描
+ *
+ * <br>使用示例:<br>
+ * ```
+ * <?php
+ * // 左侧菜单说明
+ * class Demo extends Api {
+ *      /**
+ *       * 接口服务名称
+ *       * @desc 更多说明
+ *       * /
+ *      public function index() {
+ *      }
+ * }
+ * ```
+ * @license     http://www.phalapi.net/license GPL 协议
+ * @link        http://www.phalapi.net/
+ * @author      xiaoxunzhao     2015-10-25
+ * @modify      Aevit           2014-10-29
+ * @modify      shwy            2017-03-02
+ * @modify      dogstar         2017-06-17
+ */
+
+require_once dirname(__FILE__) . '/init.php';
+
+$projectName = 'PhalApi开源接口框架';
+
+if (!empty($_GET['detail'])) {
+    $apiDesc = new \PhalApi\Helper\ApiDesc($projectName);
+    $apiDesc->render();
+} else {
+    $apiList = new \PhalApi\Helper\ApiList($projectName);
+    $apiList->render();
+}
+

+ 0 - 0
public/eos.txt


+ 7 - 0
public/examples/upload.html

@@ -0,0 +1,7 @@
+<html>
+    <form method="POST" action="/?service=App.Examples_Upload.Go" enctype="multipart/form-data">
+        <input type="file" name="file">
+        <input type="submit">
+    </form>
+</html>
+

BIN
public/favicon.ico


+ 10 - 0
public/index.php

@@ -0,0 +1,10 @@
+<?php
+/**
+ * 统一访问入口
+ */
+
+require_once dirname(__FILE__) . '/init.php';
+
+$pai = new \PhalApi\PhalApi();
+$pai->response()->output();
+

+ 28 - 0
public/init.php

@@ -0,0 +1,28 @@
+<?php
+/**
+ * 统一初始化
+ */
+
+// 定义项目路径
+defined('API_ROOT') || define('API_ROOT', dirname(__FILE__) . '/..');
+
+// 引入composer
+require_once API_ROOT . '/vendor/autoload.php';
+
+// 时区设置
+date_default_timezone_set('Asia/Shanghai');
+
+// 引入DI服务
+include API_ROOT . '/config/di.php';
+
+// 调试模式
+if (\PhalApi\DI()->debug) {
+    // 启动追踪器
+    \PhalApi\DI()->tracer->mark('PHALAPI_INIT');
+
+    error_reporting(E_ALL);
+    ini_set('display_errors', 'On'); 
+}
+
+// 翻译语言包设定
+\PhalApi\SL('zh_cn');

+ 33 - 0
public/test.php

@@ -0,0 +1,33 @@
+<?php
+function http_request_xml($url,$data = null,$arr_header = null){
+    $curl = curl_init();
+    curl_setopt($curl, CURLOPT_URL, $url);
+    // curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
+    // curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
+    if (!empty($data)){
+        curl_setopt($curl, CURLOPT_POST, 1);
+        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
+    }
+    if(!empty($arr_header)){
+        curl_setopt($curl, CURLOPT_HTTPHEADER, $arr_header);
+    }
+    curl_setopt($curl,CURLOPT_HEADER,1);
+   // curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
+    $output = curl_exec($curl);
+   // echo $output;
+    curl_close($curl);
+    unset($curl);
+    return $output;
+}
+
+
+$url = "47.98.168.8:18082/json_rpc";
+$arr_header[] = "Content-Type:application/json";
+$arr_header[] = "Authorization: Basic ".base64_encode("monero:monero"); //添加头,在name和pass处填写对应账号密码
+$request = json_encode(array(
+    'method' => 'create_account',
+    'params' => array('label'=>'asddd'),
+    'id'     => 0
+));
+$res = http_request_xml($url,$request, $arr_header);
+?>

+ 130 - 0
runtime/log/201809/20180903.log

@@ -0,0 +1,130 @@
+2018-09-03 16:24:37|ERROR|App.Ripple.createAddress|RippleRestProtocolError: CURL: Failed to connect to localhost port 5990: Connection refused (http://localhost:5990/v1/server/connected) in D:\phpStudy\WWW\qq_wallet\vendor\orzfly\php-ripple-rest\src\RippleRestClientCURL.php:34
+Stack trace:
+#0 D:\phpStudy\WWW\qq_wallet\vendor\orzfly\php-ripple-rest\src\RippleRest.php(101): RippleRestClientCURL->get('http://localhos...')
+#1 D:\phpStudy\WWW\qq_wallet\vendor\orzfly\php-ripple-rest\src\RippleRest.php(125): RippleRest::{closure}()
+#2 D:\phpStudy\WWW\qq_wallet\vendor\orzfly\php-ripple-rest\src\RippleRest.php(102): RippleRest::wrapError(Object(Closure))
+#3 D:\phpStudy\WWW\qq_wallet\vendor\orzfly\php-ripple-rest\src\RippleRest.php(52): RippleRest::get('v1/server/conne...')
+#4 D:\phpStudy\WWW\qq_wallet\src\app\Api\Ripple.php(21): RippleRest::isServerConnected()
+#5 [internal function]: App\Api\Ripple->createAddress()
+#6 D:\phpStudy\WWW\qq_wallet\vendor\phalapi\kernal\src\PhalApi.php(53): call_user_func(Array)
+#7 D:\phpStudy\WWW\qq_wallet\public\index.php(9): PhalApi\PhalApi->response()
+#8 {main}
+2018-09-03 20:15:01|ERROR|App.Ripple.autoGet|PDOException: Table 'phppai.tbl_useraddress' doesn't exist in D:\phpStudy\WWW\qq_wallet\vendor\phalapi\notorm\src\NotORM\Result.php:264
+Stack trace:
+#0 D:\phpStudy\WWW\qq_wallet\vendor\phalapi\notorm\src\NotORM\Result.php(813): NotORM_Result->query('SELECT * FROM t...', Array)
+#1 D:\phpStudy\WWW\qq_wallet\vendor\phalapi\notorm\src\NotORM\Result.php(859): NotORM_Result->execute()
+#2 D:\phpStudy\WWW\qq_wallet\vendor\phalapi\kernal\src\Model\NotORMModel.php(31): NotORM_Result->fetch()
+#3 D:\phpStudy\WWW\qq_wallet\src\app\Api\Ripple.php(190): PhalApi\Model\NotORMModel->get(1)
+#4 [internal function]: App\Api\Ripple->autoGet()
+#5 D:\phpStudy\WWW\qq_wallet\vendor\phalapi\kernal\src\PhalApi.php(53): call_user_func(Array)
+#6 D:\phpStudy\WWW\qq_wallet\public\index.php(9): PhalApi\PhalApi->response()
+#7 {main}
+2018-09-03 20:15:17|ERROR|App.Ripple.autoGet|PDOException: Table 'phppai.useraddress' doesn't exist in D:\phpStudy\WWW\qq_wallet\vendor\phalapi\notorm\src\NotORM\Result.php:264
+Stack trace:
+#0 D:\phpStudy\WWW\qq_wallet\vendor\phalapi\notorm\src\NotORM\Result.php(813): NotORM_Result->query('SELECT * FROM u...', Array)
+#1 D:\phpStudy\WWW\qq_wallet\vendor\phalapi\notorm\src\NotORM\Result.php(859): NotORM_Result->execute()
+#2 D:\phpStudy\WWW\qq_wallet\vendor\phalapi\kernal\src\Model\NotORMModel.php(31): NotORM_Result->fetch()
+#3 D:\phpStudy\WWW\qq_wallet\src\app\Api\Ripple.php(190): PhalApi\Model\NotORMModel->get(1)
+#4 [internal function]: App\Api\Ripple->autoGet()
+#5 D:\phpStudy\WWW\qq_wallet\vendor\phalapi\kernal\src\PhalApi.php(53): call_user_func(Array)
+#6 D:\phpStudy\WWW\qq_wallet\public\index.php(9): PhalApi\PhalApi->response()
+#7 {main}
+2018-09-03 20:43:51|ERROR|App.Ripple.autoGet|PDOException: Query was empty in D:\phpStudy\WWW\qq_wallet\vendor\phalapi\notorm\src\NotORM\Result.php:264
+Stack trace:
+#0 D:\phpStudy\WWW\qq_wallet\vendor\phalapi\notorm\src\NotORM\Result.php(933): NotORM_Result->query(NULL, Array)
+#1 D:\phpStudy\WWW\qq_wallet\src\app\Model\user_address.php(14): NotORM_Result->queryRows(NULL)
+#2 D:\phpStudy\WWW\qq_wallet\src\app\Api\Ripple.php(191): App\Model\user_address->test()
+#3 [internal function]: App\Api\Ripple->autoGet()
+#4 D:\phpStudy\WWW\qq_wallet\vendor\phalapi\kernal\src\PhalApi.php(53): call_user_func(Array)
+#5 D:\phpStudy\WWW\qq_wallet\public\index.php(9): PhalApi\PhalApi->response()
+#6 {main}
+2018-09-03 21:40:36|ERROR|App.Ripple.autoGet|PDOException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '"" and symbol=ripple id  10' at line 1 in D:\phpStudy\WWW\qq_wallet\vendor\phalapi\notorm\src\NotORM\Result.php:264
+Stack trace:
+#0 D:\phpStudy\WWW\qq_wallet\vendor\phalapi\notorm\src\NotORM\Result.php(933): NotORM_Result->query('select * from u...', Array)
+#1 D:\phpStudy\WWW\qq_wallet\vendor\phalapi\kernal\src\Model\NotORMModel.php(86): NotORM_Result->queryRows('select * from u...')
+#2 D:\phpStudy\WWW\qq_wallet\src\app\Api\Ripple.php(194): PhalApi\Model\NotORMModel->where(Array)
+#3 [internal function]: App\Api\Ripple->autoGet()
+#4 D:\phpStudy\WWW\qq_wallet\vendor\phalapi\kernal\src\PhalApi.php(53): call_user_func(Array)
+#5 D:\phpStudy\WWW\qq_wallet\public\index.php(9): PhalApi\PhalApi->response()
+#6 {main}
+2018-09-03 21:42:01|ERROR|App.Ripple.autoGet|PDOException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '"" and symbol=ripple id  10' at line 1 in D:\phpStudy\WWW\qq_wallet\vendor\phalapi\notorm\src\NotORM\Result.php:264
+Stack trace:
+#0 D:\phpStudy\WWW\qq_wallet\vendor\phalapi\notorm\src\NotORM\Result.php(933): NotORM_Result->query('select * from u...', Array)
+#1 D:\phpStudy\WWW\qq_wallet\vendor\phalapi\kernal\src\Model\NotORMModel.php(86): NotORM_Result->queryRows('select * from u...')
+#2 D:\phpStudy\WWW\qq_wallet\src\app\Api\Ripple.php(194): PhalApi\Model\NotORMModel->where(Array)
+#3 [internal function]: App\Api\Ripple->autoGet()
+#4 D:\phpStudy\WWW\qq_wallet\vendor\phalapi\kernal\src\PhalApi.php(53): call_user_func(Array)
+#5 D:\phpStudy\WWW\qq_wallet\public\index.php(9): PhalApi\PhalApi->response()
+#6 {main}
+2018-09-03 21:42:09|ERROR|App.Ripple.autoGet|PDOException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '"" and symbol=ripple id  10' at line 1 in D:\phpStudy\WWW\qq_wallet\vendor\phalapi\notorm\src\NotORM\Result.php:264
+Stack trace:
+#0 D:\phpStudy\WWW\qq_wallet\vendor\phalapi\notorm\src\NotORM\Result.php(933): NotORM_Result->query('select * from u...', Array)
+#1 D:\phpStudy\WWW\qq_wallet\vendor\phalapi\kernal\src\Model\NotORMModel.php(86): NotORM_Result->queryRows('select * from u...')
+#2 D:\phpStudy\WWW\qq_wallet\src\app\Api\Ripple.php(194): PhalApi\Model\NotORMModel->where(Array)
+#3 [internal function]: App\Api\Ripple->autoGet()
+#4 D:\phpStudy\WWW\qq_wallet\vendor\phalapi\kernal\src\PhalApi.php(53): call_user_func(Array)
+#5 D:\phpStudy\WWW\qq_wallet\public\index.php(9): PhalApi\PhalApi->response()
+#6 {main}
+2018-09-03 21:44:12|ERROR|App.Ripple.autoGet|PDOException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '"" and symbol=ripple order by id  limit 10' at line 1 in D:\phpStudy\WWW\qq_wallet\vendor\phalapi\notorm\src\NotORM\Result.php:264
+Stack trace:
+#0 D:\phpStudy\WWW\qq_wallet\vendor\phalapi\notorm\src\NotORM\Result.php(933): NotORM_Result->query('select * from u...', Array)
+#1 D:\phpStudy\WWW\qq_wallet\vendor\phalapi\kernal\src\Model\NotORMModel.php(86): NotORM_Result->queryRows('select * from u...')
+#2 D:\phpStudy\WWW\qq_wallet\src\app\Api\Ripple.php(194): PhalApi\Model\NotORMModel->where(Array)
+#3 [internal function]: App\Api\Ripple->autoGet()
+#4 D:\phpStudy\WWW\qq_wallet\vendor\phalapi\kernal\src\PhalApi.php(53): call_user_func(Array)
+#5 D:\phpStudy\WWW\qq_wallet\public\index.php(9): PhalApi\PhalApi->response()
+#6 {main}
+2018-09-03 21:51:04|ERROR|App.Ripple.autoGet|PDOException: Unknown column 'ripple' in 'where clause' in D:\phpStudy\WWW\qq_wallet\vendor\phalapi\notorm\src\NotORM\Result.php:264
+Stack trace:
+#0 D:\phpStudy\WWW\qq_wallet\vendor\phalapi\notorm\src\NotORM\Result.php(933): NotORM_Result->query('select * from u...', Array)
+#1 D:\phpStudy\WWW\qq_wallet\vendor\phalapi\kernal\src\Model\NotORMModel.php(86): NotORM_Result->queryRows('select * from u...')
+#2 D:\phpStudy\WWW\qq_wallet\src\app\Api\Ripple.php(194): PhalApi\Model\NotORMModel->where(Array)
+#3 [internal function]: App\Api\Ripple->autoGet()
+#4 D:\phpStudy\WWW\qq_wallet\vendor\phalapi\kernal\src\PhalApi.php(53): call_user_func(Array)
+#5 D:\phpStudy\WWW\qq_wallet\public\index.php(9): PhalApi\PhalApi->response()
+#6 {main}
+2018-09-03 21:51:26|ERROR|App.Ripple.autoGet|PDOException: Unknown column 'ripple' in 'where clause' in D:\phpStudy\WWW\qq_wallet\vendor\phalapi\notorm\src\NotORM\Result.php:264
+Stack trace:
+#0 D:\phpStudy\WWW\qq_wallet\vendor\phalapi\notorm\src\NotORM\Result.php(933): NotORM_Result->query('select * from u...', Array)
+#1 D:\phpStudy\WWW\qq_wallet\vendor\phalapi\kernal\src\Model\NotORMModel.php(86): NotORM_Result->queryRows('select * from u...')
+#2 D:\phpStudy\WWW\qq_wallet\src\app\Api\Ripple.php(194): PhalApi\Model\NotORMModel->where(Array)
+#3 [internal function]: App\Api\Ripple->autoGet()
+#4 D:\phpStudy\WWW\qq_wallet\vendor\phalapi\kernal\src\PhalApi.php(53): call_user_func(Array)
+#5 D:\phpStudy\WWW\qq_wallet\public\index.php(9): PhalApi\PhalApi->response()
+#6 {main}
+2018-09-03 22:19:42|ERROR|App.Ripple.autoGet|PDOException: Unknown column 'tid' in 'where clause' in D:\phpStudy\WWW\qq_wallet\vendor\phalapi\notorm\src\NotORM\Result.php:264
+Stack trace:
+#0 D:\phpStudy\WWW\qq_wallet\vendor\phalapi\notorm\src\NotORM\Result.php(933): NotORM_Result->query('select * from u...', Array)
+#1 D:\phpStudy\WWW\qq_wallet\vendor\phalapi\kernal\src\Model\NotORMModel.php(86): NotORM_Result->queryRows('select * from u...')
+#2 D:\phpStudy\WWW\qq_wallet\src\app\Api\Ripple.php(94): PhalApi\Model\NotORMModel->where(Array)
+#3 [internal function]: App\Api\Ripple->autoGet()
+#4 D:\phpStudy\WWW\qq_wallet\vendor\phalapi\kernal\src\PhalApi.php(53): call_user_func(Array)
+#5 D:\phpStudy\WWW\qq_wallet\public\index.php(9): PhalApi\PhalApi->response()
+#6 {main}
+2018-09-03 22:22:15|ERROR|App.Ripple.autoGet|PDOException: Unknown column 'ripple' in 'where clause' in D:\phpStudy\WWW\qq_wallet\vendor\phalapi\notorm\src\NotORM\Result.php:264
+Stack trace:
+#0 D:\phpStudy\WWW\qq_wallet\vendor\phalapi\notorm\src\NotORM\Result.php(933): NotORM_Result->query('select * from u...', Array)
+#1 D:\phpStudy\WWW\qq_wallet\vendor\phalapi\kernal\src\Model\NotORMModel.php(86): NotORM_Result->queryRows('select * from u...')
+#2 D:\phpStudy\WWW\qq_wallet\src\app\Api\Ripple.php(94): PhalApi\Model\NotORMModel->where(Array)
+#3 [internal function]: App\Api\Ripple->autoGet()
+#4 D:\phpStudy\WWW\qq_wallet\vendor\phalapi\kernal\src\PhalApi.php(53): call_user_func(Array)
+#5 D:\phpStudy\WWW\qq_wallet\public\index.php(9): PhalApi\PhalApi->response()
+#6 {main}
+2018-09-03 22:23:05|ERROR|App.Ripple.autoGet|PDOException: Unknown column 'ripple' in 'where clause' in D:\phpStudy\WWW\qq_wallet\vendor\phalapi\notorm\src\NotORM\Result.php:264
+Stack trace:
+#0 D:\phpStudy\WWW\qq_wallet\vendor\phalapi\notorm\src\NotORM\Result.php(933): NotORM_Result->query('select * from u...', Array)
+#1 D:\phpStudy\WWW\qq_wallet\vendor\phalapi\kernal\src\Model\NotORMModel.php(87): NotORM_Result->queryRows('select * from u...')
+#2 D:\phpStudy\WWW\qq_wallet\src\app\Api\Ripple.php(94): PhalApi\Model\NotORMModel->where(Array)
+#3 [internal function]: App\Api\Ripple->autoGet()
+#4 D:\phpStudy\WWW\qq_wallet\vendor\phalapi\kernal\src\PhalApi.php(53): call_user_func(Array)
+#5 D:\phpStudy\WWW\qq_wallet\public\index.php(9): PhalApi\PhalApi->response()
+#6 {main}
+2018-09-03 22:23:21|ERROR|App.Ripple.autoGet|PDOException: Unknown column 'ripple' in 'where clause' in D:\phpStudy\WWW\qq_wallet\vendor\phalapi\notorm\src\NotORM\Result.php:264
+Stack trace:
+#0 D:\phpStudy\WWW\qq_wallet\vendor\phalapi\notorm\src\NotORM\Result.php(933): NotORM_Result->query('select * from u...', Array)
+#1 D:\phpStudy\WWW\qq_wallet\vendor\phalapi\kernal\src\Model\NotORMModel.php(87): NotORM_Result->queryRows('select * from u...')
+#2 D:\phpStudy\WWW\qq_wallet\src\app\Api\Ripple.php(94): PhalApi\Model\NotORMModel->where(Array)
+#3 [internal function]: App\Api\Ripple->autoGet()
+#4 D:\phpStudy\WWW\qq_wallet\vendor\phalapi\kernal\src\PhalApi.php(53): call_user_func(Array)
+#5 D:\phpStudy\WWW\qq_wallet\public\index.php(9): PhalApi\PhalApi->response()
+#6 {main}

+ 140 - 0
runtime/log/201809/20180904.log

@@ -0,0 +1,140 @@
+2018-09-04 09:21:59|ERROR|App.Ripple.createAddress|RippleRestProtocolError: CURL: Failed to connect to localhost port 5990: Connection refused (http://localhost:5990/v1/server/connected) in D:\phpStudy\WWW\qq_wallet\vendor\orzfly\php-ripple-rest\src\RippleRestClientCURL.php:34
+Stack trace:
+#0 D:\phpStudy\WWW\qq_wallet\vendor\orzfly\php-ripple-rest\src\RippleRest.php(101): RippleRestClientCURL->get('http://localhos...')
+#1 D:\phpStudy\WWW\qq_wallet\vendor\orzfly\php-ripple-rest\src\RippleRest.php(125): RippleRest::{closure}()
+#2 D:\phpStudy\WWW\qq_wallet\vendor\orzfly\php-ripple-rest\src\RippleRest.php(102): RippleRest::wrapError(Object(Closure))
+#3 D:\phpStudy\WWW\qq_wallet\vendor\orzfly\php-ripple-rest\src\RippleRest.php(52): RippleRest::get('v1/server/conne...')
+#4 D:\phpStudy\WWW\qq_wallet\src\app\Api\Ripple.php(26): RippleRest::isServerConnected()
+#5 [internal function]: App\Api\Ripple->createAddress()
+#6 D:\phpStudy\WWW\qq_wallet\vendor\phalapi\kernal\src\PhalApi.php(53): call_user_func(Array)
+#7 D:\phpStudy\WWW\qq_wallet\public\index.php(9): PhalApi\PhalApi->response()
+#8 {main}
+2018-09-04 09:22:02|ERROR|App.Ripple.sendFrom|RippleRestProtocolError: CURL: Protocol "wss" not supported or disabled in libcurl (wss://s2.ripple.com:443 /v1/server/connected) in D:\phpStudy\WWW\qq_wallet\vendor\orzfly\php-ripple-rest\src\RippleRestClientCURL.php:34
+Stack trace:
+#0 D:\phpStudy\WWW\qq_wallet\vendor\orzfly\php-ripple-rest\src\RippleRest.php(101): RippleRestClientCURL->get('wss://s2.ripple...')
+#1 D:\phpStudy\WWW\qq_wallet\vendor\orzfly\php-ripple-rest\src\RippleRest.php(125): RippleRest::{closure}()
+#2 D:\phpStudy\WWW\qq_wallet\vendor\orzfly\php-ripple-rest\src\RippleRest.php(102): RippleRest::wrapError(Object(Closure))
+#3 D:\phpStudy\WWW\qq_wallet\vendor\orzfly\php-ripple-rest\src\RippleRest.php(52): RippleRest::get('v1/server/conne...')
+#4 D:\phpStudy\WWW\qq_wallet\src\app\Api\Ripple.php(46): RippleRest::isServerConnected()
+#5 [internal function]: App\Api\Ripple->sendFrom()
+#6 D:\phpStudy\WWW\qq_wallet\vendor\phalapi\kernal\src\PhalApi.php(53): call_user_func(Array)
+#7 D:\phpStudy\WWW\qq_wallet\public\index.php(9): PhalApi\PhalApi->response()
+#8 {main}
+2018-09-04 09:22:25|ERROR|App.Ripple.sendFrom|RippleRestProtocolError: CURL: Protocol "wss" not supported or disabled in libcurl (wss://s2.ripple.com:443/v1/server/connected) in D:\phpStudy\WWW\qq_wallet\vendor\orzfly\php-ripple-rest\src\RippleRestClientCURL.php:34
+Stack trace:
+#0 D:\phpStudy\WWW\qq_wallet\vendor\orzfly\php-ripple-rest\src\RippleRest.php(101): RippleRestClientCURL->get('wss://s2.ripple...')
+#1 D:\phpStudy\WWW\qq_wallet\vendor\orzfly\php-ripple-rest\src\RippleRest.php(125): RippleRest::{closure}()
+#2 D:\phpStudy\WWW\qq_wallet\vendor\orzfly\php-ripple-rest\src\RippleRest.php(102): RippleRest::wrapError(Object(Closure))
+#3 D:\phpStudy\WWW\qq_wallet\vendor\orzfly\php-ripple-rest\src\RippleRest.php(52): RippleRest::get('v1/server/conne...')
+#4 D:\phpStudy\WWW\qq_wallet\src\app\Api\Ripple.php(46): RippleRest::isServerConnected()
+#5 [internal function]: App\Api\Ripple->sendFrom()
+#6 D:\phpStudy\WWW\qq_wallet\vendor\phalapi\kernal\src\PhalApi.php(53): call_user_func(Array)
+#7 D:\phpStudy\WWW\qq_wallet\public\index.php(9): PhalApi\PhalApi->response()
+#8 {main}
+2018-09-04 09:22:32|ERROR|App.Ripple.sendFrom|RippleRestProtocolError: CURL: SSL certificate problem: unable to get local issuer certificate (https://s.altnet.rippletest.net:51234/v1/server/connected) in D:\phpStudy\WWW\qq_wallet\vendor\orzfly\php-ripple-rest\src\RippleRestClientCURL.php:34
+Stack trace:
+#0 D:\phpStudy\WWW\qq_wallet\vendor\orzfly\php-ripple-rest\src\RippleRest.php(101): RippleRestClientCURL->get('https://s.altne...')
+#1 D:\phpStudy\WWW\qq_wallet\vendor\orzfly\php-ripple-rest\src\RippleRest.php(125): RippleRest::{closure}()
+#2 D:\phpStudy\WWW\qq_wallet\vendor\orzfly\php-ripple-rest\src\RippleRest.php(102): RippleRest::wrapError(Object(Closure))
+#3 D:\phpStudy\WWW\qq_wallet\vendor\orzfly\php-ripple-rest\src\RippleRest.php(52): RippleRest::get('v1/server/conne...')
+#4 D:\phpStudy\WWW\qq_wallet\src\app\Api\Ripple.php(46): RippleRest::isServerConnected()
+#5 [internal function]: App\Api\Ripple->sendFrom()
+#6 D:\phpStudy\WWW\qq_wallet\vendor\phalapi\kernal\src\PhalApi.php(53): call_user_func(Array)
+#7 D:\phpStudy\WWW\qq_wallet\public\index.php(9): PhalApi\PhalApi->response()
+#8 {main}
+2018-09-04 09:26:02|ERROR|App.Ripple.sendFrom|Exception: jsonException in D:\phpStudy\WWW\qq_wallet\src\app\Api\Ripple.php:40
+Stack trace:
+#0 D:\phpStudy\WWW\qq_wallet\src\app\Api\Ripple.php(73): App\Api\Ripple->request_by_curl(Array)
+#1 [internal function]: App\Api\Ripple->sendFrom()
+#2 D:\phpStudy\WWW\qq_wallet\vendor\phalapi\kernal\src\PhalApi.php(53): call_user_func(Array)
+#3 D:\phpStudy\WWW\qq_wallet\public\index.php(9): PhalApi\PhalApi->response()
+#4 {main}
+2018-09-04 09:26:27|ERROR|App.Ripple.sendFrom|Exception: jsonException in D:\phpStudy\WWW\qq_wallet\src\app\Api\Ripple.php:40
+Stack trace:
+#0 D:\phpStudy\WWW\qq_wallet\src\app\Api\Ripple.php(72): App\Api\Ripple->request_by_curl(Array)
+#1 [internal function]: App\Api\Ripple->sendFrom()
+#2 D:\phpStudy\WWW\qq_wallet\vendor\phalapi\kernal\src\PhalApi.php(53): call_user_func(Array)
+#3 D:\phpStudy\WWW\qq_wallet\public\index.php(9): PhalApi\PhalApi->response()
+#4 {main}
+2018-09-04 09:26:29|ERROR|App.Ripple.sendFrom|Exception: jsonException in D:\phpStudy\WWW\qq_wallet\src\app\Api\Ripple.php:40
+Stack trace:
+#0 D:\phpStudy\WWW\qq_wallet\src\app\Api\Ripple.php(72): App\Api\Ripple->request_by_curl(Array)
+#1 [internal function]: App\Api\Ripple->sendFrom()
+#2 D:\phpStudy\WWW\qq_wallet\vendor\phalapi\kernal\src\PhalApi.php(53): call_user_func(Array)
+#3 D:\phpStudy\WWW\qq_wallet\public\index.php(9): PhalApi\PhalApi->response()
+#4 {main}
+2018-09-04 10:10:25|ERROR|App.Ethereum.createAddress|GuzzleHttp\Exception\ConnectException: cURL error 7: Failed to connect to localhost port 8545: Connection refused (see https://curl.haxx.se/libcurl/c/libcurl-errors.html) in D:\phpStudy\WWW\qq_wallet\vendor\guzzlehttp\guzzle\src\Handler\CurlFactory.php:185
+Stack trace:
+#0 D:\phpStudy\WWW\qq_wallet\vendor\guzzlehttp\guzzle\src\Handler\CurlFactory.php(149): GuzzleHttp\Handler\CurlFactory::createRejection(Object(GuzzleHttp\Handler\EasyHandle), Array)
+#1 D:\phpStudy\WWW\qq_wallet\vendor\guzzlehttp\guzzle\src\Handler\CurlFactory.php(102): GuzzleHttp\Handler\CurlFactory::finishError(Object(GuzzleHttp\Handler\CurlHandler), Object(GuzzleHttp\Handler\EasyHandle), Object(GuzzleHttp\Handler\CurlFactory))
+#2 D:\phpStudy\WWW\qq_wallet\vendor\guzzlehttp\guzzle\src\Handler\CurlHandler.php(43): GuzzleHttp\Handler\CurlFactory::finish(Object(GuzzleHttp\Handler\CurlHandler), Object(GuzzleHttp\Handler\EasyHandle), Object(GuzzleHttp\Handler\CurlFactory))
+#3 D:\phpStudy\WWW\qq_wallet\vendor\guzzlehttp\guzzle\src\Handler\Proxy.php(28): GuzzleHttp\Handler\CurlHandler->__invoke(Object(GuzzleHttp\Psr7\Request), Array)
+#4 D:\phpStudy\WWW\qq_wallet\vendor\guzzlehttp\guzzle\src\Handler\Proxy.php(51): GuzzleHttp\Handler\Proxy::GuzzleHttp\Handler\{closure}(Object(GuzzleHttp\Psr7\Request), Array)
+#5 D:\phpStudy\WWW\qq_wallet\vendor\guzzlehttp\guzzle\src\PrepareBodyMiddleware.php(66): GuzzleHttp\Handler\Proxy::GuzzleHttp\Handler\{closure}(Object(GuzzleHttp\Psr7\Request), Array)
+#6 D:\phpStudy\WWW\qq_wallet\vendor\guzzlehttp\guzzle\src\Middleware.php(30): GuzzleHttp\PrepareBodyMiddleware->__invoke(Object(GuzzleHttp\Psr7\Request), Array)
+#7 D:\phpStudy\WWW\qq_wallet\vendor\guzzlehttp\guzzle\src\RedirectMiddleware.php(70): GuzzleHttp\Middleware::GuzzleHttp\{closure}(Object(GuzzleHttp\Psr7\Request), Array)
+#8 D:\phpStudy\WWW\qq_wallet\vendor\guzzlehttp\guzzle\src\Middleware.php(60): GuzzleHttp\RedirectMiddleware->__invoke(Object(GuzzleHttp\Psr7\Request), Array)
+#9 D:\phpStudy\WWW\qq_wallet\vendor\guzzlehttp\guzzle\src\HandlerStack.php(67): GuzzleHttp\Middleware::GuzzleHttp\{closure}(Object(GuzzleHttp\Psr7\Request), Array)
+#10 D:\phpStudy\WWW\qq_wallet\vendor\guzzlehttp\guzzle\src\Client.php(277): GuzzleHttp\HandlerStack->__invoke(Object(GuzzleHttp\Psr7\Request), Array)
+#11 D:\phpStudy\WWW\qq_wallet\vendor\guzzlehttp\guzzle\src\Client.php(125): GuzzleHttp\Client->transfer(Object(GuzzleHttp\Psr7\Request), Array)
+#12 D:\phpStudy\WWW\qq_wallet\vendor\guzzlehttp\guzzle\src\Client.php(131): GuzzleHttp\Client->requestAsync('post', Object(GuzzleHttp\Psr7\Uri), Array)
+#13 D:\phpStudy\WWW\qq_wallet\vendor\guzzlehttp\guzzle\src\Client.php(89): GuzzleHttp\Client->request('post', '', Array)
+#14 D:\phpStudy\WWW\qq_wallet\vendor\achse\geth-jsonrpc-php-client\src\JsonRpc\GuzzleClient.php(53): GuzzleHttp\Client->__call('post', Array)
+#15 D:\phpStudy\WWW\qq_wallet\vendor\achse\geth-jsonrpc-php-client\src\JsonRpc\Client.php(64): Achse\GethJsonRpcPhpClient\JsonRpc\GuzzleClient->post('{"jsonrpc":"2.0...')
+#16 D:\phpStudy\WWW\qq_wallet\src\app\Api\Ethereum.php(25): Achse\GethJsonRpcPhpClient\JsonRpc\Client->callMethod('personal_newAcc...', Array)
+#17 [internal function]: App\Api\Ethereum->createAddress()
+#18 D:\phpStudy\WWW\qq_wallet\vendor\phalapi\kernal\src\PhalApi.php(53): call_user_func(Array)
+#19 D:\phpStudy\WWW\qq_wallet\public\index.php(9): PhalApi\PhalApi->response()
+#20 {main}
+
+Next Achse\GethJsonRpcPhpClient\JsonRpc\RequestFailedException: Request failed due to Guzzle exception: "cURL error 7: Failed to connect to localhost port 8545: Connection refused (see https://curl.haxx.se/libcurl/c/libcurl-errors.html)". in D:\phpStudy\WWW\qq_wallet\vendor\achse\geth-jsonrpc-php-client\src\JsonRpc\GuzzleClient.php:55
+Stack trace:
+#0 D:\phpStudy\WWW\qq_wallet\vendor\achse\geth-jsonrpc-php-client\src\JsonRpc\Client.php(64): Achse\GethJsonRpcPhpClient\JsonRpc\GuzzleClient->post('{"jsonrpc":"2.0...')
+#1 D:\phpStudy\WWW\qq_wallet\src\app\Api\Ethereum.php(25): Achse\GethJsonRpcPhpClient\JsonRpc\Client->callMethod('personal_newAcc...', Array)
+#2 [internal function]: App\Api\Ethereum->createAddress()
+#3 D:\phpStudy\WWW\qq_wallet\vendor\phalapi\kernal\src\PhalApi.php(53): call_user_func(Array)
+#4 D:\phpStudy\WWW\qq_wallet\public\index.php(9): PhalApi\PhalApi->response()
+#5 {main}
+2018-09-04 10:11:48|ERROR|App.Ripple.createAddress|RippleRestProtocolError: CURL: Failed to connect to localhost port 5990: Connection refused (http://localhost:5990/v1/server/connected) in D:\phpStudy\WWW\qq_wallet\vendor\orzfly\php-ripple-rest\src\RippleRestClientCURL.php:34
+Stack trace:
+#0 D:\phpStudy\WWW\qq_wallet\vendor\orzfly\php-ripple-rest\src\RippleRest.php(101): RippleRestClientCURL->get('http://localhos...')
+#1 D:\phpStudy\WWW\qq_wallet\vendor\orzfly\php-ripple-rest\src\RippleRest.php(125): RippleRest::{closure}()
+#2 D:\phpStudy\WWW\qq_wallet\vendor\orzfly\php-ripple-rest\src\RippleRest.php(102): RippleRest::wrapError(Object(Closure))
+#3 D:\phpStudy\WWW\qq_wallet\vendor\orzfly\php-ripple-rest\src\RippleRest.php(52): RippleRest::get('v1/server/conne...')
+#4 D:\phpStudy\WWW\qq_wallet\src\app\Api\Ripple.php(42): RippleRest::isServerConnected()
+#5 [internal function]: App\Api\Ripple->createAddress()
+#6 D:\phpStudy\WWW\qq_wallet\vendor\phalapi\kernal\src\PhalApi.php(53): call_user_func(Array)
+#7 D:\phpStudy\WWW\qq_wallet\public\index.php(9): PhalApi\PhalApi->response()
+#8 {main}
+2018-09-04 10:35:32|ERROR|App.Ripple.sendFrom|GuzzleHttp\Exception\RequestException: cURL error 60: SSL certificate problem: unable to get local issuer certificate (see https://curl.haxx.se/libcurl/c/libcurl-errors.html) in D:\phpStudy\WWW\qq_wallet\vendor\guzzlehttp\guzzle\src\Handler\CurlFactory.php:186
+Stack trace:
+#0 D:\phpStudy\WWW\qq_wallet\vendor\guzzlehttp\guzzle\src\Handler\CurlFactory.php(149): GuzzleHttp\Handler\CurlFactory::createRejection(Object(GuzzleHttp\Handler\EasyHandle), Array)
+#1 D:\phpStudy\WWW\qq_wallet\vendor\guzzlehttp\guzzle\src\Handler\CurlFactory.php(102): GuzzleHttp\Handler\CurlFactory::finishError(Object(GuzzleHttp\Handler\CurlHandler), Object(GuzzleHttp\Handler\EasyHandle), Object(GuzzleHttp\Handler\CurlFactory))
+#2 D:\phpStudy\WWW\qq_wallet\vendor\guzzlehttp\guzzle\src\Handler\CurlHandler.php(43): GuzzleHttp\Handler\CurlFactory::finish(Object(GuzzleHttp\Handler\CurlHandler), Object(GuzzleHttp\Handler\EasyHandle), Object(GuzzleHttp\Handler\CurlFactory))
+#3 D:\phpStudy\WWW\qq_wallet\vendor\guzzlehttp\guzzle\src\Handler\Proxy.php(28): GuzzleHttp\Handler\CurlHandler->__invoke(Object(GuzzleHttp\Psr7\Request), Array)
+#4 D:\phpStudy\WWW\qq_wallet\vendor\guzzlehttp\guzzle\src\Handler\Proxy.php(51): GuzzleHttp\Handler\Proxy::GuzzleHttp\Handler\{closure}(Object(GuzzleHttp\Psr7\Request), Array)
+#5 D:\phpStudy\WWW\qq_wallet\vendor\guzzlehttp\guzzle\src\PrepareBodyMiddleware.php(66): GuzzleHttp\Handler\Proxy::GuzzleHttp\Handler\{closure}(Object(GuzzleHttp\Psr7\Request), Array)
+#6 D:\phpStudy\WWW\qq_wallet\vendor\guzzlehttp\guzzle\src\Middleware.php(30): GuzzleHttp\PrepareBodyMiddleware->__invoke(Object(GuzzleHttp\Psr7\Request), Array)
+#7 D:\phpStudy\WWW\qq_wallet\vendor\guzzlehttp\guzzle\src\RedirectMiddleware.php(70): GuzzleHttp\Middleware::GuzzleHttp\{closure}(Object(GuzzleHttp\Psr7\Request), Array)
+#8 D:\phpStudy\WWW\qq_wallet\vendor\guzzlehttp\guzzle\src\Middleware.php(60): GuzzleHttp\RedirectMiddleware->__invoke(Object(GuzzleHttp\Psr7\Request), Array)
+#9 D:\phpStudy\WWW\qq_wallet\vendor\guzzlehttp\guzzle\src\HandlerStack.php(67): GuzzleHttp\Middleware::GuzzleHttp\{closure}(Object(GuzzleHttp\Psr7\Request), Array)
+#10 D:\phpStudy\WWW\qq_wallet\vendor\guzzlehttp\guzzle\src\Client.php(277): GuzzleHttp\HandlerStack->__invoke(Object(GuzzleHttp\Psr7\Request), Array)
+#11 D:\phpStudy\WWW\qq_wallet\vendor\guzzlehttp\guzzle\src\Client.php(125): GuzzleHttp\Client->transfer(Object(GuzzleHttp\Psr7\Request), Array)
+#12 D:\phpStudy\WWW\qq_wallet\vendor\guzzlehttp\guzzle\src\Client.php(131): GuzzleHttp\Client->requestAsync('post', Object(GuzzleHttp\Psr7\Uri), Array)
+#13 D:\phpStudy\WWW\qq_wallet\vendor\guzzlehttp\guzzle\src\Client.php(89): GuzzleHttp\Client->request('post', '', Array)
+#14 D:\phpStudy\WWW\qq_wallet\vendor\achse\geth-jsonrpc-php-client\src\JsonRpc\GuzzleClient.php(53): GuzzleHttp\Client->__call('post', Array)
+#15 D:\phpStudy\WWW\qq_wallet\vendor\achse\geth-jsonrpc-php-client\src\JsonRpc\Client.php(64): Achse\GethJsonRpcPhpClient\JsonRpc\GuzzleClient->post('{"jsonrpc":"2.0...')
+#16 D:\phpStudy\WWW\qq_wallet\src\app\Api\Ripple.php(75): Achse\GethJsonRpcPhpClient\JsonRpc\Client->callMethod('account_info', Array)
+#17 [internal function]: App\Api\Ripple->sendFrom()
+#18 D:\phpStudy\WWW\qq_wallet\vendor\phalapi\kernal\src\PhalApi.php(53): call_user_func(Array)
+#19 D:\phpStudy\WWW\qq_wallet\public\index.php(9): PhalApi\PhalApi->response()
+#20 {main}
+
+Next Achse\GethJsonRpcPhpClient\JsonRpc\RequestFailedException: Request failed due to Guzzle exception: "cURL error 60: SSL certificate problem: unable to get local issuer certificate (see https://curl.haxx.se/libcurl/c/libcurl-errors.html)". in D:\phpStudy\WWW\qq_wallet\vendor\achse\geth-jsonrpc-php-client\src\JsonRpc\GuzzleClient.php:55
+Stack trace:
+#0 D:\phpStudy\WWW\qq_wallet\vendor\achse\geth-jsonrpc-php-client\src\JsonRpc\Client.php(64): Achse\GethJsonRpcPhpClient\JsonRpc\GuzzleClient->post('{"jsonrpc":"2.0...')
+#1 D:\phpStudy\WWW\qq_wallet\src\app\Api\Ripple.php(75): Achse\GethJsonRpcPhpClient\JsonRpc\Client->callMethod('account_info', Array)
+#2 [internal function]: App\Api\Ripple->sendFrom()
+#3 D:\phpStudy\WWW\qq_wallet\vendor\phalapi\kernal\src\PhalApi.php(53): call_user_func(Array)
+#4 D:\phpStudy\WWW\qq_wallet\public\index.php(9): PhalApi\PhalApi->response()
+#5 {main}

+ 95 - 0
runtime/log/201809/20180905.log

@@ -0,0 +1,95 @@
+2018-09-05 14:48:32|ERROR|App.dockCoin.getRecharge|PDOException: Unknown column 'type' in 'field list' in D:\phpStudy\WWW\qq_wallet\vendor\phalapi\notorm\src\NotORM\Result.php:264
+Stack trace:
+#0 D:\phpStudy\WWW\qq_wallet\vendor\phalapi\notorm\src\NotORM\Result.php(341): NotORM_Result->query('INSERT INTO use...', Array)
+#1 D:\phpStudy\WWW\qq_wallet\vendor\phalapi\notorm\src\NotORM\Result.php(358): NotORM_Result->insert_multi(Array)
+#2 D:\phpStudy\WWW\qq_wallet\vendor\phalapi\kernal\src\Model\NotORMModel.php(42): NotORM_Result->insert(Array)
+#3 D:\phpStudy\WWW\qq_wallet\src\app\Api\Ripple.php(412): PhalApi\Model\NotORMModel->insert(Array)
+#4 [internal function]: App\Api\Ripple::autoGet()
+#5 D:\phpStudy\WWW\qq_wallet\src\app\Api\dockCoin.php(87): call_user_func(Array)
+#6 [internal function]: App\Api\dockCoin->getRecharge()
+#7 D:\phpStudy\WWW\qq_wallet\vendor\phalapi\kernal\src\PhalApi.php(53): call_user_func(Array)
+#8 D:\phpStudy\WWW\qq_wallet\public\index.php(9): PhalApi\PhalApi->response()
+#9 {main}
+2018-09-05 14:49:27|ERROR|App.dockCoin.getRecharge|PDOException: Operand should contain 1 column(s) in D:\phpStudy\WWW\qq_wallet\vendor\phalapi\notorm\src\NotORM\Result.php:264
+Stack trace:
+#0 D:\phpStudy\WWW\qq_wallet\vendor\phalapi\notorm\src\NotORM\Result.php(341): NotORM_Result->query('INSERT INTO use...', Array)
+#1 D:\phpStudy\WWW\qq_wallet\vendor\phalapi\notorm\src\NotORM\Result.php(358): NotORM_Result->insert_multi(Array)
+#2 D:\phpStudy\WWW\qq_wallet\vendor\phalapi\kernal\src\Model\NotORMModel.php(42): NotORM_Result->insert(Array)
+#3 D:\phpStudy\WWW\qq_wallet\src\app\Api\Ripple.php(412): PhalApi\Model\NotORMModel->insert(Array)
+#4 [internal function]: App\Api\Ripple::autoGet()
+#5 D:\phpStudy\WWW\qq_wallet\src\app\Api\dockCoin.php(87): call_user_func(Array)
+#6 [internal function]: App\Api\dockCoin->getRecharge()
+#7 D:\phpStudy\WWW\qq_wallet\vendor\phalapi\kernal\src\PhalApi.php(53): call_user_func(Array)
+#8 D:\phpStudy\WWW\qq_wallet\public\index.php(9): PhalApi\PhalApi->response()
+#9 {main}
+2018-09-05 14:50:25|ERROR|App.dockCoin.getRecharge|PDOException: Operand should contain 1 column(s) in D:\phpStudy\WWW\qq_wallet\vendor\phalapi\notorm\src\NotORM\Result.php:264
+Stack trace:
+#0 D:\phpStudy\WWW\qq_wallet\vendor\phalapi\notorm\src\NotORM\Result.php(341): NotORM_Result->query('INSERT INTO use...', Array)
+#1 D:\phpStudy\WWW\qq_wallet\vendor\phalapi\notorm\src\NotORM\Result.php(358): NotORM_Result->insert_multi(Array)
+#2 D:\phpStudy\WWW\qq_wallet\vendor\phalapi\kernal\src\Model\NotORMModel.php(42): NotORM_Result->insert(Array)
+#3 D:\phpStudy\WWW\qq_wallet\src\app\Api\Ripple.php(412): PhalApi\Model\NotORMModel->insert(Array)
+#4 [internal function]: App\Api\Ripple::autoGet()
+#5 D:\phpStudy\WWW\qq_wallet\src\app\Api\dockCoin.php(87): call_user_func(Array)
+#6 [internal function]: App\Api\dockCoin->getRecharge()
+#7 D:\phpStudy\WWW\qq_wallet\vendor\phalapi\kernal\src\PhalApi.php(53): call_user_func(Array)
+#8 D:\phpStudy\WWW\qq_wallet\public\index.php(9): PhalApi\PhalApi->response()
+#9 {main}
+2018-09-05 14:53:10|ERROR|App.dockCoin.getRecharge|PDOException: Operand should contain 1 column(s) in D:\phpStudy\WWW\qq_wallet\vendor\phalapi\notorm\src\NotORM\Result.php:264
+Stack trace:
+#0 D:\phpStudy\WWW\qq_wallet\vendor\phalapi\notorm\src\NotORM\Result.php(341): NotORM_Result->query('INSERT INTO use...', Array)
+#1 D:\phpStudy\WWW\qq_wallet\vendor\phalapi\notorm\src\NotORM\Result.php(358): NotORM_Result->insert_multi(Array)
+#2 D:\phpStudy\WWW\qq_wallet\vendor\phalapi\kernal\src\Model\NotORMModel.php(42): NotORM_Result->insert(Array)
+#3 D:\phpStudy\WWW\qq_wallet\src\app\Api\Ripple.php(412): PhalApi\Model\NotORMModel->insert(Array)
+#4 [internal function]: App\Api\Ripple::autoGet()
+#5 D:\phpStudy\WWW\qq_wallet\src\app\Api\dockCoin.php(87): call_user_func(Array)
+#6 [internal function]: App\Api\dockCoin->getRecharge()
+#7 D:\phpStudy\WWW\qq_wallet\vendor\phalapi\kernal\src\PhalApi.php(53): call_user_func(Array)
+#8 D:\phpStudy\WWW\qq_wallet\public\index.php(9): PhalApi\PhalApi->response()
+#9 {main}
+2018-09-05 14:56:07|ERROR|App.dockCoin.getRecharge|PDOException: Unknown column 'type' in 'field list' in D:\phpStudy\WWW\qq_wallet\vendor\phalapi\notorm\src\NotORM\Result.php:264
+Stack trace:
+#0 D:\phpStudy\WWW\qq_wallet\vendor\phalapi\notorm\src\NotORM\Result.php(341): NotORM_Result->query('INSERT INTO use...', Array)
+#1 D:\phpStudy\WWW\qq_wallet\vendor\phalapi\notorm\src\NotORM\Result.php(358): NotORM_Result->insert_multi(Array)
+#2 D:\phpStudy\WWW\qq_wallet\vendor\phalapi\kernal\src\Model\NotORMModel.php(42): NotORM_Result->insert(Array)
+#3 D:\phpStudy\WWW\qq_wallet\src\app\Api\Ripple.php(412): PhalApi\Model\NotORMModel->insert(Array)
+#4 [internal function]: App\Api\Ripple::autoGet()
+#5 D:\phpStudy\WWW\qq_wallet\src\app\Api\dockCoin.php(87): call_user_func(Array)
+#6 [internal function]: App\Api\dockCoin->getRecharge()
+#7 D:\phpStudy\WWW\qq_wallet\vendor\phalapi\kernal\src\PhalApi.php(53): call_user_func(Array)
+#8 D:\phpStudy\WWW\qq_wallet\public\index.php(9): PhalApi\PhalApi->response()
+#9 {main}
+2018-09-05 15:03:37|ERROR|App.dockCoin.getRecharge|PDOException: Unknown column 'amount' in 'field list' in D:\phpStudy\WWW\qq_wallet\vendor\phalapi\notorm\src\NotORM\Result.php:264
+Stack trace:
+#0 D:\phpStudy\WWW\qq_wallet\vendor\phalapi\notorm\src\NotORM\Result.php(341): NotORM_Result->query('INSERT INTO use...', Array)
+#1 D:\phpStudy\WWW\qq_wallet\vendor\phalapi\notorm\src\NotORM\Result.php(358): NotORM_Result->insert_multi(Array)
+#2 D:\phpStudy\WWW\qq_wallet\vendor\phalapi\kernal\src\Model\NotORMModel.php(42): NotORM_Result->insert(Array)
+#3 D:\phpStudy\WWW\qq_wallet\src\app\Api\Ripple.php(412): PhalApi\Model\NotORMModel->insert(Array)
+#4 [internal function]: App\Api\Ripple::autoGet()
+#5 D:\phpStudy\WWW\qq_wallet\src\app\Api\dockCoin.php(87): call_user_func(Array)
+#6 [internal function]: App\Api\dockCoin->getRecharge()
+#7 D:\phpStudy\WWW\qq_wallet\vendor\phalapi\kernal\src\PhalApi.php(53): call_user_func(Array)
+#8 D:\phpStudy\WWW\qq_wallet\public\index.php(9): PhalApi\PhalApi->response()
+#9 {main}
+2018-09-05 16:45:43|ERROR|App.dockCoin.getRecharge|PDOException: Duplicate entry '664D3576F544112067232C0607860F75388C1D031B0E96BCF7FB547F2D74056D' for key 'hash' in D:\phpStudy\WWW\qq_wallet\vendor\phalapi\notorm\src\NotORM\Result.php:264
+Stack trace:
+#0 D:\phpStudy\WWW\qq_wallet\vendor\phalapi\notorm\src\NotORM\Result.php(341): NotORM_Result->query('INSERT INTO use...', Array)
+#1 D:\phpStudy\WWW\qq_wallet\vendor\phalapi\notorm\src\NotORM\Result.php(358): NotORM_Result->insert_multi(Array)
+#2 D:\phpStudy\WWW\qq_wallet\vendor\phalapi\kernal\src\Model\NotORMModel.php(42): NotORM_Result->insert(Array)
+#3 D:\phpStudy\WWW\qq_wallet\src\app\Api\Ripple.php(439): PhalApi\Model\NotORMModel->insert(Array)
+#4 [internal function]: App\Api\Ripple::autoGet()
+#5 D:\phpStudy\WWW\qq_wallet\src\app\Api\dockCoin.php(87): call_user_func(Array)
+#6 [internal function]: App\Api\dockCoin->getRecharge()
+#7 D:\phpStudy\WWW\qq_wallet\vendor\phalapi\kernal\src\PhalApi.php(53): call_user_func(Array)
+#8 D:\phpStudy\WWW\qq_wallet\public\index.php(9): PhalApi\PhalApi->response()
+#9 {main}
+2018-09-05 17:39:19|ERROR|App.dockCoin.getRecharge|PDOException: Table 'phppai.symbol_recharge_block' doesn't exist in D:\phpStudy\WWW\qq_wallet\vendor\phalapi\notorm\src\NotORM\Result.php:264
+Stack trace:
+#0 D:\phpStudy\WWW\qq_wallet\vendor\phalapi\notorm\src\NotORM\Result.php(933): NotORM_Result->query('select * from s...', Array)
+#1 D:\phpStudy\WWW\qq_wallet\vendor\phalapi\kernal\src\Model\NotORMModel.php(86): NotORM_Result->queryRows('select * from s...')
+#2 D:\phpStudy\WWW\qq_wallet\src\app\Api\Ripple.php(366): PhalApi\Model\NotORMModel->where(Array)
+#3 [internal function]: App\Api\Ripple::autoGet()
+#4 D:\phpStudy\WWW\qq_wallet\src\app\Api\dockCoin.php(87): call_user_func(Array)
+#5 [internal function]: App\Api\dockCoin->getRecharge()
+#6 D:\phpStudy\WWW\qq_wallet\vendor\phalapi\kernal\src\PhalApi.php(53): call_user_func(Array)
+#7 D:\phpStudy\WWW\qq_wallet\public\index.php(9): PhalApi\PhalApi->response()
+#8 {main}

+ 0 - 0
runtime/log/201809/20180906.log


File diff suppressed because it is too large
+ 1120 - 0
runtime/log/201809/20180908.log


+ 40 - 0
runtime/log/201809/20180909.log

@@ -0,0 +1,40 @@
+2018-09-09 09:54:24|ERROR|App.Ethereum.checkRemain|PDOException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ')' at line 1 in D:\phpStudy\WWW\qq_wallet\vendor\phalapi\notorm\src\NotORM\Result.php:264
+Stack trace:
+#0 D:\phpStudy\WWW\qq_wallet\vendor\phalapi\notorm\src\NotORM\Result.php(933): NotORM_Result->query('update eth_rema...', Array)
+#1 D:\phpStudy\WWW\qq_wallet\vendor\phalapi\notorm\src\NotORM\Result.php(920): NotORM_Result->queryRows('update eth_rema...', Array)
+#2 D:\phpStudy\WWW\qq_wallet\vendor\phalapi\kernal\src\Model\NotORMModel.php(101): NotORM_Result->queryAll('update eth_rema...')
+#3 D:\phpStudy\WWW\qq_wallet\src\app\Api\Ethereum.php(335): PhalApi\Model\NotORMModel->saveAll('update eth_rema...')
+#4 [internal function]: App\Api\Ethereum->checkRemain()
+#5 D:\phpStudy\WWW\qq_wallet\vendor\phalapi\kernal\src\PhalApi.php(53): call_user_func(Array)
+#6 D:\phpStudy\WWW\qq_wallet\public\index.php(9): PhalApi\PhalApi->response()
+#7 {main}
+2018-09-09 09:56:04|ERROR|App.Ethereum.checkRemain|PDOException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ')' at line 1 in D:\phpStudy\WWW\qq_wallet\vendor\phalapi\notorm\src\NotORM\Result.php:264
+Stack trace:
+#0 D:\phpStudy\WWW\qq_wallet\vendor\phalapi\notorm\src\NotORM\Result.php(933): NotORM_Result->query('update eth_rema...', Array)
+#1 D:\phpStudy\WWW\qq_wallet\vendor\phalapi\notorm\src\NotORM\Result.php(920): NotORM_Result->queryRows('update eth_rema...', Array)
+#2 D:\phpStudy\WWW\qq_wallet\vendor\phalapi\kernal\src\Model\NotORMModel.php(101): NotORM_Result->queryAll('update eth_rema...')
+#3 D:\phpStudy\WWW\qq_wallet\src\app\Api\Ethereum.php(336): PhalApi\Model\NotORMModel->saveAll('update eth_rema...')
+#4 [internal function]: App\Api\Ethereum->checkRemain()
+#5 D:\phpStudy\WWW\qq_wallet\vendor\phalapi\kernal\src\PhalApi.php(53): call_user_func(Array)
+#6 D:\phpStudy\WWW\qq_wallet\public\index.php(9): PhalApi\PhalApi->response()
+#7 {main}
+2018-09-09 09:57:50|ERROR|App.Ethereum.checkRemain|PDOException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ')' at line 1 in D:\phpStudy\WWW\qq_wallet\vendor\phalapi\notorm\src\NotORM\Result.php:264
+Stack trace:
+#0 D:\phpStudy\WWW\qq_wallet\vendor\phalapi\notorm\src\NotORM\Result.php(933): NotORM_Result->query('update eth_rema...', Array)
+#1 D:\phpStudy\WWW\qq_wallet\vendor\phalapi\notorm\src\NotORM\Result.php(920): NotORM_Result->queryRows('update eth_rema...', Array)
+#2 D:\phpStudy\WWW\qq_wallet\vendor\phalapi\kernal\src\Model\NotORMModel.php(101): NotORM_Result->queryAll('update eth_rema...')
+#3 D:\phpStudy\WWW\qq_wallet\src\app\Api\Ethereum.php(337): PhalApi\Model\NotORMModel->saveAll('update eth_rema...')
+#4 [internal function]: App\Api\Ethereum->checkRemain()
+#5 D:\phpStudy\WWW\qq_wallet\vendor\phalapi\kernal\src\PhalApi.php(53): call_user_func(Array)
+#6 D:\phpStudy\WWW\qq_wallet\public\index.php(9): PhalApi\PhalApi->response()
+#7 {main}
+2018-09-09 10:02:37|ERROR|App.Ethereum.checkRemain|PDOException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ')' at line 1 in D:\phpStudy\WWW\qq_wallet\vendor\phalapi\notorm\src\NotORM\Result.php:264
+Stack trace:
+#0 D:\phpStudy\WWW\qq_wallet\vendor\phalapi\notorm\src\NotORM\Result.php(933): NotORM_Result->query('update eth_rema...', Array)
+#1 D:\phpStudy\WWW\qq_wallet\vendor\phalapi\notorm\src\NotORM\Result.php(920): NotORM_Result->queryRows('update eth_rema...', Array)
+#2 D:\phpStudy\WWW\qq_wallet\vendor\phalapi\kernal\src\Model\NotORMModel.php(101): NotORM_Result->queryAll('update eth_rema...')
+#3 D:\phpStudy\WWW\qq_wallet\src\app\Api\Ethereum.php(335): PhalApi\Model\NotORMModel->saveAll('update eth_rema...')
+#4 [internal function]: App\Api\Ethereum->checkRemain()
+#5 D:\phpStudy\WWW\qq_wallet\vendor\phalapi\kernal\src\PhalApi.php(53): call_user_func(Array)
+#6 D:\phpStudy\WWW\qq_wallet\public\index.php(9): PhalApi\PhalApi->response()
+#7 {main}

+ 0 - 0
runtime/log/201809/20180910.log


+ 0 - 0
runtime/log/201809/20180912.log


+ 8 - 0
runtime/log/201809/20180913.log

@@ -0,0 +1,8 @@
+2018-09-13 12:43:23|ERROR|App.etc.sendfrom|Exception: jsonException in D:\phpStudy\WWW\qq_wallet\src\app\Common\EtcToken.php:29
+Stack trace:
+#0 D:\phpStudy\WWW\qq_wallet\src\app\Common\EtcToken.php(133): App\Common\EtcToken->request_by_curl(Array, Array, Array)
+#1 D:\phpStudy\WWW\qq_wallet\src\app\Api\Etc.php(138): App\Common\EtcToken->getGasLimit('0x791f59ffd89De...')
+#2 [internal function]: App\Api\Etc->sendFrom()
+#3 D:\phpStudy\WWW\qq_wallet\vendor\phalapi\kernal\src\PhalApi.php(53): call_user_func(Array)
+#4 D:\phpStudy\WWW\qq_wallet\public\index.php(9): PhalApi\PhalApi->response()
+#5 {main}

+ 0 - 0
runtime/log/201809/20180914.log


+ 107 - 0
runtime/log/201809/20180915.log

@@ -0,0 +1,107 @@
+2018-09-15 14:17:00|ERROR|App.test.index|GuzzleHttp\Exception\RequestException: cURL error 77: error setting certificate verify locations:
+  CAfile: D:/phpStudy/WWW/qq_wallet/ca-bundle.crt
+  CApath: none (see https://curl.haxx.se/libcurl/c/libcurl-errors.html) in D:\phpStudy\WWW\qq_wallet\vendor\guzzlehttp\guzzle\src\Handler\CurlFactory.php:186
+Stack trace:
+#0 D:\phpStudy\WWW\qq_wallet\vendor\guzzlehttp\guzzle\src\Handler\CurlFactory.php(149): GuzzleHttp\Handler\CurlFactory::createRejection(Object(GuzzleHttp\Handler\EasyHandle), Array)
+#1 D:\phpStudy\WWW\qq_wallet\vendor\guzzlehttp\guzzle\src\Handler\CurlFactory.php(102): GuzzleHttp\Handler\CurlFactory::finishError(Object(GuzzleHttp\Handler\CurlHandler), Object(GuzzleHttp\Handler\EasyHandle), Object(GuzzleHttp\Handler\CurlFactory))
+#2 D:\phpStudy\WWW\qq_wallet\vendor\guzzlehttp\guzzle\src\Handler\CurlHandler.php(43): GuzzleHttp\Handler\CurlFactory::finish(Object(GuzzleHttp\Handler\CurlHandler), Object(GuzzleHttp\Handler\EasyHandle), Object(GuzzleHttp\Handler\CurlFactory))
+#3 D:\phpStudy\WWW\qq_wallet\vendor\guzzlehttp\guzzle\src\Handler\Proxy.php(28): GuzzleHttp\Handler\CurlHandler->__invoke(Object(GuzzleHttp\Psr7\Request), Array)
+#4 D:\phpStudy\WWW\qq_wallet\vendor\guzzlehttp\guzzle\src\Handler\Proxy.php(51): GuzzleHttp\Handler\Proxy::GuzzleHttp\Handler\{closure}(Object(GuzzleHttp\Psr7\Request), Array)
+#5 D:\phpStudy\WWW\qq_wallet\vendor\guzzlehttp\guzzle\src\PrepareBodyMiddleware.php(37): GuzzleHttp\Handler\Proxy::GuzzleHttp\Handler\{closure}(Object(GuzzleHttp\Psr7\Request), Array)
+#6 D:\phpStudy\WWW\qq_wallet\vendor\guzzlehttp\guzzle\src\Middleware.php(30): GuzzleHttp\PrepareBodyMiddleware->__invoke(Object(GuzzleHttp\Psr7\Request), Array)
+#7 D:\phpStudy\WWW\qq_wallet\vendor\guzzlehttp\guzzle\src\RedirectMiddleware.php(70): GuzzleHttp\Middleware::GuzzleHttp\{closure}(Object(GuzzleHttp\Psr7\Request), Array)
+#8 D:\phpStudy\WWW\qq_wallet\vendor\guzzlehttp\guzzle\src\Middleware.php(60): GuzzleHttp\RedirectMiddleware->__invoke(Object(GuzzleHttp\Psr7\Request), Array)
+#9 D:\phpStudy\WWW\qq_wallet\vendor\guzzlehttp\guzzle\src\HandlerStack.php(67): GuzzleHttp\Middleware::GuzzleHttp\{closure}(Object(GuzzleHttp\Psr7\Request), Array)
+#10 D:\phpStudy\WWW\qq_wallet\vendor\guzzlehttp\guzzle\src\Client.php(276): GuzzleHttp\HandlerStack->__invoke(Object(GuzzleHttp\Psr7\Request), Array)
+#11 D:\phpStudy\WWW\qq_wallet\vendor\guzzlehttp\guzzle\src\Client.php(124): GuzzleHttp\Client->transfer(Object(GuzzleHttp\Psr7\Request), Array)
+#12 D:\phpStudy\WWW\qq_wallet\vendor\guzzlehttp\guzzle\src\Client.php(130): GuzzleHttp\Client->requestAsync('get', Object(GuzzleHttp\Psr7\Uri), Array)
+#13 D:\phpStudy\WWW\qq_wallet\vendor\guzzlehttp\guzzle\src\Client.php(88): GuzzleHttp\Client->request('get', 'addresses/summa...', Array)
+#14 D:\phpStudy\WWW\qq_wallet\vendor\codybutz\cardano-php-api\src\Explorer\ExplorerAPI.php(144): GuzzleHttp\Client->__call('get', Array)
+#15 D:\phpStudy\WWW\qq_wallet\vendor\codybutz\cardano-php-api\src\Explorer\ExplorerAPI.php(119): Butz\Cardano\Explorer\ExplorerAPI->get('addresses/summa...')
+#16 D:\phpStudy\WWW\qq_wallet\vendor\codybutz\cardano-php-api\src\Explorer\ExplorerAPI.php(103): Butz\Cardano\Explorer\ExplorerAPI->getExplorer('addresses/summa...')
+#17 D:\phpStudy\WWW\qq_wallet\src\app\Api\Test.php(17): Butz\Cardano\Explorer\ExplorerAPI->getAddressSummary('27tWU7uzrR5MbKK...')
+#18 [internal function]: App\Api\Test->index()
+#19 D:\phpStudy\WWW\qq_wallet\vendor\phalapi\kernal\src\PhalApi.php(53): call_user_func(Array)
+#20 D:\phpStudy\WWW\qq_wallet\public\index.php(9): PhalApi\PhalApi->response()
+#21 {main}
+2018-09-15 14:24:00|ERROR|App.test.index|Butz\Cardano\Explorer\Exceptions\AddressNotFoundException: Address was not found. in D:\phpStudy\WWW\qq_wallet\vendor\codybutz\cardano-php-api\src\Explorer\ExplorerAPI.php:125
+Stack trace:
+#0 D:\phpStudy\WWW\qq_wallet\vendor\codybutz\cardano-php-api\src\Explorer\ExplorerAPI.php(103): Butz\Cardano\Explorer\ExplorerAPI->getExplorer('addresses/summa...')
+#1 D:\phpStudy\WWW\qq_wallet\src\app\Api\Test.php(17): Butz\Cardano\Explorer\ExplorerAPI->getAddressSummary('27tWU7uzrR5MbKK...')
+#2 [internal function]: App\Api\Test->index()
+#3 D:\phpStudy\WWW\qq_wallet\vendor\phalapi\kernal\src\PhalApi.php(53): call_user_func(Array)
+#4 D:\phpStudy\WWW\qq_wallet\public\index.php(9): PhalApi\PhalApi->response()
+#5 {main}
+2018-09-15 14:59:41|ERROR|App.test.create|Butz\Cardano\Explorer\Exceptions\AddressNotFoundException: Address was not found. in D:\phpStudy\WWW\qq_wallet\vendor\codybutz\cardano-php-api\src\Explorer\ExplorerAPI.php:125
+Stack trace:
+#0 D:\phpStudy\WWW\qq_wallet\vendor\codybutz\cardano-php-api\src\Explorer\ExplorerAPI.php(103): Butz\Cardano\Explorer\ExplorerAPI->getExplorer('addresses/summa...')
+#1 D:\phpStudy\WWW\qq_wallet\vendor\codybutz\cardano-php-api\test\Cardano\Explorer\ExplorerAPITest.php(41): Butz\Cardano\Explorer\ExplorerAPI->getAddressSummary('27tWU7uzrR5MbKK...')
+#2 D:\phpStudy\WWW\qq_wallet\src\app\Api\Test.php(24): Butz\Tests\Cardano\Explorer\ExplorerAPITest->testAddressSummarySuccess()
+#3 [internal function]: App\Api\Test->create()
+#4 D:\phpStudy\WWW\qq_wallet\vendor\phalapi\kernal\src\PhalApi.php(53): call_user_func(Array)
+#5 D:\phpStudy\WWW\qq_wallet\public\index.php(9): PhalApi\PhalApi->response()
+#6 {main}
+2018-09-15 15:11:50|ERROR|App.test.index|Butz\Cardano\Explorer\Exceptions\AddressNotFoundException: Address was not found. in D:\phpStudy\WWW\qq_wallet\vendor\codybutz\cardano-php-api\src\Explorer\ExplorerAPI.php:125
+Stack trace:
+#0 D:\phpStudy\WWW\qq_wallet\vendor\codybutz\cardano-php-api\src\Explorer\ExplorerAPI.php(103): Butz\Cardano\Explorer\ExplorerAPI->getExplorer('addresses/summa...')
+#1 D:\phpStudy\WWW\qq_wallet\src\app\Api\Test.php(18): Butz\Cardano\Explorer\ExplorerAPI->getAddressSummary('27tWU7uzrR5MbKK...')
+#2 [internal function]: App\Api\Test->index()
+#3 D:\phpStudy\WWW\qq_wallet\vendor\phalapi\kernal\src\PhalApi.php(53): call_user_func(Array)
+#4 D:\phpStudy\WWW\qq_wallet\public\index.php(9): PhalApi\PhalApi->response()
+#5 {main}
+2018-09-15 15:12:10|ERROR|App.test.index|Butz\Cardano\Explorer\Exceptions\AddressNotFoundException: Address was not found. in D:\phpStudy\WWW\qq_wallet\vendor\codybutz\cardano-php-api\src\Explorer\ExplorerAPI.php:125
+Stack trace:
+#0 D:\phpStudy\WWW\qq_wallet\vendor\codybutz\cardano-php-api\src\Explorer\ExplorerAPI.php(103): Butz\Cardano\Explorer\ExplorerAPI->getExplorer('addresses/summa...')
+#1 D:\phpStudy\WWW\qq_wallet\src\app\Api\Test.php(19): Butz\Cardano\Explorer\ExplorerAPI->getAddressSummary('27tWU7uzrR5MbKK...')
+#2 [internal function]: App\Api\Test->index()
+#3 D:\phpStudy\WWW\qq_wallet\vendor\phalapi\kernal\src\PhalApi.php(53): call_user_func(Array)
+#4 D:\phpStudy\WWW\qq_wallet\public\index.php(9): PhalApi\PhalApi->response()
+#5 {main}
+2018-09-15 15:13:04|ERROR|App.test.index|Butz\Cardano\Explorer\Exceptions\AddressNotFoundException: Address was not found. in D:\phpStudy\WWW\qq_wallet\vendor\codybutz\cardano-php-api\src\Explorer\ExplorerAPI.php:125
+Stack trace:
+#0 D:\phpStudy\WWW\qq_wallet\vendor\codybutz\cardano-php-api\src\Explorer\ExplorerAPI.php(103): Butz\Cardano\Explorer\ExplorerAPI->getExplorer('addresses/summa...')
+#1 D:\phpStudy\WWW\qq_wallet\src\app\Api\Test.php(19): Butz\Cardano\Explorer\ExplorerAPI->getAddressSummary('27tWU7uzrR5MbKK...')
+#2 [internal function]: App\Api\Test->index()
+#3 D:\phpStudy\WWW\qq_wallet\vendor\phalapi\kernal\src\PhalApi.php(53): call_user_func(Array)
+#4 D:\phpStudy\WWW\qq_wallet\public\index.php(9): PhalApi\PhalApi->response()
+#5 {main}
+2018-09-15 15:13:20|ERROR|App.test.index|Butz\Cardano\Explorer\Exceptions\AddressNotFoundException: Address was not found. in D:\phpStudy\WWW\qq_wallet\vendor\codybutz\cardano-php-api\src\Explorer\ExplorerAPI.php:125
+Stack trace:
+#0 D:\phpStudy\WWW\qq_wallet\vendor\codybutz\cardano-php-api\src\Explorer\ExplorerAPI.php(103): Butz\Cardano\Explorer\ExplorerAPI->getExplorer('addresses/summa...')
+#1 D:\phpStudy\WWW\qq_wallet\src\app\Api\Test.php(19): Butz\Cardano\Explorer\ExplorerAPI->getAddressSummary('27tWU7uzrR5MbKK...')
+#2 [internal function]: App\Api\Test->index()
+#3 D:\phpStudy\WWW\qq_wallet\vendor\phalapi\kernal\src\PhalApi.php(53): call_user_func(Array)
+#4 D:\phpStudy\WWW\qq_wallet\public\index.php(9): PhalApi\PhalApi->response()
+#5 {main}
+2018-09-15 15:28:59|ERROR|App.test.index|Butz\Cardano\Explorer\Exceptions\AddressNotFoundException: Address was not found. in D:\phpStudy\WWW\qq_wallet\vendor\codybutz\cardano-php-api\src\Explorer\ExplorerAPI.php:125
+Stack trace:
+#0 D:\phpStudy\WWW\qq_wallet\vendor\codybutz\cardano-php-api\src\Explorer\ExplorerAPI.php(103): Butz\Cardano\Explorer\ExplorerAPI->getExplorer('addresses/summa...')
+#1 D:\phpStudy\WWW\qq_wallet\src\app\Api\Test.php(19): Butz\Cardano\Explorer\ExplorerAPI->getAddressSummary('27tWU7uzrR5MbKK...')
+#2 [internal function]: App\Api\Test->index()
+#3 D:\phpStudy\WWW\qq_wallet\vendor\phalapi\kernal\src\PhalApi.php(53): call_user_func(Array)
+#4 D:\phpStudy\WWW\qq_wallet\public\index.php(9): PhalApi\PhalApi->response()
+#5 {main}
+2018-09-15 15:42:44|ERROR|App.test.index|Butz\Cardano\Explorer\Exceptions\AddressNotFoundException: Address was not found. in D:\phpStudy\WWW\qq_wallet\vendor\codybutz\cardano-php-api\src\Explorer\ExplorerAPI.php:125
+Stack trace:
+#0 D:\phpStudy\WWW\qq_wallet\vendor\codybutz\cardano-php-api\src\Explorer\ExplorerAPI.php(103): Butz\Cardano\Explorer\ExplorerAPI->getExplorer('addresses/summa...')
+#1 D:\phpStudy\WWW\qq_wallet\src\app\Api\Test.php(19): Butz\Cardano\Explorer\ExplorerAPI->getAddressSummary('27tWU7uzrR5MbKK...')
+#2 [internal function]: App\Api\Test->index()
+#3 D:\phpStudy\WWW\qq_wallet\vendor\phalapi\kernal\src\PhalApi.php(53): call_user_func(Array)
+#4 D:\phpStudy\WWW\qq_wallet\public\index.php(9): PhalApi\PhalApi->response()
+#5 {main}
+2018-09-15 15:44:31|ERROR|App.test.index|Butz\Cardano\Explorer\Exceptions\AddressNotFoundException: Address was not found. in D:\phpStudy\WWW\qq_wallet\vendor\codybutz\cardano-php-api\src\Explorer\ExplorerAPI.php:125
+Stack trace:
+#0 D:\phpStudy\WWW\qq_wallet\vendor\codybutz\cardano-php-api\src\Explorer\ExplorerAPI.php(103): Butz\Cardano\Explorer\ExplorerAPI->getExplorer('addresses/summa...')
+#1 D:\phpStudy\WWW\qq_wallet\src\app\Api\Test.php(19): Butz\Cardano\Explorer\ExplorerAPI->getAddressSummary('27tWU7uzrR5MbKK...')
+#2 [internal function]: App\Api\Test->index()
+#3 D:\phpStudy\WWW\qq_wallet\vendor\phalapi\kernal\src\PhalApi.php(53): call_user_func(Array)
+#4 D:\phpStudy\WWW\qq_wallet\public\index.php(9): PhalApi\PhalApi->response()
+#5 {main}
+2018-09-15 16:08:55|ERROR|App.test.index|Butz\Cardano\Explorer\Exceptions\AddressNotFoundException: Address was not found. in D:\phpStudy\WWW\qq_wallet\vendor\codybutz\cardano-php-api\src\Explorer\ExplorerAPI.php:125
+Stack trace:
+#0 D:\phpStudy\WWW\qq_wallet\vendor\codybutz\cardano-php-api\src\Explorer\ExplorerAPI.php(103): Butz\Cardano\Explorer\ExplorerAPI->getExplorer('addresses/summa...')
+#1 D:\phpStudy\WWW\qq_wallet\src\app\Api\Test.php(19): Butz\Cardano\Explorer\ExplorerAPI->getAddressSummary('27tWU7uzrR5MbKK...')
+#2 [internal function]: App\Api\Test->index()
+#3 D:\phpStudy\WWW\qq_wallet\vendor\phalapi\kernal\src\PhalApi.php(53): call_user_func(Array)
+#4 D:\phpStudy\WWW\qq_wallet\public\index.php(9): PhalApi\PhalApi->response()
+#5 {main}

+ 24 - 0
runtime/log/201809/20180916.log

@@ -0,0 +1,24 @@
+2018-09-16 18:30:38|ERROR|App.test.index|GuzzleHttp\Exception\ConnectException: cURL error 28: Operation timed out after 16 milliseconds with 0 out of 0 bytes received (see https://curl.haxx.se/libcurl/c/libcurl-errors.html) in D:\phpStudy\WWW\qq_wallet\vendor\guzzlehttp\guzzle\src\Handler\CurlFactory.php:185
+Stack trace:
+#0 D:\phpStudy\WWW\qq_wallet\vendor\guzzlehttp\guzzle\src\Handler\CurlFactory.php(149): GuzzleHttp\Handler\CurlFactory::createRejection(Object(GuzzleHttp\Handler\EasyHandle), Array)
+#1 D:\phpStudy\WWW\qq_wallet\vendor\guzzlehttp\guzzle\src\Handler\CurlFactory.php(102): GuzzleHttp\Handler\CurlFactory::finishError(Object(GuzzleHttp\Handler\CurlHandler), Object(GuzzleHttp\Handler\EasyHandle), Object(GuzzleHttp\Handler\CurlFactory))
+#2 D:\phpStudy\WWW\qq_wallet\vendor\guzzlehttp\guzzle\src\Handler\CurlHandler.php(43): GuzzleHttp\Handler\CurlFactory::finish(Object(GuzzleHttp\Handler\CurlHandler), Object(GuzzleHttp\Handler\EasyHandle), Object(GuzzleHttp\Handler\CurlFactory))
+#3 D:\phpStudy\WWW\qq_wallet\vendor\guzzlehttp\guzzle\src\Handler\Proxy.php(28): GuzzleHttp\Handler\CurlHandler->__invoke(Object(GuzzleHttp\Psr7\Request), Array)
+#4 D:\phpStudy\WWW\qq_wallet\vendor\guzzlehttp\guzzle\src\Handler\Proxy.php(51): GuzzleHttp\Handler\Proxy::GuzzleHttp\Handler\{closure}(Object(GuzzleHttp\Psr7\Request), Array)
+#5 D:\phpStudy\WWW\qq_wallet\vendor\guzzlehttp\guzzle\src\PrepareBodyMiddleware.php(37): GuzzleHttp\Handler\Proxy::GuzzleHttp\Handler\{closure}(Object(GuzzleHttp\Psr7\Request), Array)
+#6 D:\phpStudy\WWW\qq_wallet\vendor\guzzlehttp\guzzle\src\Middleware.php(30): GuzzleHttp\PrepareBodyMiddleware->__invoke(Object(GuzzleHttp\Psr7\Request), Array)
+#7 D:\phpStudy\WWW\qq_wallet\vendor\guzzlehttp\guzzle\src\RedirectMiddleware.php(70): GuzzleHttp\Middleware::GuzzleHttp\{closure}(Object(GuzzleHttp\Psr7\Request), Array)
+#8 D:\phpStudy\WWW\qq_wallet\vendor\guzzlehttp\guzzle\src\Middleware.php(60): GuzzleHttp\RedirectMiddleware->__invoke(Object(GuzzleHttp\Psr7\Request), Array)
+#9 D:\phpStudy\WWW\qq_wallet\vendor\guzzlehttp\guzzle\src\HandlerStack.php(67): GuzzleHttp\Middleware::GuzzleHttp\{closure}(Object(GuzzleHttp\Psr7\Request), Array)
+#10 D:\phpStudy\WWW\qq_wallet\vendor\guzzlehttp\guzzle\src\Client.php(276): GuzzleHttp\HandlerStack->__invoke(Object(GuzzleHttp\Psr7\Request), Array)
+#11 D:\phpStudy\WWW\qq_wallet\vendor\guzzlehttp\guzzle\src\Client.php(124): GuzzleHttp\Client->transfer(Object(GuzzleHttp\Psr7\Request), Array)
+#12 D:\phpStudy\WWW\qq_wallet\vendor\guzzlehttp\guzzle\src\Client.php(130): GuzzleHttp\Client->requestAsync('get', Object(GuzzleHttp\Psr7\Uri), Array)
+#13 D:\phpStudy\WWW\qq_wallet\vendor\guzzlehttp\guzzle\src\Client.php(88): GuzzleHttp\Client->request('get', 'addresses/summa...', Array)
+#14 D:\phpStudy\WWW\qq_wallet\vendor\codybutz\cardano-php-api\src\Explorer\ExplorerAPI.php(144): GuzzleHttp\Client->__call('get', Array)
+#15 D:\phpStudy\WWW\qq_wallet\vendor\codybutz\cardano-php-api\src\Explorer\ExplorerAPI.php(119): Butz\Cardano\Explorer\ExplorerAPI->get('addresses/summa...')
+#16 D:\phpStudy\WWW\qq_wallet\vendor\codybutz\cardano-php-api\src\Explorer\ExplorerAPI.php(103): Butz\Cardano\Explorer\ExplorerAPI->getExplorer('addresses/summa...')
+#17 D:\phpStudy\WWW\qq_wallet\src\app\Api\Test.php(19): Butz\Cardano\Explorer\ExplorerAPI->getAddressSummary('27tWU7uzrR5MbKK...')
+#18 [internal function]: App\Api\Test->index()
+#19 D:\phpStudy\WWW\qq_wallet\vendor\phalapi\kernal\src\PhalApi.php(53): call_user_func(Array)
+#20 D:\phpStudy\WWW\qq_wallet\public\index.php(9): PhalApi\PhalApi->response()
+#21 {main}

+ 67 - 0
runtime/log/201809/20180917.log

@@ -0,0 +1,67 @@
+2018-09-17 07:58:16|ERROR|App.test.index|Butz\Cardano\Explorer\Exceptions\AddressNotFoundException: Address was not found. in D:\phpStudy\WWW\qq_wallet\vendor\codybutz\cardano-php-api\src\Explorer\ExplorerAPI.php:125
+Stack trace:
+#0 D:\phpStudy\WWW\qq_wallet\vendor\codybutz\cardano-php-api\src\Explorer\ExplorerAPI.php(103): Butz\Cardano\Explorer\ExplorerAPI->getExplorer('addresses/summa...')
+#1 D:\phpStudy\WWW\qq_wallet\src\app\Api\Test.php(19): Butz\Cardano\Explorer\ExplorerAPI->getAddressSummary('27tWU7uzrR5MbKK...')
+#2 [internal function]: App\Api\Test->index()
+#3 D:\phpStudy\WWW\qq_wallet\vendor\phalapi\kernal\src\PhalApi.php(53): call_user_func(Array)
+#4 D:\phpStudy\WWW\qq_wallet\public\index.php(9): PhalApi\PhalApi->response()
+#5 {main}
+2018-09-17 10:30:13|ERROR|App.test.test|RuntimeException in D:\phpStudy\WWW\qq_wallet\vendor\phpninjas\mnemonics\src\Mnemonic.php:32
+Stack trace:
+#0 D:\phpStudy\WWW\qq_wallet\src\app\Api\Test.php(21): phpninjas\Mnemonics\Mnemonic->__construct(Object(Closure))
+#1 D:\phpStudy\WWW\qq_wallet\src\app\Api\Test.php(25): App\Api\Test->setUp()
+#2 [internal function]: App\Api\Test->test()
+#3 D:\phpStudy\WWW\qq_wallet\vendor\phalapi\kernal\src\PhalApi.php(53): call_user_func(Array)
+#4 D:\phpStudy\WWW\qq_wallet\public\index.php(9): PhalApi\PhalApi->response()
+#5 {main}
+2018-09-17 10:31:01|ERROR|App.test.test|RuntimeException: Entropy bits must be divisible by 32 in D:\phpStudy\WWW\qq_wallet\vendor\phpninjas\mnemonics\src\Mnemonic.php:44
+Stack trace:
+#0 D:\phpStudy\WWW\qq_wallet\src\app\Api\Test.php(26): phpninjas\Mnemonics\Mnemonic->toMnemonic('yanfei')
+#1 [internal function]: App\Api\Test->test()
+#2 D:\phpStudy\WWW\qq_wallet\vendor\phalapi\kernal\src\PhalApi.php(53): call_user_func(Array)
+#3 D:\phpStudy\WWW\qq_wallet\public\index.php(9): PhalApi\PhalApi->response()
+#4 {main}
+2018-09-17 10:33:13|ERROR|App.test.test|RuntimeException: Entropy bits must be divisible by 32 in D:\phpStudy\WWW\qq_wallet\vendor\phpninjas\mnemonics\src\Mnemonic.php:44
+Stack trace:
+#0 D:\phpStudy\WWW\qq_wallet\src\app\Api\Test.php(26): phpninjas\Mnemonics\Mnemonic->toMnemonic('yanfei')
+#1 [internal function]: App\Api\Test->test()
+#2 D:\phpStudy\WWW\qq_wallet\vendor\phalapi\kernal\src\PhalApi.php(53): call_user_func(Array)
+#3 D:\phpStudy\WWW\qq_wallet\public\index.php(9): PhalApi\PhalApi->response()
+#4 {main}
+2018-09-17 10:33:51|ERROR|App.test.test|RuntimeException: Entropy bits must be divisible by 32 in D:\phpStudy\WWW\qq_wallet\vendor\phpninjas\mnemonics\src\Mnemonic.php:44
+Stack trace:
+#0 D:\phpStudy\WWW\qq_wallet\src\app\Api\Test.php(26): phpninjas\Mnemonics\Mnemonic->toMnemonic('yanfei123')
+#1 [internal function]: App\Api\Test->test()
+#2 D:\phpStudy\WWW\qq_wallet\vendor\phalapi\kernal\src\PhalApi.php(53): call_user_func(Array)
+#3 D:\phpStudy\WWW\qq_wallet\public\index.php(9): PhalApi\PhalApi->response()
+#4 {main}
+2018-09-17 10:46:14|ERROR|App.dockCoin.create|RuntimeException: Entropy bits must be divisible by 32 in D:\phpStudy\WWW\qq_wallet\vendor\phpninjas\mnemonics\src\Mnemonic.php:44
+Stack trace:
+#0 D:\phpStudy\WWW\qq_wallet\src\app\Api\Daedalus.php(98): phpninjas\Mnemonics\Mnemonic->toMnemonic('yanfei1123')
+#1 [internal function]: App\Api\Daedalus::createAddress('yanfei1123')
+#2 D:\phpStudy\WWW\qq_wallet\src\app\Api\dockCoin.php(45): call_user_func(Array, 'yanfei1')
+#3 [internal function]: App\Api\dockCoin->create()
+#4 D:\phpStudy\WWW\qq_wallet\vendor\phalapi\kernal\src\PhalApi.php(53): call_user_func(Array)
+#5 D:\phpStudy\WWW\qq_wallet\public\index.php(9): PhalApi\PhalApi->response()
+#6 {main}
+2018-09-17 10:46:21|ERROR|App.dockCoin.create|RuntimeException: Entropy bits must be divisible by 32 in D:\phpStudy\WWW\qq_wallet\vendor\phpninjas\mnemonics\src\Mnemonic.php:44
+Stack trace:
+#0 D:\phpStudy\WWW\qq_wallet\src\app\Api\Daedalus.php(98): phpninjas\Mnemonics\Mnemonic->toMnemonic('yanfei1123')
+#1 [internal function]: App\Api\Daedalus::createAddress('yanfei1123')
+#2 D:\phpStudy\WWW\qq_wallet\src\app\Api\dockCoin.php(45): call_user_func(Array, 'yanfei1')
+#3 [internal function]: App\Api\dockCoin->create()
+#4 D:\phpStudy\WWW\qq_wallet\vendor\phalapi\kernal\src\PhalApi.php(53): call_user_func(Array)
+#5 D:\phpStudy\WWW\qq_wallet\public\index.php(9): PhalApi\PhalApi->response()
+#6 {main}
+2018-09-17 11:38:17|ERROR|App.dockCoin.send|PDOException: Operand should contain 1 column(s) in D:\phpStudy\WWW\qq_wallet\vendor\phalapi\notorm\src\NotORM\Result.php:264
+Stack trace:
+#0 D:\phpStudy\WWW\qq_wallet\vendor\phalapi\notorm\src\NotORM\Result.php(341): NotORM_Result->query('INSERT INTO use...', Array)
+#1 D:\phpStudy\WWW\qq_wallet\vendor\phalapi\notorm\src\NotORM\Result.php(358): NotORM_Result->insert_multi(Array)
+#2 D:\phpStudy\WWW\qq_wallet\vendor\phalapi\kernal\src\Model\NotORMModel.php(42): NotORM_Result->insert(Array)
+#3 D:\phpStudy\WWW\qq_wallet\src\app\Api\Daedalus.php(195): PhalApi\Model\NotORMModel->insert(Array)
+#4 [internal function]: App\Api\Daedalus::sendFrom(Array)
+#5 D:\phpStudy\WWW\qq_wallet\src\app\Api\dockCoin.php(71): call_user_func(Array, Array)
+#6 [internal function]: App\Api\dockCoin->send()
+#7 D:\phpStudy\WWW\qq_wallet\vendor\phalapi\kernal\src\PhalApi.php(53): call_user_func(Array)
+#8 D:\phpStudy\WWW\qq_wallet\public\index.php(9): PhalApi\PhalApi->response()
+#9 {main}

+ 0 - 0
runtime/log/201809/20180918.log


+ 0 - 0
runtime/log/201809/20180919.log


+ 0 - 0
runtime/log/201809/20180920.log


+ 9 - 0
runtime/log/201809/20180926.log

@@ -0,0 +1,9 @@
+2018-09-26 21:22:40|ERROR|App.dockcoin.create|RuntimeException: Entropy bits must be divisible by 32 in D:\phpStudy\WWW\qq_wallet\vendor\phpninjas\mnemonics\src\Mnemonic.php:44
+Stack trace:
+#0 D:\phpStudy\WWW\qq_wallet\src\app\Api\Daedalus.php(103): phpninjas\Mnemonics\Mnemonic->toMnemonic('XM3826310000000')
+#1 [internal function]: App\Api\Daedalus::createAddress('yanfei5')
+#2 D:\phpStudy\WWW\qq_wallet\src\app\Api\dockCoin.php(45): call_user_func(Array, 'yanfei5')
+#3 [internal function]: App\Api\dockCoin->create()
+#4 D:\phpStudy\WWW\qq_wallet\vendor\phalapi\kernal\src\PhalApi.php(53): call_user_func(Array)
+#5 D:\phpStudy\WWW\qq_wallet\public\index.php(9): PhalApi\PhalApi->response()
+#6 {main}

+ 0 - 0
runtime/log/201809/20180927.log


+ 0 - 0
runtime/log/201810/20181012.log


+ 193 - 0
sdk/C_Sharp/PhalApiClient/PhalApiClient.cs

@@ -0,0 +1,193 @@
+
+
+using System;
+using System.Collections.Generic;
+using System.Text;
+using System.Net;
+using System.IO;
+
+namespace PhalApiClientSDK
+{
+
+    /**
+     * PhalApi客户端SDK包(JAVA版)
+     *
+     * - 以接口查询语言(ASQL)的方式来实现接口请求
+     * - 出于简明客户端,将全部的类都归于同一个文件,避免过多的加载
+     * 
+     * <br>使用示例:<br>
+     ```
+     * PhalApiClientResponse response = PhalApiClient.create()
+     *   .withHost("http://demo.phalapi.net/")
+     *   .withService("Default.Index")
+     *   .withparamsList("name", "dogstar")
+     *   .withTimeout(3000)
+     *   .request();
+     *
+     * Log.v("response ret", response.ret + "");
+     * Log.v("response data", response.data);
+     * Log.v("response msg", response.msg);
+    ```
+        *
+        * @package     PhalApi\Response
+        * @license     http://www.phalapi.net/license GPL 协议
+        * @link        http://www.phalapi.net/
+        * @author      dogstar <chanzonghuang@gmail.com> 2015-10-16
+     */
+
+    public class PhalApiClient {
+
+        protected String host;
+        protected PhalApiClientFilter filter;
+        protected PhalApiClientParser parser;
+        protected String service;
+        protected int timeoutMs;
+        protected Dictionary<String, String> paramsList;
+
+        /**
+         * 创建一个接口实例,注意:不是单例模式
+         * @return PhalApiClient
+         */
+        public static PhalApiClient create() {
+            return new PhalApiClient();
+        }
+
+        protected PhalApiClient() {
+    	    this.host = "";
+            this.parser = new PhalApiClientParserJson();
+
+            this.reset();
+        }
+
+        /**
+         * 设置接口域名
+         * @param String host
+         * @return PhalApiClient
+         */
+        public PhalApiClient withHost(String host) {
+            this.host = host;
+            return this;
+        }
+
+        /**
+         * 设置过滤器,与服务器的DI().filter对应
+         * @param PhalApiClientFilter filter 过滤器
+         * @return PhalApiClient
+         */
+        public PhalApiClient withFilter(PhalApiClientFilter filter) {
+            this.filter = filter;
+            return this;
+        }
+
+        /**
+         * 设置结果解析器,仅当不是JSON返回格式时才需要设置
+         * @param PhalApiClientParser parser 结果解析器
+         * @return PhalApiClient
+         */
+        public PhalApiClient withParser(PhalApiClientParser parser) {
+            this.parser = parser;
+            return this;
+        }
+
+        /**
+         * 重置,将接口服务名称、接口参数、请求超时进行重置,便于重复请求
+         * @return PhalApiClient
+         */
+        public PhalApiClient reset() {
+            this.service = "";
+            this.timeoutMs = 3000;
+            this.paramsList = new Dictionary<String, String>();
+        
+            return this;
+        }
+
+        /**
+         * 设置将在调用的接口服务名称,如:Default.Index
+         * @param String service 接口服务名称
+         * @return PhalApiClient
+         */
+        public PhalApiClient withService(String service) {
+            this.service = service;
+            return this;
+        }
+
+        /**
+         * 设置接口参数,此方法是唯一一个可以多次调用并累加参数的操作
+         * @param String name 参数名字
+         * @param String value 值
+         * @return PhalApiClient
+         */
+        public PhalApiClient withParams(String name, String value) {
+            this.paramsList.Add(name, value);
+            return this;
+        }
+
+        /**
+         * 设置超时时间,单位毫秒
+         * @param int timeoutMS 超时时间,单位毫秒
+         * @return PhalApiClient
+         */
+        public PhalApiClient withTimeout(int timeoutMs) {
+            this.timeoutMs = timeoutMs;
+            return this;
+        }
+
+        /**
+         * 发起接口请求
+         * @return PhalApiClientResponse
+         */
+        public PhalApiClientResponse request() {
+            String url = this.host;
+
+            if (this.service != null && this.service.Length > 0) {
+                url += "?service=" + this.service;
+            }
+            if (this.filter != null) {
+                this.filter.filter(this.service, this.paramsList);
+            }
+
+            try {
+        	    String rs = this.doRequest(url, this.paramsList, this.timeoutMs);
+        	    return this.parser.parse(rs);
+            } catch (Exception ex) {
+        	    //return new PhalApiClientResponse(408, new JSONObject(), ex.Message);
+                return new PhalApiClientResponse(408); //TODO
+            }
+        }
+    
+	    protected String doRequest(String requestUrl, Dictionary<String, String> paramsList, int timeoutMs) {
+		    String result = null;
+            Encoding encoding = Encoding.Default;
+
+            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(requestUrl);
+
+            request.Method = "post";
+
+            request.Accept = "text/html, application/xhtml+xml, */*";
+
+            request.ContentType = "application/x-www-form-urlencoded";
+
+            String strPostdata = "";
+            //KeyValuePair<T,K>
+            foreach (KeyValuePair<String, String> kv in paramsList)
+            {
+                strPostdata += "&" + kv.Key + "=" + kv.Value;
+            }
+            byte[] buffer = encoding.GetBytes(strPostdata);
+
+            request.ContentLength = buffer.Length;
+
+            request.GetRequestStream().Write(buffer, 0, buffer.Length);
+
+            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
+
+            using (StreamReader reader = new StreamReader(response.GetResponseStream(), System.Text.Encoding.GetEncoding("utf-8")))
+            {
+
+                return reader.ReadToEnd();
+            }  
+
+		   
+	    }
+    }
+}

+ 24 - 0
sdk/C_Sharp/PhalApiClient/PhalApiClientFilter.cs

@@ -0,0 +1,24 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+
+namespace PhalApiClientSDK
+{
+    /**
+     * 接口过滤器
+     * 
+     * - 可用于接口签名生成
+     */
+    public interface PhalApiClientFilter {
+
+        /**
+         * 过滤操作
+         * @param string service 接口服务名称
+         * @param Map<String, String> params 接口参数,注意是引用。可以直接修改
+         * @return null
+         */
+	    void filter(String service, Dictionary<String, String> paramsList);
+    }
+
+}

+ 25 - 0
sdk/C_Sharp/PhalApiClient/PhalApiClientParser.cs

@@ -0,0 +1,25 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+
+namespace PhalApiClientSDK
+{
+    /**
+    * 接口结果解析器
+    * 
+    * - 可用于不同接口返回格式的处理
+    */
+    public interface PhalApiClientParser
+    {
+
+        /**
+         * 结果解析
+         * @param String apiResult
+         * @return PhalApiClientResponse
+         */
+        PhalApiClientResponse parse(String apiResult);
+    }
+
+
+}

+ 24 - 0
sdk/C_Sharp/PhalApiClient/PhalApiClientParserJson.cs

@@ -0,0 +1,24 @@
+using Newtonsoft.Json;
+using System;
+
+namespace PhalApiClientSDK
+{
+    /**
+    * JSON解析
+    */
+    public class PhalApiClientParserJson : PhalApiClientParser {
+
+	    public PhalApiClientResponse parse(String apiResult) {
+		    if (apiResult == null) {
+                return new PhalApiClientResponse(408, "", "Request Timeout");
+		    }
+		
+		    try {
+
+                return JsonConvert.DeserializeObject<PhalApiClientResponse>(apiResult);
+		    } catch (Exception ex) {
+			    return new PhalApiClientResponse(500, "", "Internal Server Error: " + ex.Message);
+		    }
+	    }
+    }
+}

+ 51 - 0
sdk/C_Sharp/PhalApiClient/PhalApiClientResponse.cs

@@ -0,0 +1,51 @@
+using System;
+
+namespace PhalApiClientSDK
+{
+    /**
+     * 接口返回结果
+     *
+     * - 与接口返回的格式对应,即有:ret/data/msg
+     */
+    public class PhalApiClientResponse
+    {
+        public int ret { get; set; }
+
+        public dynamic data { get; set; }
+
+        public String msg { get; set; }
+
+        
+
+        /**
+         * 完全构造函数
+         * @param int ret
+         * @param JSONObject data
+         * @param String msg
+         */
+        public PhalApiClientResponse(int ret, dynamic data, String msg)
+        {
+            this.ret = ret;
+            this.data = data;
+            this.msg = msg;
+        }
+
+        public PhalApiClientResponse(int ret, dynamic data)
+        {
+            this.ret = ret;
+            this.data = data;
+            this.msg = "";
+        }
+
+        public PhalApiClientResponse(int ret)
+        {
+            this.ret = ret;
+            this.data = "";
+            this.msg = "";
+        }
+        public PhalApiClientResponse()
+        {
+            
+        }
+    }
+}

+ 144 - 0
sdk/Go/PhalApiClient/PhalApiClient.go

@@ -0,0 +1,144 @@
+package PhalApiClient
+
+import (
+	"encoding/json"
+	"errors"
+	"io/ioutil"
+	"net"
+	"net/http"
+	"net/url"
+	"time"
+)
+
+/**
+ * PhalApi客户端SDK包(Go版)
+ *
+ *
+ * <br>使用示例:<br>
+ ```
+	rs, err := PhalApiClient.NewRequest().
+		WithHost(`http://127.0.0.1/PhalApi/Public/index.php`).
+		WithService("Default.index").
+		WithParams(url.Values{}).
+		Get()
+	if err != nil {
+		fmt.Println(err.Error())
+	} else {
+		fmt.Println("code------------------------", rs.Code)
+		fmt.Println("data------------------------", rs.Data)
+		fmt.Println("msg------------------------", rs.Msg)
+	}
+```
+    *
+    * @package     PhalApi\SDK
+    * @author      prettyyjnic <prettyyjnic@qq.com> 2016-03-09
+*/
+
+type request struct {
+	Host    string
+	Service string
+	Params  url.Values
+	Timeout time.Duration
+}
+
+type result struct {
+	Code int64       `json:"ret"`
+	Data interface{} `json:"data"`
+	Msg  interface{} `json:"msg"`
+}
+
+func NewRequest() *request {
+	ptr_request := new(request)
+	return ptr_request
+}
+
+func (this *request) WithHost(host string) *request {
+	this.Host = host
+	return this
+}
+
+func (this *request) WithService(service string) *request {
+	this.Service = service
+	return this
+}
+
+func (this *request) WithParams(params url.Values) *request {
+	this.Params = params
+	return this
+}
+
+func (this *request) WithTimeout(timeout time.Duration) *request {
+	this.Timeout = timeout
+	return this
+}
+
+func (this *request) Reset() {
+	this.Params = url.Values{}
+	this.Host = ""
+	this.Service = ""
+	this.Timeout = 0
+}
+
+func (this *request) Get() (*result, error) {
+	client := this.getClient()
+	var str_url string
+	if this.Service != "" {
+		this.Params.Add("service", this.Service)
+	}
+	str_url = this.Host + "?" + this.Params.Encode()
+	resp, err := client.Get(str_url)
+	if err != nil {
+		return nil, err
+	} else {
+		defer resp.Body.Close()
+		return dealResult(resp)
+	}
+
+}
+
+func (this *request) Post() (*result, error) {
+	client := this.getClient()
+	var str_url string
+	if this.Service != "" {
+		str_url = this.Host + "?service=" + this.Service
+	} else {
+		str_url = this.Host
+	}
+	resp, err := client.PostForm(str_url, this.Params)
+	if err != nil {
+		return nil, err
+	} else {
+		defer resp.Body.Close()
+		return dealResult(resp)
+	}
+}
+
+func dealResult(response *http.Response) (*result, error) {
+	if response.Status == "200 OK" {
+		ret := new(result)
+		body, _ := ioutil.ReadAll(response.Body)
+		json.Unmarshal(body, ret)
+		return ret, nil
+	} else {
+		return nil, errors.New(response.Status)
+	}
+}
+
+func (this *request) getClient() *http.Client {
+	tr := &http.Transport{
+		Dial: func(netw, addr string) (net.Conn, error) {
+			if this.Timeout == 0 {
+				this.Timeout = time.Second * 3
+			}
+			conn, err := net.DialTimeout(netw, addr, this.Timeout)
+			if err != nil {
+				return nil, err
+			}
+			conn.SetDeadline(time.Now().Add(this.Timeout))
+			return conn, nil
+		},
+		ResponseHeaderTimeout: this.Timeout,
+	}
+	client := &http.Client{Transport: tr}
+	return client
+}

+ 22 - 0
sdk/Go/main.go

@@ -0,0 +1,22 @@
+package main
+
+import (
+	"./PhalApiClient"
+	"fmt"
+	"net/url"
+)
+
+func main() {
+	rs, err := PhalApiClient.NewRequest().
+		WithHost(`http://127.0.0.1/PhalApi/Public/index.php`).
+		WithService("Default.index").
+		WithParams(url.Values{}).
+		Get()
+	if err != nil {
+		fmt.Println(err.Error())
+	} else {
+		fmt.Println("code------------------------", rs.Code)
+		fmt.Println("data------------------------", rs.Data)
+		fmt.Println("msg------------------------", rs.Msg)
+	}
+}

+ 175 - 0
sdk/JAVA/README.md

@@ -0,0 +1,175 @@
+
+## 使用说明
+将框架目录下的 ./SDK/JAVA/net 目录中的全部代码拷贝到项目里面即可使用。如:  
+
+![](http://7qnay5.com1.z0.glb.clouddn.com/qq20151017100539.jpg)  
+  
+##  代码示例
+如下是使用的代码场景片段。  
+  
+首先,我们需要导入SDK包:
+```java
+//FullscreenActivity.java
+import net.phalapi.sdk.*;
+```
+  
+然后,准备一个子线程调用,并在此线程中实现接口请求:
+```java
+    /**
+     * 网络操作相关的子线程
+     */  
+    Runnable networkTask = new Runnable() {  
+      
+        @Override  
+        public void run() {  
+            // TODO  
+            // 在这里进行 http request.网络请求相关操作  
+            
+        	PhalApiClient client = PhalApiClient.create()
+	       			    .withHost("http://demo.phalapi.net/");
+	       	
+	       	PhalApiClientResponse response = client
+	       			    .withService("Default.Index")
+	       			    .withParams("username", "dogstar")
+	       			    .withTimeout(3000)
+	       			    .request();
+
+	   		String content = "";
+	   		content += "ret=" + response.getRet() + "\n";
+	   		if (response.getRet() == 200) {
+				try {
+					JSONObject data = new JSONObject(response.getData());
+					content += "data.title=" + data.getString("title") + "\n";
+					content += "data.content=" + data.getString("content") + "\n";
+					content += "data.version=" + data.getString("version") + "\n";
+				} catch (JSONException ex) {
+					  
+				}
+	   		}
+			content += "msg=" + response.getMsg() + "\n";
+			
+			Log.v("[PhalApiClientResponse]", content);
+            
+            
+            Message msg = new Message();  
+            Bundle data = new Bundle();  
+            data.putString("value", content);  
+            msg.setData(data);  
+            handler.sendMessage(msg);  
+        }  
+    }; 
+```
+  
+接着,实现线程回调的hander:
+```java
+    Handler handler = new Handler() {  
+        @Override  
+        public void handleMessage(Message msg) {  
+            super.handleMessage(msg);  
+            Bundle data = msg.getData();  
+            String val = data.getString("value");  
+            Log.i("mylog", "请求结果为-->" + val);  
+            // TODO  
+            // UI界面的更新等相关操作  
+        }  
+    }; 
+``` 
+  
+最后,在我们需要的地方启动:
+```java
+    View.OnClickListener mDummyBtnClickListener = new View.OnClickListener() {
+        
+        @Override
+        public void onClick(View arg0) {
+            // 开启一个子线程,进行网络操作,等待有返回结果,使用handler通知UI  
+            new Thread(networkTask).start();  
+            
+            // ....
+        }
+    };
+```
+
+### 再一次调用和异常请求
+当我们需要再次使用同一个接口实例进行请求时,需要先进行重置,以便清空之前的接口参数,如:
+```java
+//再一次请求
+response = client.reset() //重置
+		.withService("User.GetBaseInfo")
+		.withParams("user_id", "1")
+		.request();
+
+
+content = "";
+content += "ret=" + response.getRet() + "\n";
+if (response.getRet() == 200) {
+	try {
+		JSONObject data = new JSONObject(response.getData());
+		JSONObject info = new JSONObject(data.getString("info"));
+		
+		content += "data.info.id=" + info.getString("id") + "\n";
+		content += "data.info.name=" + info.getString("name") + "\n";
+		content += "data.info.from=" + info.getString("from") + "\n";
+	} catch (JSONException ex) {
+		  
+	}
+}
+content += "msg=" + response.getMsg() + "\n";
+
+Log.v("[PhalApiClientResponse]", content);
+```
+  
+异常情况下,即ret != 200时,将返回错误的信息,如:
+```java
+//再来试一下异常的请求
+response = client.reset()
+		.withService("XXX.XXXX")
+		.withParams("user_id", "1")
+		.request();
+
+content = "";
+content += "ret=" + response.getRet() + "\n";
+content += "msg=" + response.getMsg() + "\n";
+
+Log.v("[PhalApiClientResponse]", content);
+```
+##  运行效果
+运行后,查询log,可以看到:  
+
+![](http://7qnay5.com1.z0.glb.clouddn.com/QQ20151017154114.jpg)  
+
+  
+可以注意到,在调试模式时,会有接口请求的链接和返回的结果日记,如:  
+```
+10-17 07:40:55.268: D/[PhalApiClient requestUrl](1376): http://demo.phalapi.net/?service=User.GetBaseInfo&user_id=1
+10-17 07:40:55.364: D/[PhalApiClient apiResult](1376): {"ret":200,"data":{"code":0,"msg":"","info":{"id":"1","name":"dogstar","from":"oschina"}},"msg":""}
+```
+
+## 扩展你的过滤器和结果解析器
+### (1)扩展过滤器
+当服务端接口需要接口签名验证,或者接口参数加密传送,或者压缩传送时,可以实现此过滤器,以便和服务端操持一致。  
+  
+当需要扩展时,分两步。首先,需要实现过滤器接口:  
+```java
+class MyFilter implements PhalApiClientFilter {
+
+        public void filter(String service, Map<String, String> params) {
+            //TODO ...
+        }
+}
+```
+然后设置过滤器:
+```java
+PhalApiClientResponse response = PhalApiClient.create()
+		   .withHost("http://demo.phalapi.net/")
+		   .withFilter(new MyFilter())
+		   // ...
+		   .request();
+```
+### (2)扩展结果解析器
+当返回的接口结果不是JSON格式时,可以重新实现此接口。  
+  
+当需要扩展时,同样分两步。类似过滤器扩展,这里不再赘述。
+##  特别注意:Android之NetworkOnMainThreadException异常
+由于此SDK包是使用HttpURLConnection发起请求时,所以在主线程调用时会触发NetworkOnMainThreadException异常,具体可参考: [Android之NetworkOnMainThreadException异常](http://blog.csdn.net/mad1989/article/details/25964495)  
+  
+所以,需要使用子线程来发起请求,或者重新继承改用异步的请求。  

+ 218 - 0
sdk/JAVA/net/phalapi/sdk/PhalApiClient.java

@@ -0,0 +1,218 @@
+package net.phalapi.sdk;
+
+import java.io.BufferedReader;
+import java.io.DataOutputStream;
+import java.io.IOException;
+import java.io.InputStreamReader;
+import java.net.HttpURLConnection;
+import java.net.URL;
+import java.net.URLEncoder;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.Map;
+import java.util.Map.Entry;
+
+import org.json.JSONObject;
+
+import android.util.Log;
+
+/**
+ * PhalApi客户端SDK包(JAVA版)
+ *
+ * - 以接口查询语言(ASQL)的方式来实现接口请求
+ * - 出于简明客户端,将全部的类都归于同一个文件,避免过多的加载
+ * 
+ * <br>使用示例:<br>
+ ```
+ * PhalApiClientResponse response = PhalApiClient.create()
+ *   .withHost("http://demo.phalapi.net/")
+ *   .withService("Default.Index")
+ *   .withParams("name", "dogstar")
+ *   .withTimeout(3000)
+ *   .request();
+ *
+ * Log.v("response ret", response.getRet() + "");
+ * Log.v("response data", response.getData());
+ * Log.v("response msg", response.getMsg());
+```
+    *
+    * @package     PhalApi\Response
+    * @license     http://www.phalapi.net/license GPL 协议
+    * @link        http://www.phalapi.net/
+    * @author      dogstar <chanzonghuang@gmail.com> 2015-10-16
+ */
+
+public class PhalApiClient {
+
+    protected String host;
+    protected PhalApiClientFilter filter;
+    protected PhalApiClientParser parser;
+    protected String service;
+    protected int timeoutMs;
+    protected Map<String, String> params;
+
+    /**
+     * 创建一个接口实例,注意:不是单例模式
+     * @return PhalApiClient
+     */
+    public static PhalApiClient create() {
+        return new PhalApiClient();
+    }
+
+    protected PhalApiClient() {
+    	this.host = "";
+    	this.reset();
+
+        this.parser = new PhalApiClientParserJson();
+    }
+
+    /**
+     * 设置接口域名
+     * @param String host
+     * @return PhalApiClient
+     */
+    public PhalApiClient withHost(String host) {
+        this.host = host;
+        return this;
+    }
+
+    /**
+     * 设置过滤器,与服务器的DI().filter对应
+     * @param PhalApiClientFilter filter 过滤器
+     * @return PhalApiClient
+     */
+    public PhalApiClient withFilter(PhalApiClientFilter filter) {
+        this.filter = filter;
+        return this;
+    }
+
+    /**
+     * 设置结果解析器,仅当不是JSON返回格式时才需要设置
+     * @param PhalApiClientParser parser 结果解析器
+     * @return PhalApiClient
+     */
+    public PhalApiClient withParser(PhalApiClientParser parser) {
+        this.parser = parser;
+        return this;
+    }
+
+    /**
+     * 重置,将接口服务名称、接口参数、请求超时进行重置,便于重复请求
+     * @return PhalApiClient
+     */
+    public PhalApiClient reset() {
+    	this.service = "";
+    	this.timeoutMs = 3000;
+        this.params = new HashMap<String, String>();
+        
+        return this;
+    }
+    
+    /**
+     * 设置将在调用的接口服务名称,如:Default.Index
+     * @param String service 接口服务名称
+     * @return PhalApiClient
+     */
+    public PhalApiClient withService(String service) {
+        this.service = service;
+        return this;
+    }
+
+    /**
+     * 设置接口参数,此方法是唯一一个可以多次调用并累加参数的操作
+     * @param String name 参数名字
+     * @param String value 值
+     * @return PhalApiClient
+     */
+    public PhalApiClient withParams(String name, String value) {
+        this.params.put(name, value);
+        return this;
+    }
+
+    /**
+     * 设置超时时间,单位毫秒
+     * @param int timeoutMS 超时时间,单位毫秒
+     * @return PhalApiClient
+     */
+    public PhalApiClient withTimeout(int timeoutMS) {
+        this.timeoutMs = timeoutMS;
+        return this;
+    }
+
+    /**
+     * 发起接口请求
+     * @return PhalApiClientResponse
+     */
+    public PhalApiClientResponse request() {
+        String url = this.host;
+
+        if (this.service != null && this.service.length() > 0) {
+            url += "?service=" + this.service;
+        }
+        if (this.filter != null) {
+            this.filter.filter(this.service, this.params);
+        }
+
+        try {
+        	String rs = this.doRequest(url, this.params, this.timeoutMs);
+        	return this.parser.parse(rs);
+        } catch (Exception ex) {
+        	return new PhalApiClientResponse(408, "", ex.getMessage());
+        }
+    }
+    
+	protected String doRequest(String requestUrl, Map<String, String> params, int timeoutMs) throws Exception {
+		String result = null;
+		URL url = null;
+		HttpURLConnection connection = null;
+		InputStreamReader in = null;
+		
+		url = new URL(requestUrl);
+		connection = (HttpURLConnection) url.openConnection();
+		connection.setDoInput(true);
+		connection.setDoOutput(true);
+		connection.setRequestMethod("POST"); // 请求方式
+		connection.setUseCaches(false);
+		connection.setConnectTimeout(timeoutMs);
+		
+        DataOutputStream out = new DataOutputStream(connection.getOutputStream());
+        
+        //POST参数
+        String postContent = "";
+        Iterator<Entry<String, String>> iter = params.entrySet().iterator();
+        while (iter.hasNext()) {
+        	Map.Entry<String, String> entry = (Map.Entry<String, String>) iter.next(); 
+        	postContent += "&" + entry.getKey() + "=" + entry.getValue();
+        }
+        out.writeBytes(postContent);
+        out.flush();
+        out.close();
+
+		Log.d("[PhalApiClient requestUrl]", requestUrl + postContent);
+        
+		in = new InputStreamReader(connection.getInputStream());
+		BufferedReader bufferedReader = new BufferedReader(in);
+		StringBuffer strBuffer = new StringBuffer();
+		String line = null;
+		while ((line = bufferedReader.readLine()) != null) {
+			strBuffer.append(line);
+		}
+		result = strBuffer.toString();
+		
+		Log.d("[PhalApiClient apiResult]", result);
+		
+		if (connection != null) {
+			connection.disconnect();
+		}
+		
+		if (in != null) {
+			try {
+				in.close();
+			} catch (IOException e) {
+				e.printStackTrace();
+			}
+		}
+
+		return result;
+	}
+}

+ 19 - 0
sdk/JAVA/net/phalapi/sdk/PhalApiClientFilter.java

@@ -0,0 +1,19 @@
+package net.phalapi.sdk;
+
+import java.util.Map;
+
+/**
+ * 接口过滤器
+ * 
+ * - 可用于接口签名生成
+ */
+public interface PhalApiClientFilter {
+
+    /**
+     * 过滤操作
+     * @param string service 接口服务名称
+     * @param Map<String, String> params 接口参数,注意是引用。可以直接修改
+     * @return null
+     */
+	public void filter(String service, Map<String, String> params);
+}

+ 17 - 0
sdk/JAVA/net/phalapi/sdk/PhalApiClientParser.java

@@ -0,0 +1,17 @@
+package net.phalapi.sdk;
+
+/**
+ * 接口结果解析器
+ * 
+ * - 可用于不同接口返回格式的处理
+ */
+public interface PhalApiClientParser {
+
+    /**
+     * 结果解析
+     * @param String apiResult
+     * @return PhalApiClientResponse
+     */
+    public PhalApiClientResponse parse(String apiResult);
+}
+

+ 24 - 0
sdk/JAVA/net/phalapi/sdk/PhalApiClientParserJson.java

@@ -0,0 +1,24 @@
+package net.phalapi.sdk;
+
+import org.json.JSONObject;
+
+/**
+ * JSON解析
+ */
+public class PhalApiClientParserJson implements PhalApiClientParser {
+
+	public PhalApiClientResponse parse(String apiResult) {
+		if (apiResult == null) {
+			return new PhalApiClientResponse(408, "", "Request Timeout");
+		}
+		
+		try {
+			JSONObject jsonObj = new JSONObject(apiResult);
+			
+			return new PhalApiClientResponse(
+					jsonObj.getInt("ret"), jsonObj.getString("data"), jsonObj.getString("msg"));
+		} catch (Exception ex) {
+			return new PhalApiClientResponse(500, "", "Internal Server Error Or " + ex.getMessage());
+		}
+	}
+}

+ 45 - 0
sdk/JAVA/net/phalapi/sdk/PhalApiClientResponse.java

@@ -0,0 +1,45 @@
+package net.phalapi.sdk;
+
+/**
+ * 接口返回结果
+ *
+ * - 与接口返回的格式对应,即有:ret/data/msg
+ */
+public class PhalApiClientResponse {
+
+    protected int ret;
+    protected String data;
+    protected String msg;
+
+    /**
+     * 完全构造函数
+     * @param int ret
+     * @param String data
+     * @param String msg
+     */
+    public PhalApiClientResponse(int ret, String data, String msg) {
+        this.ret = ret;
+        this.data = data;
+        this.msg = msg;
+    }
+
+    public PhalApiClientResponse(int ret, String data) {
+    	this(ret, data, "");
+    }
+    
+    public PhalApiClientResponse(int ret) {
+    	this(ret, "", "");
+    }
+    
+    public int getRet() {
+        return this.ret;
+    }
+
+    public String getData() {
+        return this.data;
+    }
+
+    public String getMsg() {
+        return this.msg;
+    }
+}

+ 130 - 0
sdk/JS/demo.html

@@ -0,0 +1,130 @@
+<!DOCTYPE html>
+<html xmlns="http://www.w3.org/1999/html">
+<head lang="en">
+  <meta charset="UTF-8">
+  <title>PhalApi_Demo</title>
+  <script src="js/SDK/jquery.min.js"></script>
+  <script src="js/SDK/PhalApi.js"></script>
+</head>
+<body>
+
+</br></br>
+<table>
+  <tr>
+    <td> U R L:<input type="txt" id="url"/></td>
+    <td> A P I:<input type="txt" id="api"/></td>
+  </tr>
+  <tr>
+    <td>参数名1:<input type="txt" id="param1"/></td>
+    <td>参数值1:<input type="txt" id="value1"/></td>
+  </tr>
+  <tr>
+    <td>参数名2:<input type="txt" id="param2"/></td>
+    <td>参数值2:<input type="txt" id="value2"/></td>
+  </tr>
+  <tr>
+    <td>参数名3:<input type="txt" id="param3"/></td>
+    <td>参数值3:<input type="txt" id="value3"/></td>
+  </tr>
+  <tr>
+    <td>返回结果:<textarea rows="10" cols="30" id="rs_data"></textarea></td>
+  </tr>
+
+</table>
+</br></br>
+<input onclick="post()" type="button" value="post请求" name="post"/>
+<input onclick="get()" type="button" value="get请求" name="get"/>
+<input onclick="jsonp()" type="button" value="jsonp请求" name="jsonp"/>
+</body>
+<script>
+
+  var url = $('#url').val('http://127.0.0.1/'); //请求地址
+  var api = $('#api').val('Default.Index');                    //请求接口
+
+  //使用普通的post请求
+  function post(){
+    var url = $('#url').val();
+    var api = $('#api').val();
+    var param1 = $('#param1').val();
+    var param2 = $('#param2').val();
+    var param3 = $('#param3').val();
+    var value1 = $('#value1').val();
+    var value2 = $('#value2').val();
+    var value3 = $('#value3').val();
+    var rs_data = $('#rs_data').val();
+
+    var data = {};
+    data[param1] = value1;
+    data[param2] = value2;
+    data[param3] = value3;
+    query_post(url, api, data, function(rs){
+      //回调函数
+      if(rs.ret == 200){
+        $('#rs_data').val(JSON.stringify(rs));
+        //如果成功打印信息并且做出相应的处理
+        alert(rs.ret);
+      }else{
+        $('#rs_data').val(JSON.stringify(rs));
+        //如果失败打印失败信息并且做出相应的处理
+        alert(rs.msg);
+      }
+    });
+
+  }
+
+  //使用普通的get请求
+  function get(){
+    var url = $('#url').val();
+    var api = $('#api').val();
+    var param1 = $('#param1').val();
+    var param2 = $('#param2').val();
+    var param3 = $('#param3').val();
+    var value1 = $('#value1').val();
+    var value2 = $('#value2').val();
+    var value3 = $('#value3').val();
+    //拼接GET参数
+    var data = '&' + param1 + '=' + value1 + '&' + param2 + '=' + value2 + '&' + param3 + '=' + value3;
+
+    query_get(url, api, data, function(rs){
+      //回调函数
+      if(rs.ret == 200){
+        $('#rs_data').val(JSON.stringify(rs));
+        //如果成功打印信息并且做出相应的处理
+        alert(rs.ret);
+      }else{
+        $('#rs_data').val(JSON.stringify(rs));
+        //如果失败打印失败信息并且做出相应的处理
+        alert(rs.msg);
+      }
+    });
+  }
+
+  //使用jsonP get跨域访问
+  function jsonp(){
+    var url = $('#url').val();
+    var api = $('#api').val();
+    var param1 = $('#param1').val();
+    var param2 = $('#param2').val();
+    var param3 = $('#param3').val();
+    var value1 = $('#value1').val();
+    var value2 = $('#value2').val();
+    var value3 = $('#value3').val();
+    //拼接GET参数
+    var data = '&' + param1 + '=' + value1 + '&' + param2 + '=' + value2 + '&' + param3 + '=' + value3;
+
+    query_jsonp(url, api, data, function(rs){
+      //回调函数
+      if(rs.ret == 200){
+        $('#rs_data').val(JSON.stringify(rs));
+        //如果成功打印信息并且做出相应的处理
+        alert(rs.ret);
+      }else{
+        $('#rs_data').val(JSON.stringify(rs));
+        //如果失败打印失败信息并且做出相应的处理
+        alert(rs.msg);
+      }
+    });
+  }
+
+</script>
+</html>

+ 105 - 0
sdk/JS/js/SDK/PhalApi.js

@@ -0,0 +1,105 @@
+/**
+ * PhalApi框架 JS请求SDK
+ *
+ * "猫了_个咪"提供,博客地址w-blog.cn
+ * 有好的意见或建议请联系我-><wenzhenxi@vip.qq.com> 2015-10-20
+ *
+ * 分为3种请求方式:get,post和get_jsonp
+ *
+ * 所有请求均统一传递4个参数值(请求地址,接口名称.请求参数GET传递拼接好的参数
+ * Post传递数组key-value值,回调函数)
+ *
+ * 统一使用方式如下
+ * var url = '';
+ * var api = '';
+ * var data = '';
+ * query_get(url, api, data, function(rs){
+ *     //回调函数 rs为返回结果已经反json化
+ *     if(rs.ret == 200){
+ *        成功处理
+ *     }else{
+ *        失败处理
+ *     }
+ *   });
+ *
+ */
+
+//-------------------------------配置项------------------------------------
+var debug = true; //调试模式
+//-------------------------------配置项------------------------------------
+
+/**
+ *  普通的post请求方法
+ **/
+function query_post(api_url, api_name, data, callback){
+  //拼接请求的URL地址
+  var fullapi = api_url + '?service=' + api_name;
+  //执行请求
+  $.ajax({
+    url        : fullapi,  //请求地址
+    method     : 'POST',   //请求方式
+    crossDomain: true,
+    data       : data,     //请求参数
+    complete   : function(rs){
+      //反Json化
+      rs = JSON.parse(rs.response || rs.responseText);
+      //把返回结果返回到控制台(debug模式自动开启)
+      if(debug == true){
+        console.log(fullapi, 'back', rs);
+      }
+      //回调函数
+      callback(rs);
+    }
+  });
+}
+
+/**
+ *  普通的get请求方法
+ **/
+function query_get(api_url, api_name, data, callback){
+  //拼接请求的URL地址
+  var fullapi = api_url + '?service=' + api_name + data;
+  //执行请求
+  $.ajax({
+    url     : fullapi,  //请求地址
+    method  : 'GET',   //请求方式
+    complete: function(rs){
+      //反Json化
+      rs = JSON.parse(rs.response || rs.responseText);
+      //把返回结果返回到控制台(debug模式自动开启)
+      if(debug == true){
+        console.log(fullapi, 'back', rs);
+      }
+      //回调函数
+      callback(rs);
+    }
+  });
+}
+
+/**
+ *  JsonP请求方法(用于跨域请求,只能进行get请求)
+ **/
+function query_jsonp(api_url, api_name, data, callback){
+  //拼接请求的URL地址(&callback=1是Phalapi默认使用JsonP格式)
+  var fullapi = api_url + '?service=' + api_name + '&callback=1' + data;
+  //执行请求
+  $.ajax({
+    type    : "get",
+    async   : false,
+    url     : fullapi,    //请求参数
+    dataType: "jsonp",
+    jsonp   : "callback", //传递给请求处理程序或页面的,用以获得jsonp回调函数名的参数名(一般默认为:callback)
+    success : function(rs){
+      //把返回结果返回到控制台(debug模式自动开启)
+      if(debug == true){
+        console.log(fullapi, 'back', rs);
+      }
+      //回调函数
+      callback(rs);
+    },
+    error   : function(error){
+      alert('fail');
+    }
+  });
+}
+

File diff suppressed because it is too large
+ 4 - 0
sdk/JS/js/SDK/jquery.min.js


+ 14 - 0
sdk/Objective-C/PhalApiClient/AFNPhalApiClient/AFNPhalApiClient.h

@@ -0,0 +1,14 @@
+//
+//  AFNPhalApiClient.h
+//  PhalApiClientDemo
+//
+//  Created by Aevit on 15/10/18.
+//  Copyright © 2015年 Aevit. All rights reserved.
+//
+
+#import "PhalApiClient.h"
+#import "AFHTTPRequestOperationManager.h"
+
+@interface AFNPhalApiClient : PhalApiClient
+
+@end

+ 101 - 0
sdk/Objective-C/PhalApiClient/AFNPhalApiClient/AFNPhalApiClient.m

@@ -0,0 +1,101 @@
+//
+//  AFNPhalApiClient.m
+//  PhalApiClientDemo
+//
+//  Created by Aevit on 15/10/18.
+//  Copyright © 2015年 Aevit. All rights reserved.
+//
+
+#import "AFNPhalApiClient.h"
+#import "PhalApiClientFilter.h"
+
+@implementation AFNPhalApiClient
+
+#pragma mark - generate a client
+/**
+ *  生成单例
+ *
+ *  @return 单例PhalApiClient
+ */
++ (AFNPhalApiClient*)sharedClient {
+    static AFNPhalApiClient *_sharedClient;
+    static dispatch_once_t onceToken;
+    dispatch_once(&onceToken, ^{
+        _sharedClient = [[AFNPhalApiClient alloc] init];
+    });
+    return _sharedClient;
+}
+
+/**
+ *  生成非单例
+ *
+ *  @return 非单例PhalApiClient
+ */
++ (AFNPhalApiClient*)create {
+    AFNPhalApiClient *client = [[AFNPhalApiClient alloc] init];
+    return client;
+}
+
+#pragma mark - request
+/**
+ *  发起接口请求(POST请求)
+ *
+ *  @param completeBlock 请求成功的回调
+ *  @param failureBlock  请求失败的回调
+ *
+ *  @return 请求实例
+ */
+- (id)request:(HttpCompleteBlock)completeBlock failureBlock:(HttpFailureBlock)failureBlock {
+    return [self requestWithFormDataBlock:nil completeBlock:completeBlock failureBlock:failureBlock];
+}
+
+/**
+ *  发起接口请求(提交表单)
+ *
+ *  @param formDataBlock 表单内容
+ *  @param completeBlock 请求成功的回调
+ *  @param failureBlock  请求失败的回调
+ *
+ *  @return 请求实例
+ */
+- (id)requestWithFormDataBlock:(FormDataBlock)formDataBlock completeBlock:(HttpCompleteBlock)completeBlock failureBlock:(HttpFailureBlock)failureBlock {
+    
+    if (self.filter) {
+        // 过滤器,可生成签名验证等
+        [self.filter filter:self.service params:self.params];
+    }
+    
+    NSString *url = self.host;
+    if (self.service && self.service.length > 0) {
+        // 一般来说,建议service以GET方式写在url里,其他所有参数,统一用POST方式
+        url = [NSString stringWithFormat:@"%@?service=%@", self.host, self.service];
+    }
+    
+    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
+    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/html", @"text/plain", @"text/json", @"text/xml", nil];
+    manager.requestSerializer.timeoutInterval = self.timeout;
+    
+    AFHTTPRequestOperation *operation = [manager POST:url parameters:self.params constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
+        if (formDataBlock) {
+            formDataBlock(formData);
+        }
+    } success:^(AFHTTPRequestOperation * _Nonnull operation, id  _Nonnull responseObject) {
+        // 默认以JSON返回,如需其他格式(如XML,请上google搜索"AFNetworking XML"相关资料即可)
+        if (completeBlock) {
+            completeBlock(responseObject);
+        }
+    } failure:^(AFHTTPRequestOperation * _Nonnull operation, NSError * _Nonnull error) {
+        if (error.code == NSURLErrorTimedOut) {
+            NSDictionary *timeoutDict = @{@"ret": @408, @"data": @{}, @"msg": @"Request Timeout"};
+            failureBlock(timeoutDict);
+            return ;
+        }
+        if (failureBlock) {
+            failureBlock(error);
+        }
+    }];
+    
+    return operation;
+}
+
+@end

File diff suppressed because it is too large
+ 70 - 0
sdk/Objective-C/PhalApiClient/AFNPhalApiClient/Vendor/AFNetworking-2.6.1/AFHTTPRequestOperation.h


+ 206 - 0
sdk/Objective-C/PhalApiClient/AFNPhalApiClient/Vendor/AFNetworking-2.6.1/AFHTTPRequestOperation.m

@@ -0,0 +1,206 @@
+// AFHTTPRequestOperation.m
+// Copyright (c) 2011–2015 Alamofire Software Foundation (http://alamofire.org/)
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+#import "AFHTTPRequestOperation.h"
+
+static dispatch_queue_t http_request_operation_processing_queue() {
+    static dispatch_queue_t af_http_request_operation_processing_queue;
+    static dispatch_once_t onceToken;
+    dispatch_once(&onceToken, ^{
+        af_http_request_operation_processing_queue = dispatch_queue_create("com.alamofire.networking.http-request.processing", DISPATCH_QUEUE_CONCURRENT);
+    });
+
+    return af_http_request_operation_processing_queue;
+}
+
+static dispatch_group_t http_request_operation_completion_group() {
+    static dispatch_group_t af_http_request_operation_completion_group;
+    static dispatch_once_t onceToken;
+    dispatch_once(&onceToken, ^{
+        af_http_request_operation_completion_group = dispatch_group_create();
+    });
+
+    return af_http_request_operation_completion_group;
+}
+
+#pragma mark -
+
+@interface AFURLConnectionOperation ()
+@property (readwrite, nonatomic, strong) NSURLRequest *request;
+@property (readwrite, nonatomic, strong) NSURLResponse *response;
+@end
+
+@interface AFHTTPRequestOperation ()
+@property (readwrite, nonatomic, strong) NSHTTPURLResponse *response;
+@property (readwrite, nonatomic, strong) id responseObject;
+@property (readwrite, nonatomic, strong) NSError *responseSerializationError;
+@property (readwrite, nonatomic, strong) NSRecursiveLock *lock;
+@end
+
+@implementation AFHTTPRequestOperation
+@dynamic response;
+@dynamic lock;
+
+- (instancetype)initWithRequest:(NSURLRequest *)urlRequest {
+    self = [super initWithRequest:urlRequest];
+    if (!self) {
+        return nil;
+    }
+
+    self.responseSerializer = [AFHTTPResponseSerializer serializer];
+
+    return self;
+}
+
+- (void)setResponseSerializer:(AFHTTPResponseSerializer <AFURLResponseSerialization> *)responseSerializer {
+    NSParameterAssert(responseSerializer);
+
+    [self.lock lock];
+    _responseSerializer = responseSerializer;
+    self.responseObject = nil;
+    self.responseSerializationError = nil;
+    [self.lock unlock];
+}
+
+- (id)responseObject {
+    [self.lock lock];
+    if (!_responseObject && [self isFinished] && !self.error) {
+        NSError *error = nil;
+        self.responseObject = [self.responseSerializer responseObjectForResponse:self.response data:self.responseData error:&error];
+        if (error) {
+            self.responseSerializationError = error;
+        }
+    }
+    [self.lock unlock];
+
+    return _responseObject;
+}
+
+- (NSError *)error {
+    if (_responseSerializationError) {
+        return _responseSerializationError;
+    } else {
+        return [super error];
+    }
+}
+
+#pragma mark - AFHTTPRequestOperation
+
+- (void)setCompletionBlockWithSuccess:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
+                              failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure
+{
+    // completionBlock is manually nilled out in AFURLConnectionOperation to break the retain cycle.
+#pragma clang diagnostic push
+#pragma clang diagnostic ignored "-Warc-retain-cycles"
+#pragma clang diagnostic ignored "-Wgnu"
+    self.completionBlock = ^{
+        if (self.completionGroup) {
+            dispatch_group_enter(self.completionGroup);
+        }
+
+        dispatch_async(http_request_operation_processing_queue(), ^{
+            if (self.error) {
+                if (failure) {
+                    dispatch_group_async(self.completionGroup ?: http_request_operation_completion_group(), self.completionQueue ?: dispatch_get_main_queue(), ^{
+                        failure(self, self.error);
+                    });
+                }
+            } else {
+                id responseObject = self.responseObject;
+                if (self.error) {
+                    if (failure) {
+                        dispatch_group_async(self.completionGroup ?: http_request_operation_completion_group(), self.completionQueue ?: dispatch_get_main_queue(), ^{
+                            failure(self, self.error);
+                        });
+                    }
+                } else {
+                    if (success) {
+                        dispatch_group_async(self.completionGroup ?: http_request_operation_completion_group(), self.completionQueue ?: dispatch_get_main_queue(), ^{
+                            success(self, responseObject);
+                        });
+                    }
+                }
+            }
+
+            if (self.completionGroup) {
+                dispatch_group_leave(self.completionGroup);
+            }
+        });
+    };
+#pragma clang diagnostic pop
+}
+
+#pragma mark - AFURLRequestOperation
+
+- (void)pause {
+    [super pause];
+
+    u_int64_t offset = 0;
+    if ([self.outputStream propertyForKey:NSStreamFileCurrentOffsetKey]) {
+        offset = [(NSNumber *)[self.outputStream propertyForKey:NSStreamFileCurrentOffsetKey] unsignedLongLongValue];
+    } else {
+        offset = [(NSData *)[self.outputStream propertyForKey:NSStreamDataWrittenToMemoryStreamKey] length];
+    }
+
+    NSMutableURLRequest *mutableURLRequest = [self.request mutableCopy];
+    if ([self.response respondsToSelector:@selector(allHeaderFields)] && [[self.response allHeaderFields] valueForKey:@"ETag"]) {
+        [mutableURLRequest setValue:[[self.response allHeaderFields] valueForKey:@"ETag"] forHTTPHeaderField:@"If-Range"];
+    }
+    [mutableURLRequest setValue:[NSString stringWithFormat:@"bytes=%llu-", offset] forHTTPHeaderField:@"Range"];
+    self.request = mutableURLRequest;
+}
+
+#pragma mark - NSSecureCoding
+
++ (BOOL)supportsSecureCoding {
+    return YES;
+}
+
+- (id)initWithCoder:(NSCoder *)decoder {
+    self = [super initWithCoder:decoder];
+    if (!self) {
+        return nil;
+    }
+
+    self.responseSerializer = [decoder decodeObjectOfClass:[AFHTTPResponseSerializer class] forKey:NSStringFromSelector(@selector(responseSerializer))];
+
+    return self;
+}
+
+- (void)encodeWithCoder:(NSCoder *)coder {
+    [super encodeWithCoder:coder];
+
+    [coder encodeObject:self.responseSerializer forKey:NSStringFromSelector(@selector(responseSerializer))];
+}
+
+#pragma mark - NSCopying
+
+- (id)copyWithZone:(NSZone *)zone {
+    AFHTTPRequestOperation *operation = [super copyWithZone:zone];
+
+    operation.responseSerializer = [self.responseSerializer copyWithZone:zone];
+    operation.completionQueue = self.completionQueue;
+    operation.completionGroup = self.completionGroup;
+
+    return operation;
+}
+
+@end

File diff suppressed because it is too large
+ 326 - 0
sdk/Objective-C/PhalApiClient/AFNPhalApiClient/Vendor/AFNetworking-2.6.1/AFHTTPRequestOperationManager.h


+ 284 - 0
sdk/Objective-C/PhalApiClient/AFNPhalApiClient/Vendor/AFNetworking-2.6.1/AFHTTPRequestOperationManager.m

@@ -0,0 +1,284 @@
+// AFHTTPRequestOperationManager.m
+// Copyright (c) 2011–2015 Alamofire Software Foundation (http://alamofire.org/)
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+#import <Foundation/Foundation.h>
+
+#import "AFHTTPRequestOperationManager.h"
+#import "AFHTTPRequestOperation.h"
+
+#import <Availability.h>
+#import <Security/Security.h>
+
+#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED)
+#import <UIKit/UIKit.h>
+#endif
+
+@interface AFHTTPRequestOperationManager ()
+@property (readwrite, nonatomic, strong) NSURL *baseURL;
+@end
+
+@implementation AFHTTPRequestOperationManager
+
++ (instancetype)manager {
+    return [[self alloc] initWithBaseURL:nil];
+}
+
+- (instancetype)init {
+    return [self initWithBaseURL:nil];
+}
+
+- (instancetype)initWithBaseURL:(NSURL *)url {
+    self = [super init];
+    if (!self) {
+        return nil;
+    }
+
+    // Ensure terminal slash for baseURL path, so that NSURL +URLWithString:relativeToURL: works as expected
+    if ([[url path] length] > 0 && ![[url absoluteString] hasSuffix:@"/"]) {
+        url = [url URLByAppendingPathComponent:@""];
+    }
+
+    self.baseURL = url;
+
+    self.requestSerializer = [AFHTTPRequestSerializer serializer];
+    self.responseSerializer = [AFJSONResponseSerializer serializer];
+
+    self.securityPolicy = [AFSecurityPolicy defaultPolicy];
+
+    self.reachabilityManager = [AFNetworkReachabilityManager sharedManager];
+
+    self.operationQueue = [[NSOperationQueue alloc] init];
+
+    self.shouldUseCredentialStorage = YES;
+
+    return self;
+}
+
+#pragma mark -
+
+#ifdef _SYSTEMCONFIGURATION_H
+#endif
+
+- (void)setRequestSerializer:(AFHTTPRequestSerializer <AFURLRequestSerialization> *)requestSerializer {
+    NSParameterAssert(requestSerializer);
+
+    _requestSerializer = requestSerializer;
+}
+
+- (void)setResponseSerializer:(AFHTTPResponseSerializer <AFURLResponseSerialization> *)responseSerializer {
+    NSParameterAssert(responseSerializer);
+
+    _responseSerializer = responseSerializer;
+}
+
+#pragma mark -
+
+- (AFHTTPRequestOperation *)HTTPRequestOperationWithHTTPMethod:(NSString *)method
+                                                     URLString:(NSString *)URLString
+                                                    parameters:(id)parameters
+                                                       success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
+                                                       failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure
+{
+    NSError *serializationError = nil;
+    NSMutableURLRequest *request = [self.requestSerializer requestWithMethod:method URLString:[[NSURL URLWithString:URLString relativeToURL:self.baseURL] absoluteString] parameters:parameters error:&serializationError];
+    if (serializationError) {
+        if (failure) {
+#pragma clang diagnostic push
+#pragma clang diagnostic ignored "-Wgnu"
+            dispatch_async(self.completionQueue ?: dispatch_get_main_queue(), ^{
+                failure(nil, serializationError);
+            });
+#pragma clang diagnostic pop
+        }
+
+        return nil;
+    }
+
+    return [self HTTPRequestOperationWithRequest:request success:success failure:failure];
+}
+
+- (AFHTTPRequestOperation *)HTTPRequestOperationWithRequest:(NSURLRequest *)request
+                                                    success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
+                                                    failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure
+{
+    AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
+    operation.responseSerializer = self.responseSerializer;
+    operation.shouldUseCredentialStorage = self.shouldUseCredentialStorage;
+    operation.credential = self.credential;
+    operation.securityPolicy = self.securityPolicy;
+
+    [operation setCompletionBlockWithSuccess:success failure:failure];
+    operation.completionQueue = self.completionQueue;
+    operation.completionGroup = self.completionGroup;
+
+    return operation;
+}
+
+#pragma mark -
+
+- (AFHTTPRequestOperation *)GET:(NSString *)URLString
+                     parameters:(id)parameters
+                        success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
+                        failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure
+{
+    AFHTTPRequestOperation *operation = [self HTTPRequestOperationWithHTTPMethod:@"GET" URLString:URLString parameters:parameters success:success failure:failure];
+
+    [self.operationQueue addOperation:operation];
+
+    return operation;
+}
+
+- (AFHTTPRequestOperation *)HEAD:(NSString *)URLString
+                      parameters:(id)parameters
+                         success:(void (^)(AFHTTPRequestOperation *operation))success
+                         failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure
+{
+    AFHTTPRequestOperation *operation = [self HTTPRequestOperationWithHTTPMethod:@"HEAD" URLString:URLString parameters:parameters success:^(AFHTTPRequestOperation *requestOperation, __unused id responseObject) {
+        if (success) {
+            success(requestOperation);
+        }
+    } failure:failure];
+
+    [self.operationQueue addOperation:operation];
+
+    return operation;
+}
+
+- (AFHTTPRequestOperation *)POST:(NSString *)URLString
+                      parameters:(id)parameters
+                         success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
+                         failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure
+{
+    AFHTTPRequestOperation *operation = [self HTTPRequestOperationWithHTTPMethod:@"POST" URLString:URLString parameters:parameters success:success failure:failure];
+
+    [self.operationQueue addOperation:operation];
+
+    return operation;
+}
+
+- (AFHTTPRequestOperation *)POST:(NSString *)URLString
+                      parameters:(id)parameters
+       constructingBodyWithBlock:(void (^)(id <AFMultipartFormData> formData))block
+                         success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
+                         failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure
+{
+    NSError *serializationError = nil;
+    NSMutableURLRequest *request = [self.requestSerializer multipartFormRequestWithMethod:@"POST" URLString:[[NSURL URLWithString:URLString relativeToURL:self.baseURL] absoluteString] parameters:parameters constructingBodyWithBlock:block error:&serializationError];
+    if (serializationError) {
+        if (failure) {
+#pragma clang diagnostic push
+#pragma clang diagnostic ignored "-Wgnu"
+            dispatch_async(self.completionQueue ?: dispatch_get_main_queue(), ^{
+                failure(nil, serializationError);
+            });
+#pragma clang diagnostic pop
+        }
+
+        return nil;
+    }
+
+    AFHTTPRequestOperation *operation = [self HTTPRequestOperationWithRequest:request success:success failure:failure];
+
+    [self.operationQueue addOperation:operation];
+
+    return operation;
+}
+
+- (AFHTTPRequestOperation *)PUT:(NSString *)URLString
+                     parameters:(id)parameters
+                        success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
+                        failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure
+{
+    AFHTTPRequestOperation *operation = [self HTTPRequestOperationWithHTTPMethod:@"PUT" URLString:URLString parameters:parameters success:success failure:failure];
+
+    [self.operationQueue addOperation:operation];
+
+    return operation;
+}
+
+- (AFHTTPRequestOperation *)PATCH:(NSString *)URLString
+                       parameters:(id)parameters
+                          success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
+                          failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure
+{
+    AFHTTPRequestOperation *operation = [self HTTPRequestOperationWithHTTPMethod:@"PATCH" URLString:URLString parameters:parameters success:success failure:failure];
+
+    [self.operationQueue addOperation:operation];
+
+    return operation;
+}
+
+- (AFHTTPRequestOperation *)DELETE:(NSString *)URLString
+                        parameters:(id)parameters
+                           success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
+                           failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure
+{
+    AFHTTPRequestOperation *operation = [self HTTPRequestOperationWithHTTPMethod:@"DELETE" URLString:URLString parameters:parameters success:success failure:failure];
+
+    [self.operationQueue addOperation:operation];
+
+    return operation;
+}
+
+#pragma mark - NSObject
+
+- (NSString *)description {
+    return [NSString stringWithFormat:@"<%@: %p, baseURL: %@, operationQueue: %@>", NSStringFromClass([self class]), self, [self.baseURL absoluteString], self.operationQueue];
+}
+
+#pragma mark - NSSecureCoding
+
++ (BOOL)supportsSecureCoding {
+    return YES;
+}
+
+- (id)initWithCoder:(NSCoder *)decoder {
+    NSURL *baseURL = [decoder decodeObjectForKey:NSStringFromSelector(@selector(baseURL))];
+
+    self = [self initWithBaseURL:baseURL];
+    if (!self) {
+        return nil;
+    }
+
+    self.requestSerializer = [decoder decodeObjectOfClass:[AFHTTPRequestSerializer class] forKey:NSStringFromSelector(@selector(requestSerializer))];
+    self.responseSerializer = [decoder decodeObjectOfClass:[AFHTTPResponseSerializer class] forKey:NSStringFromSelector(@selector(responseSerializer))];
+
+    return self;
+}
+
+- (void)encodeWithCoder:(NSCoder *)coder {
+    [coder encodeObject:self.baseURL forKey:NSStringFromSelector(@selector(baseURL))];
+    [coder encodeObject:self.requestSerializer forKey:NSStringFromSelector(@selector(requestSerializer))];
+    [coder encodeObject:self.responseSerializer forKey:NSStringFromSelector(@selector(responseSerializer))];
+}
+
+#pragma mark - NSCopying
+
+- (id)copyWithZone:(NSZone *)zone {
+    AFHTTPRequestOperationManager *HTTPClient = [[[self class] allocWithZone:zone] initWithBaseURL:self.baseURL];
+
+    HTTPClient.requestSerializer = [self.requestSerializer copyWithZone:zone];
+    HTTPClient.responseSerializer = [self.responseSerializer copyWithZone:zone];
+
+    return HTTPClient;
+}
+
+@end

+ 253 - 0
sdk/Objective-C/PhalApiClient/AFNPhalApiClient/Vendor/AFNetworking-2.6.1/AFHTTPSessionManager.h

@@ -0,0 +1,253 @@
+// AFHTTPSessionManager.h
+// Copyright (c) 2011–2015 Alamofire Software Foundation (http://alamofire.org/)
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+#import <Foundation/Foundation.h>
+#if !TARGET_OS_WATCH
+#import <SystemConfiguration/SystemConfiguration.h>
+#endif
+#import <Availability.h>
+
+#if __IPHONE_OS_VERSION_MIN_REQUIRED
+#import <MobileCoreServices/MobileCoreServices.h>
+#else
+#import <CoreServices/CoreServices.h>
+#endif
+
+#import "AFURLSessionManager.h"
+
+#ifndef NS_DESIGNATED_INITIALIZER
+#if __has_attribute(objc_designated_initializer)
+#define NS_DESIGNATED_INITIALIZER __attribute__((objc_designated_initializer))
+#else
+#define NS_DESIGNATED_INITIALIZER
+#endif
+#endif
+
+/**
+ `AFHTTPSessionManager` is a subclass of `AFURLSessionManager` with convenience methods for making HTTP requests. When a `baseURL` is provided, requests made with the `GET` / `POST` / et al. convenience methods can be made with relative paths.
+
+ ## Subclassing Notes
+
+ Developers targeting iOS 7 or Mac OS X 10.9 or later that deal extensively with a web service are encouraged to subclass `AFHTTPSessionManager`, providing a class method that returns a shared singleton object on which authentication and other configuration can be shared across the application.
+
+ For developers targeting iOS 6 or Mac OS X 10.8 or earlier, `AFHTTPRequestOperationManager` may be used to similar effect.
+
+ ## Methods to Override
+
+ To change the behavior of all data task operation construction, which is also used in the `GET` / `POST` / et al. convenience methods, override `dataTaskWithRequest:completionHandler:`.
+
+ ## Serialization
+
+ Requests created by an HTTP client will contain default headers and encode parameters according to the `requestSerializer` property, which is an object conforming to `<AFURLRequestSerialization>`.
+
+ Responses received from the server are automatically validated and serialized by the `responseSerializers` property, which is an object conforming to `<AFURLResponseSerialization>`
+
+ ## URL Construction Using Relative Paths
+
+ For HTTP convenience methods, the request serializer constructs URLs from the path relative to the `-baseURL`, using `NSURL +URLWithString:relativeToURL:`, when provided. If `baseURL` is `nil`, `path` needs to resolve to a valid `NSURL` object using `NSURL +URLWithString:`.
+
+ Below are a few examples of how `baseURL` and relative paths interact:
+
+    NSURL *baseURL = [NSURL URLWithString:@"http://example.com/v1/"];
+    [NSURL URLWithString:@"foo" relativeToURL:baseURL];                  // http://example.com/v1/foo
+    [NSURL URLWithString:@"foo?bar=baz" relativeToURL:baseURL];          // http://example.com/v1/foo?bar=baz
+    [NSURL URLWithString:@"/foo" relativeToURL:baseURL];                 // http://example.com/foo
+    [NSURL URLWithString:@"foo/" relativeToURL:baseURL];                 // http://example.com/v1/foo
+    [NSURL URLWithString:@"/foo/" relativeToURL:baseURL];                // http://example.com/foo/
+    [NSURL URLWithString:@"http://example2.com/" relativeToURL:baseURL]; // http://example2.com/
+
+ Also important to note is that a trailing slash will be added to any `baseURL` without one. This would otherwise cause unexpected behavior when constructing URLs using paths without a leading slash.
+
+ @warning Managers for background sessions must be owned for the duration of their use. This can be accomplished by creating an application-wide or shared singleton instance.
+ */
+
+#if (defined(__IPHONE_OS_VERSION_MAX_ALLOWED) && __IPHONE_OS_VERSION_MAX_ALLOWED >= 70000) || (defined(__MAC_OS_X_VERSION_MAX_ALLOWED) && __MAC_OS_X_VERSION_MAX_ALLOWED >= 1090) || TARGET_OS_WATCH
+
+NS_ASSUME_NONNULL_BEGIN
+
+@interface AFHTTPSessionManager : AFURLSessionManager <NSSecureCoding, NSCopying>
+
+/**
+ The URL used to construct requests from relative paths in methods like `requestWithMethod:URLString:parameters:`, and the `GET` / `POST` / et al. convenience methods.
+ */
+@property (readonly, nonatomic, strong, nullable) NSURL *baseURL;
+
+/**
+ Requests created with `requestWithMethod:URLString:parameters:` & `multipartFormRequestWithMethod:URLString:parameters:constructingBodyWithBlock:` are constructed with a set of default headers using a parameter serialization specified by this property. By default, this is set to an instance of `AFHTTPRequestSerializer`, which serializes query string parameters for `GET`, `HEAD`, and `DELETE` requests, or otherwise URL-form-encodes HTTP message bodies.
+
+ @warning `requestSerializer` must not be `nil`.
+ */
+@property (nonatomic, strong) AFHTTPRequestSerializer <AFURLRequestSerialization> * requestSerializer;
+
+/**
+ Responses sent from the server in data tasks created with `dataTaskWithRequest:success:failure:` and run using the `GET` / `POST` / et al. convenience methods are automatically validated and serialized by the response serializer. By default, this property is set to an instance of `AFJSONResponseSerializer`.
+
+ @warning `responseSerializer` must not be `nil`.
+ */
+@property (nonatomic, strong) AFHTTPResponseSerializer <AFURLResponseSerialization> * responseSerializer;
+
+///---------------------
+/// @name Initialization
+///---------------------
+
+/**
+ Creates and returns an `AFHTTPSessionManager` object.
+ */
++ (instancetype)manager;
+
+/**
+ Initializes an `AFHTTPSessionManager` object with the specified base URL.
+
+ @param url The base URL for the HTTP client.
+
+ @return The newly-initialized HTTP client
+ */
+- (instancetype)initWithBaseURL:(nullable NSURL *)url;
+
+/**
+ Initializes an `AFHTTPSessionManager` object with the specified base URL.
+
+ This is the designated initializer.
+
+ @param url The base URL for the HTTP client.
+ @param configuration The configuration used to create the managed session.
+
+ @return The newly-initialized HTTP client
+ */
+- (instancetype)initWithBaseURL:(nullable NSURL *)url
+           sessionConfiguration:(nullable NSURLSessionConfiguration *)configuration NS_DESIGNATED_INITIALIZER;
+
+///---------------------------
+/// @name Making HTTP Requests
+///---------------------------
+
+/**
+ Creates and runs an `NSURLSessionDataTask` with a `GET` request.
+
+ @param URLString The URL string used to create the request URL.
+ @param parameters The parameters to be encoded according to the client request serializer.
+ @param success A block object to be executed when the task finishes successfully. This block has no return value and takes two arguments: the data task, and the response object created by the client response serializer.
+ @param failure A block object to be executed when the task finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes a two arguments: the data task and the error describing the network or parsing error that occurred.
+
+ @see -dataTaskWithRequest:completionHandler:
+ */
+- (nullable NSURLSessionDataTask *)GET:(NSString *)URLString
+                   parameters:(nullable id)parameters
+                      success:(nullable void (^)(NSURLSessionDataTask *task, id responseObject))success
+                      failure:(nullable void (^)(NSURLSessionDataTask *task, NSError *error))failure;
+
+/**
+ Creates and runs an `NSURLSessionDataTask` with a `HEAD` request.
+
+ @param URLString The URL string used to create the request URL.
+ @param parameters The parameters to be encoded according to the client request serializer.
+ @param success A block object to be executed when the task finishes successfully. This block has no return value and takes a single arguments: the data task.
+ @param failure A block object to be executed when the task finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes a two arguments: the data task and the error describing the network or parsing error that occurred.
+
+ @see -dataTaskWithRequest:completionHandler:
+ */
+- (nullable NSURLSessionDataTask *)HEAD:(NSString *)URLString
+                    parameters:(nullable id)parameters
+                       success:(nullable void (^)(NSURLSessionDataTask *task))success
+                       failure:(nullable void (^)(NSURLSessionDataTask *task, NSError *error))failure;
+
+/**
+ Creates and runs an `NSURLSessionDataTask` with a `POST` request.
+
+ @param URLString The URL string used to create the request URL.
+ @param parameters The parameters to be encoded according to the client request serializer.
+ @param success A block object to be executed when the task finishes successfully. This block has no return value and takes two arguments: the data task, and the response object created by the client response serializer.
+ @param failure A block object to be executed when the task finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes a two arguments: the data task and the error describing the network or parsing error that occurred.
+
+ @see -dataTaskWithRequest:completionHandler:
+ */
+- (nullable NSURLSessionDataTask *)POST:(NSString *)URLString
+                    parameters:(nullable id)parameters
+                       success:(nullable void (^)(NSURLSessionDataTask *task, id responseObject))success
+                       failure:(nullable void (^)(NSURLSessionDataTask *task, NSError *error))failure;
+
+/**
+ Creates and runs an `NSURLSessionDataTask` with a multipart `POST` request.
+
+ @param URLString The URL string used to create the request URL.
+ @param parameters The parameters to be encoded according to the client request serializer.
+ @param block A block that takes a single argument and appends data to the HTTP body. The block argument is an object adopting the `AFMultipartFormData` protocol.
+ @param success A block object to be executed when the task finishes successfully. This block has no return value and takes two arguments: the data task, and the response object created by the client response serializer.
+ @param failure A block object to be executed when the task finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes a two arguments: the data task and the error describing the network or parsing error that occurred.
+
+ @see -dataTaskWithRequest:completionHandler:
+ */
+- (nullable NSURLSessionDataTask *)POST:(NSString *)URLString
+                    parameters:(nullable id)parameters
+     constructingBodyWithBlock:(nullable void (^)(id <AFMultipartFormData> formData))block
+                       success:(nullable void (^)(NSURLSessionDataTask *task, id responseObject))success
+                       failure:(nullable void (^)(NSURLSessionDataTask *task, NSError *error))failure;
+
+/**
+ Creates and runs an `NSURLSessionDataTask` with a `PUT` request.
+
+ @param URLString The URL string used to create the request URL.
+ @param parameters The parameters to be encoded according to the client request serializer.
+ @param success A block object to be executed when the task finishes successfully. This block has no return value and takes two arguments: the data task, and the response object created by the client response serializer.
+ @param failure A block object to be executed when the task finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes a two arguments: the data task and the error describing the network or parsing error that occurred.
+
+ @see -dataTaskWithRequest:completionHandler:
+ */
+- (nullable NSURLSessionDataTask *)PUT:(NSString *)URLString
+                   parameters:(nullable id)parameters
+                      success:(nullable void (^)(NSURLSessionDataTask *task, id responseObject))success
+                      failure:(nullable void (^)(NSURLSessionDataTask *task, NSError *error))failure;
+
+/**
+ Creates and runs an `NSURLSessionDataTask` with a `PATCH` request.
+
+ @param URLString The URL string used to create the request URL.
+ @param parameters The parameters to be encoded according to the client request serializer.
+ @param success A block object to be executed when the task finishes successfully. This block has no return value and takes two arguments: the data task, and the response object created by the client response serializer.
+ @param failure A block object to be executed when the task finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes a two arguments: the data task and the error describing the network or parsing error that occurred.
+
+ @see -dataTaskWithRequest:completionHandler:
+ */
+- (nullable NSURLSessionDataTask *)PATCH:(NSString *)URLString
+                     parameters:(nullable id)parameters
+                        success:(nullable void (^)(NSURLSessionDataTask *task, id responseObject))success
+                        failure:(nullable void (^)(NSURLSessionDataTask *task, NSError *error))failure;
+
+/**
+ Creates and runs an `NSURLSessionDataTask` with a `DELETE` request.
+
+ @param URLString The URL string used to create the request URL.
+ @param parameters The parameters to be encoded according to the client request serializer.
+ @param success A block object to be executed when the task finishes successfully. This block has no return value and takes two arguments: the data task, and the response object created by the client response serializer.
+ @param failure A block object to be executed when the task finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes a two arguments: the data task and the error describing the network or parsing error that occurred.
+
+ @see -dataTaskWithRequest:completionHandler:
+ */
+- (nullable NSURLSessionDataTask *)DELETE:(NSString *)URLString
+                      parameters:(nullable id)parameters
+                         success:(nullable void (^)(NSURLSessionDataTask *task, id responseObject))success
+                         failure:(nullable void (^)(NSURLSessionDataTask *task, NSError *error))failure;
+
+@end
+
+NS_ASSUME_NONNULL_END
+
+#endif

+ 323 - 0
sdk/Objective-C/PhalApiClient/AFNPhalApiClient/Vendor/AFNetworking-2.6.1/AFHTTPSessionManager.m

@@ -0,0 +1,323 @@
+// AFHTTPSessionManager.m
+// Copyright (c) 2011–2015 Alamofire Software Foundation (http://alamofire.org/)
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+#import "AFHTTPSessionManager.h"
+
+#if (defined(__IPHONE_OS_VERSION_MAX_ALLOWED) && __IPHONE_OS_VERSION_MAX_ALLOWED >= 70000) || (defined(__MAC_OS_X_VERSION_MAX_ALLOWED) && __MAC_OS_X_VERSION_MAX_ALLOWED >= 1090) || TARGET_WATCH_OS
+
+#import "AFURLRequestSerialization.h"
+#import "AFURLResponseSerialization.h"
+
+#import <Availability.h>
+#import <Security/Security.h>
+
+#ifdef _SYSTEMCONFIGURATION_H
+#import <netinet/in.h>
+#import <netinet6/in6.h>
+#import <arpa/inet.h>
+#import <ifaddrs.h>
+#import <netdb.h>
+#endif
+
+#if TARGET_OS_IOS
+#import <UIKit/UIKit.h>
+#elif TARGET_OS_WATCH
+#import <WatchKit/WatchKit.h>
+#endif
+
+@interface AFHTTPSessionManager ()
+@property (readwrite, nonatomic, strong) NSURL *baseURL;
+@end
+
+@implementation AFHTTPSessionManager
+@dynamic responseSerializer;
+
++ (instancetype)manager {
+    return [[[self class] alloc] initWithBaseURL:nil];
+}
+
+- (instancetype)init {
+    return [self initWithBaseURL:nil];
+}
+
+- (instancetype)initWithBaseURL:(NSURL *)url {
+    return [self initWithBaseURL:url sessionConfiguration:nil];
+}
+
+- (instancetype)initWithSessionConfiguration:(NSURLSessionConfiguration *)configuration {
+    return [self initWithBaseURL:nil sessionConfiguration:configuration];
+}
+
+- (instancetype)initWithBaseURL:(NSURL *)url
+           sessionConfiguration:(NSURLSessionConfiguration *)configuration
+{
+    self = [super initWithSessionConfiguration:configuration];
+    if (!self) {
+        return nil;
+    }
+
+    // Ensure terminal slash for baseURL path, so that NSURL +URLWithString:relativeToURL: works as expected
+    if ([[url path] length] > 0 && ![[url absoluteString] hasSuffix:@"/"]) {
+        url = [url URLByAppendingPathComponent:@""];
+    }
+
+    self.baseURL = url;
+
+    self.requestSerializer = [AFHTTPRequestSerializer serializer];
+    self.responseSerializer = [AFJSONResponseSerializer serializer];
+
+    return self;
+}
+
+#pragma mark -
+
+#ifdef _SYSTEMCONFIGURATION_H
+#endif
+
+- (void)setRequestSerializer:(AFHTTPRequestSerializer <AFURLRequestSerialization> *)requestSerializer {
+    NSParameterAssert(requestSerializer);
+
+    _requestSerializer = requestSerializer;
+}
+
+- (void)setResponseSerializer:(AFHTTPResponseSerializer <AFURLResponseSerialization> *)responseSerializer {
+    NSParameterAssert(responseSerializer);
+
+    [super setResponseSerializer:responseSerializer];
+}
+
+#pragma mark -
+
+- (NSURLSessionDataTask *)GET:(NSString *)URLString
+                   parameters:(id)parameters
+                      success:(void (^)(NSURLSessionDataTask *task, id responseObject))success
+                      failure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure
+{
+    NSURLSessionDataTask *dataTask = [self dataTaskWithHTTPMethod:@"GET" URLString:URLString parameters:parameters success:success failure:failure];
+
+    [dataTask resume];
+
+    return dataTask;
+}
+
+- (NSURLSessionDataTask *)HEAD:(NSString *)URLString
+                    parameters:(id)parameters
+                       success:(void (^)(NSURLSessionDataTask *task))success
+                       failure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure
+{
+    NSURLSessionDataTask *dataTask = [self dataTaskWithHTTPMethod:@"HEAD" URLString:URLString parameters:parameters success:^(NSURLSessionDataTask *task, __unused id responseObject) {
+        if (success) {
+            success(task);
+        }
+    } failure:failure];
+
+    [dataTask resume];
+
+    return dataTask;
+}
+
+- (NSURLSessionDataTask *)POST:(NSString *)URLString
+                    parameters:(id)parameters
+                       success:(void (^)(NSURLSessionDataTask *task, id responseObject))success
+                       failure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure
+{
+    NSURLSessionDataTask *dataTask = [self dataTaskWithHTTPMethod:@"POST" URLString:URLString parameters:parameters success:success failure:failure];
+
+    [dataTask resume];
+
+    return dataTask;
+}
+
+- (NSURLSessionDataTask *)POST:(NSString *)URLString
+                    parameters:(id)parameters
+     constructingBodyWithBlock:(void (^)(id <AFMultipartFormData> formData))block
+                       success:(void (^)(NSURLSessionDataTask *task, id responseObject))success
+                       failure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure
+{
+    NSError *serializationError = nil;
+    NSMutableURLRequest *request = [self.requestSerializer multipartFormRequestWithMethod:@"POST" URLString:[[NSURL URLWithString:URLString relativeToURL:self.baseURL] absoluteString] parameters:parameters constructingBodyWithBlock:block error:&serializationError];
+    if (serializationError) {
+        if (failure) {
+#pragma clang diagnostic push
+#pragma clang diagnostic ignored "-Wgnu"
+            dispatch_async(self.completionQueue ?: dispatch_get_main_queue(), ^{
+                failure(nil, serializationError);
+            });
+#pragma clang diagnostic pop
+        }
+
+        return nil;
+    }
+
+    __block NSURLSessionDataTask *task = [self uploadTaskWithStreamedRequest:request progress:nil completionHandler:^(NSURLResponse * __unused response, id responseObject, NSError *error) {
+        if (error) {
+            if (failure) {
+                failure(task, error);
+            }
+        } else {
+            if (success) {
+                success(task, responseObject);
+            }
+        }
+    }];
+
+    [task resume];
+
+    return task;
+}
+
+- (NSURLSessionDataTask *)PUT:(NSString *)URLString
+                   parameters:(id)parameters
+                      success:(void (^)(NSURLSessionDataTask *task, id responseObject))success
+                      failure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure
+{
+    NSURLSessionDataTask *dataTask = [self dataTaskWithHTTPMethod:@"PUT" URLString:URLString parameters:parameters success:success failure:failure];
+
+    [dataTask resume];
+
+    return dataTask;
+}
+
+- (NSURLSessionDataTask *)PATCH:(NSString *)URLString
+                     parameters:(id)parameters
+                        success:(void (^)(NSURLSessionDataTask *task, id responseObject))success
+                        failure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure
+{
+    NSURLSessionDataTask *dataTask = [self dataTaskWithHTTPMethod:@"PATCH" URLString:URLString parameters:parameters success:success failure:failure];
+
+    [dataTask resume];
+
+    return dataTask;
+}
+
+- (NSURLSessionDataTask *)DELETE:(NSString *)URLString
+                      parameters:(id)parameters
+                         success:(void (^)(NSURLSessionDataTask *task, id responseObject))success
+                         failure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure
+{
+    NSURLSessionDataTask *dataTask = [self dataTaskWithHTTPMethod:@"DELETE" URLString:URLString parameters:parameters success:success failure:failure];
+
+    [dataTask resume];
+
+    return dataTask;
+}
+
+- (NSURLSessionDataTask *)dataTaskWithHTTPMethod:(NSString *)method
+                                       URLString:(NSString *)URLString
+                                      parameters:(id)parameters
+                                         success:(void (^)(NSURLSessionDataTask *, id))success
+                                         failure:(void (^)(NSURLSessionDataTask *, NSError *))failure
+{
+    NSError *serializationError = nil;
+    NSMutableURLRequest *request = [self.requestSerializer requestWithMethod:method URLString:[[NSURL URLWithString:URLString relativeToURL:self.baseURL] absoluteString] parameters:parameters error:&serializationError];
+    if (serializationError) {
+        if (failure) {
+#pragma clang diagnostic push
+#pragma clang diagnostic ignored "-Wgnu"
+            dispatch_async(self.completionQueue ?: dispatch_get_main_queue(), ^{
+                failure(nil, serializationError);
+            });
+#pragma clang diagnostic pop
+        }
+
+        return nil;
+    }
+
+    __block NSURLSessionDataTask *dataTask = nil;
+    dataTask = [self dataTaskWithRequest:request completionHandler:^(NSURLResponse * __unused response, id responseObject, NSError *error) {
+        if (error) {
+            if (failure) {
+                failure(dataTask, error);
+            }
+        } else {
+            if (success) {
+                success(dataTask, responseObject);
+            }
+        }
+    }];
+
+    return dataTask;
+}
+
+#pragma mark - NSObject
+
+- (NSString *)description {
+    return [NSString stringWithFormat:@"<%@: %p, baseURL: %@, session: %@, operationQueue: %@>", NSStringFromClass([self class]), self, [self.baseURL absoluteString], self.session, self.operationQueue];
+}
+
+#pragma mark - NSSecureCoding
+
++ (BOOL)supportsSecureCoding {
+    return YES;
+}
+
+- (id)initWithCoder:(NSCoder *)decoder {
+    NSURL *baseURL = [decoder decodeObjectOfClass:[NSURL class] forKey:NSStringFromSelector(@selector(baseURL))];
+    NSURLSessionConfiguration *configuration = [decoder decodeObjectOfClass:[NSURLSessionConfiguration class] forKey:@"sessionConfiguration"];
+    if (!configuration) {
+        NSString *configurationIdentifier = [decoder decodeObjectOfClass:[NSString class] forKey:@"identifier"];
+        if (configurationIdentifier) {
+#if (defined(__IPHONE_OS_VERSION_MIN_REQUIRED) && __IPHONE_OS_VERSION_MIN_REQUIRED >= 80000) || (defined(__MAC_OS_X_VERSION_MIN_REQUIRED) && __MAC_OS_X_VERSION_MIN_REQUIRED >= 1100)
+            configuration = [NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:configurationIdentifier];
+#else
+            configuration = [NSURLSessionConfiguration backgroundSessionConfiguration:configurationIdentifier];
+#endif
+        }
+    }
+
+    self = [self initWithBaseURL:baseURL sessionConfiguration:configuration];
+    if (!self) {
+        return nil;
+    }
+
+    self.requestSerializer = [decoder decodeObjectOfClass:[AFHTTPRequestSerializer class] forKey:NSStringFromSelector(@selector(requestSerializer))];
+    self.responseSerializer = [decoder decodeObjectOfClass:[AFHTTPResponseSerializer class] forKey:NSStringFromSelector(@selector(responseSerializer))];
+
+    return self;
+}
+
+- (void)encodeWithCoder:(NSCoder *)coder {
+    [super encodeWithCoder:coder];
+
+    [coder encodeObject:self.baseURL forKey:NSStringFromSelector(@selector(baseURL))];
+    if ([self.session.configuration conformsToProtocol:@protocol(NSCoding)]) {
+        [coder encodeObject:self.session.configuration forKey:@"sessionConfiguration"];
+    } else {
+        [coder encodeObject:self.session.configuration.identifier forKey:@"identifier"];
+    }
+    [coder encodeObject:self.requestSerializer forKey:NSStringFromSelector(@selector(requestSerializer))];
+    [coder encodeObject:self.responseSerializer forKey:NSStringFromSelector(@selector(responseSerializer))];
+}
+
+#pragma mark - NSCopying
+
+- (id)copyWithZone:(NSZone *)zone {
+    AFHTTPSessionManager *HTTPClient = [[[self class] allocWithZone:zone] initWithBaseURL:self.baseURL sessionConfiguration:self.session.configuration];
+
+    HTTPClient.requestSerializer = [self.requestSerializer copyWithZone:zone];
+    HTTPClient.responseSerializer = [self.responseSerializer copyWithZone:zone];
+
+    return HTTPClient;
+}
+
+@end
+
+#endif

+ 207 - 0
sdk/Objective-C/PhalApiClient/AFNPhalApiClient/Vendor/AFNetworking-2.6.1/AFNetworkReachabilityManager.h

@@ -0,0 +1,207 @@
+// AFNetworkReachabilityManager.h
+// Copyright (c) 2011–2015 Alamofire Software Foundation (http://alamofire.org/)
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+#import <Foundation/Foundation.h>
+
+#if !TARGET_OS_WATCH
+#import <SystemConfiguration/SystemConfiguration.h>
+
+#ifndef NS_DESIGNATED_INITIALIZER
+#if __has_attribute(objc_designated_initializer)
+#define NS_DESIGNATED_INITIALIZER __attribute__((objc_designated_initializer))
+#else
+#define NS_DESIGNATED_INITIALIZER
+#endif
+#endif
+
+typedef NS_ENUM(NSInteger, AFNetworkReachabilityStatus) {
+    AFNetworkReachabilityStatusUnknown          = -1,
+    AFNetworkReachabilityStatusNotReachable     = 0,
+    AFNetworkReachabilityStatusReachableViaWWAN = 1,
+    AFNetworkReachabilityStatusReachableViaWiFi = 2,
+};
+
+NS_ASSUME_NONNULL_BEGIN
+
+/**
+ `AFNetworkReachabilityManager` monitors the reachability of domains, and addresses for both WWAN and WiFi network interfaces.
+
+ Reachability can be used to determine background information about why a network operation failed, or to trigger a network operation retrying when a connection is established. It should not be used to prevent a user from initiating a network request, as it's possible that an initial request may be required to establish reachability.
+
+ See Apple's Reachability Sample Code (https://developer.apple.com/library/ios/samplecode/reachability/)
+
+ @warning Instances of `AFNetworkReachabilityManager` must be started with `-startMonitoring` before reachability status can be determined.
+ */
+@interface AFNetworkReachabilityManager : NSObject
+
+/**
+ The current network reachability status.
+ */
+@property (readonly, nonatomic, assign) AFNetworkReachabilityStatus networkReachabilityStatus;
+
+/**
+ Whether or not the network is currently reachable.
+ */
+@property (readonly, nonatomic, assign, getter = isReachable) BOOL reachable;
+
+/**
+ Whether or not the network is currently reachable via WWAN.
+ */
+@property (readonly, nonatomic, assign, getter = isReachableViaWWAN) BOOL reachableViaWWAN;
+
+/**
+ Whether or not the network is currently reachable via WiFi.
+ */
+@property (readonly, nonatomic, assign, getter = isReachableViaWiFi) BOOL reachableViaWiFi;
+
+///---------------------
+/// @name Initialization
+///---------------------
+
+/**
+ Returns the shared network reachability manager.
+ */
++ (instancetype)sharedManager;
+
+/**
+ Creates and returns a network reachability manager for the specified domain.
+
+ @param domain The domain used to evaluate network reachability.
+
+ @return An initialized network reachability manager, actively monitoring the specified domain.
+ */
++ (instancetype)managerForDomain:(NSString *)domain;
+
+/**
+ Creates and returns a network reachability manager for the socket address.
+
+ @param address The socket address (`sockaddr_in`) used to evaluate network reachability.
+
+ @return An initialized network reachability manager, actively monitoring the specified socket address.
+ */
++ (instancetype)managerForAddress:(const void *)address;
+
+/**
+ Initializes an instance of a network reachability manager from the specified reachability object.
+
+ @param reachability The reachability object to monitor.
+
+ @return An initialized network reachability manager, actively monitoring the specified reachability.
+ */
+- (instancetype)initWithReachability:(SCNetworkReachabilityRef)reachability NS_DESIGNATED_INITIALIZER;
+
+///--------------------------------------------------
+/// @name Starting & Stopping Reachability Monitoring
+///--------------------------------------------------
+
+/**
+ Starts monitoring for changes in network reachability status.
+ */
+- (void)startMonitoring;
+
+/**
+ Stops monitoring for changes in network reachability status.
+ */
+- (void)stopMonitoring;
+
+///-------------------------------------------------
+/// @name Getting Localized Reachability Description
+///-------------------------------------------------
+
+/**
+ Returns a localized string representation of the current network reachability status.
+ */
+- (NSString *)localizedNetworkReachabilityStatusString;
+
+///---------------------------------------------------
+/// @name Setting Network Reachability Change Callback
+///---------------------------------------------------
+
+/**
+ Sets a callback to be executed when the network availability of the `baseURL` host changes.
+
+ @param block A block object to be executed when the network availability of the `baseURL` host changes.. This block has no return value and takes a single argument which represents the various reachability states from the device to the `baseURL`.
+ */
+- (void)setReachabilityStatusChangeBlock:(nullable void (^)(AFNetworkReachabilityStatus status))block;
+
+@end
+
+///----------------
+/// @name Constants
+///----------------
+
+/**
+ ## Network Reachability
+
+ The following constants are provided by `AFNetworkReachabilityManager` as possible network reachability statuses.
+
+ enum {
+ AFNetworkReachabilityStatusUnknown,
+ AFNetworkReachabilityStatusNotReachable,
+ AFNetworkReachabilityStatusReachableViaWWAN,
+ AFNetworkReachabilityStatusReachableViaWiFi,
+ }
+
+ `AFNetworkReachabilityStatusUnknown`
+ The `baseURL` host reachability is not known.
+
+ `AFNetworkReachabilityStatusNotReachable`
+ The `baseURL` host cannot be reached.
+
+ `AFNetworkReachabilityStatusReachableViaWWAN`
+ The `baseURL` host can be reached via a cellular connection, such as EDGE or GPRS.
+
+ `AFNetworkReachabilityStatusReachableViaWiFi`
+ The `baseURL` host can be reached via a Wi-Fi connection.
+
+ ### Keys for Notification UserInfo Dictionary
+
+ Strings that are used as keys in a `userInfo` dictionary in a network reachability status change notification.
+
+ `AFNetworkingReachabilityNotificationStatusItem`
+ A key in the userInfo dictionary in a `AFNetworkingReachabilityDidChangeNotification` notification.
+ The corresponding value is an `NSNumber` object representing the `AFNetworkReachabilityStatus` value for the current reachability status.
+ */
+
+///--------------------
+/// @name Notifications
+///--------------------
+
+/**
+ Posted when network reachability changes.
+ This notification assigns no notification object. The `userInfo` dictionary contains an `NSNumber` object under the `AFNetworkingReachabilityNotificationStatusItem` key, representing the `AFNetworkReachabilityStatus` value for the current network reachability.
+
+ @warning In order for network reachability to be monitored, include the `SystemConfiguration` framework in the active target's "Link Binary With Library" build phase, and add `#import <SystemConfiguration/SystemConfiguration.h>` to the header prefix of the project (`Prefix.pch`).
+ */
+FOUNDATION_EXPORT NSString * const AFNetworkingReachabilityDidChangeNotification;
+FOUNDATION_EXPORT NSString * const AFNetworkingReachabilityNotificationStatusItem;
+
+///--------------------
+/// @name Functions
+///--------------------
+
+/**
+ Returns a localized string representation of an `AFNetworkReachabilityStatus` value.
+ */
+FOUNDATION_EXPORT NSString * AFStringFromNetworkReachabilityStatus(AFNetworkReachabilityStatus status);
+
+NS_ASSUME_NONNULL_END
+#endif

+ 262 - 0
sdk/Objective-C/PhalApiClient/AFNPhalApiClient/Vendor/AFNetworking-2.6.1/AFNetworkReachabilityManager.m

@@ -0,0 +1,262 @@
+// AFNetworkReachabilityManager.m
+// Copyright (c) 2011–2015 Alamofire Software Foundation (http://alamofire.org/)
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+#import "AFNetworkReachabilityManager.h"
+#if !TARGET_OS_WATCH
+
+#import <netinet/in.h>
+#import <netinet6/in6.h>
+#import <arpa/inet.h>
+#import <ifaddrs.h>
+#import <netdb.h>
+
+NSString * const AFNetworkingReachabilityDidChangeNotification = @"com.alamofire.networking.reachability.change";
+NSString * const AFNetworkingReachabilityNotificationStatusItem = @"AFNetworkingReachabilityNotificationStatusItem";
+
+typedef void (^AFNetworkReachabilityStatusBlock)(AFNetworkReachabilityStatus status);
+
+typedef NS_ENUM(NSUInteger, AFNetworkReachabilityAssociation) {
+    AFNetworkReachabilityForAddress = 1,
+    AFNetworkReachabilityForAddressPair = 2,
+    AFNetworkReachabilityForName = 3,
+};
+
+NSString * AFStringFromNetworkReachabilityStatus(AFNetworkReachabilityStatus status) {
+    switch (status) {
+        case AFNetworkReachabilityStatusNotReachable:
+            return NSLocalizedStringFromTable(@"Not Reachable", @"AFNetworking", nil);
+        case AFNetworkReachabilityStatusReachableViaWWAN:
+            return NSLocalizedStringFromTable(@"Reachable via WWAN", @"AFNetworking", nil);
+        case AFNetworkReachabilityStatusReachableViaWiFi:
+            return NSLocalizedStringFromTable(@"Reachable via WiFi", @"AFNetworking", nil);
+        case AFNetworkReachabilityStatusUnknown:
+        default:
+            return NSLocalizedStringFromTable(@"Unknown", @"AFNetworking", nil);
+    }
+}
+
+static AFNetworkReachabilityStatus AFNetworkReachabilityStatusForFlags(SCNetworkReachabilityFlags flags) {
+    BOOL isReachable = ((flags & kSCNetworkReachabilityFlagsReachable) != 0);
+    BOOL needsConnection = ((flags & kSCNetworkReachabilityFlagsConnectionRequired) != 0);
+    BOOL canConnectionAutomatically = (((flags & kSCNetworkReachabilityFlagsConnectionOnDemand ) != 0) || ((flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) != 0));
+    BOOL canConnectWithoutUserInteraction = (canConnectionAutomatically && (flags & kSCNetworkReachabilityFlagsInterventionRequired) == 0);
+    BOOL isNetworkReachable = (isReachable && (!needsConnection || canConnectWithoutUserInteraction));
+
+    AFNetworkReachabilityStatus status = AFNetworkReachabilityStatusUnknown;
+    if (isNetworkReachable == NO) {
+        status = AFNetworkReachabilityStatusNotReachable;
+    }
+#if	TARGET_OS_IPHONE
+    else if ((flags & kSCNetworkReachabilityFlagsIsWWAN) != 0) {
+        status = AFNetworkReachabilityStatusReachableViaWWAN;
+    }
+#endif
+    else {
+        status = AFNetworkReachabilityStatusReachableViaWiFi;
+    }
+
+    return status;
+}
+
+static void AFNetworkReachabilityCallback(SCNetworkReachabilityRef __unused target, SCNetworkReachabilityFlags flags, void *info) {
+    AFNetworkReachabilityStatus status = AFNetworkReachabilityStatusForFlags(flags);
+    AFNetworkReachabilityStatusBlock block = (__bridge AFNetworkReachabilityStatusBlock)info;
+    if (block) {
+        block(status);
+    }
+
+
+    dispatch_async(dispatch_get_main_queue(), ^{
+        NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter];
+        NSDictionary *userInfo = @{ AFNetworkingReachabilityNotificationStatusItem: @(status) };
+        [notificationCenter postNotificationName:AFNetworkingReachabilityDidChangeNotification object:nil userInfo:userInfo];
+    });
+
+}
+
+static const void * AFNetworkReachabilityRetainCallback(const void *info) {
+    return Block_copy(info);
+}
+
+static void AFNetworkReachabilityReleaseCallback(const void *info) {
+    if (info) {
+        Block_release(info);
+    }
+}
+
+@interface AFNetworkReachabilityManager ()
+@property (readwrite, nonatomic, strong) id networkReachability;
+@property (readwrite, nonatomic, assign) AFNetworkReachabilityAssociation networkReachabilityAssociation;
+@property (readwrite, nonatomic, assign) AFNetworkReachabilityStatus networkReachabilityStatus;
+@property (readwrite, nonatomic, copy) AFNetworkReachabilityStatusBlock networkReachabilityStatusBlock;
+@end
+
+@implementation AFNetworkReachabilityManager
+
++ (instancetype)sharedManager {
+    static AFNetworkReachabilityManager *_sharedManager = nil;
+    static dispatch_once_t onceToken;
+    dispatch_once(&onceToken, ^{
+        struct sockaddr_in address;
+        bzero(&address, sizeof(address));
+        address.sin_len = sizeof(address);
+        address.sin_family = AF_INET;
+
+        _sharedManager = [self managerForAddress:&address];
+    });
+
+    return _sharedManager;
+}
+
++ (instancetype)managerForDomain:(NSString *)domain {
+    SCNetworkReachabilityRef reachability = SCNetworkReachabilityCreateWithName(kCFAllocatorDefault, [domain UTF8String]);
+
+    AFNetworkReachabilityManager *manager = [[self alloc] initWithReachability:reachability];
+    manager.networkReachabilityAssociation = AFNetworkReachabilityForName;
+
+    return manager;
+}
+
++ (instancetype)managerForAddress:(const void *)address {
+    SCNetworkReachabilityRef reachability = SCNetworkReachabilityCreateWithAddress(kCFAllocatorDefault, (const struct sockaddr *)address);
+
+    AFNetworkReachabilityManager *manager = [[self alloc] initWithReachability:reachability];
+    manager.networkReachabilityAssociation = AFNetworkReachabilityForAddress;
+
+    return manager;
+}
+
+- (instancetype)initWithReachability:(SCNetworkReachabilityRef)reachability {
+    self = [super init];
+    if (!self) {
+        return nil;
+    }
+
+    self.networkReachability = CFBridgingRelease(reachability);
+    self.networkReachabilityStatus = AFNetworkReachabilityStatusUnknown;
+
+    return self;
+}
+
+- (instancetype)init NS_UNAVAILABLE
+{
+    return nil;
+}
+
+- (void)dealloc {
+    [self stopMonitoring];
+}
+
+#pragma mark -
+
+- (BOOL)isReachable {
+    return [self isReachableViaWWAN] || [self isReachableViaWiFi];
+}
+
+- (BOOL)isReachableViaWWAN {
+    return self.networkReachabilityStatus == AFNetworkReachabilityStatusReachableViaWWAN;
+}
+
+- (BOOL)isReachableViaWiFi {
+    return self.networkReachabilityStatus == AFNetworkReachabilityStatusReachableViaWiFi;
+}
+
+#pragma mark -
+
+- (void)startMonitoring {
+    [self stopMonitoring];
+
+    if (!self.networkReachability) {
+        return;
+    }
+
+    __weak __typeof(self)weakSelf = self;
+    AFNetworkReachabilityStatusBlock callback = ^(AFNetworkReachabilityStatus status) {
+        __strong __typeof(weakSelf)strongSelf = weakSelf;
+
+        strongSelf.networkReachabilityStatus = status;
+        if (strongSelf.networkReachabilityStatusBlock) {
+            strongSelf.networkReachabilityStatusBlock(status);
+        }
+
+    };
+
+    id networkReachability = self.networkReachability;
+    SCNetworkReachabilityContext context = {0, (__bridge void *)callback, AFNetworkReachabilityRetainCallback, AFNetworkReachabilityReleaseCallback, NULL};
+    SCNetworkReachabilitySetCallback((__bridge SCNetworkReachabilityRef)networkReachability, AFNetworkReachabilityCallback, &context);
+    SCNetworkReachabilityScheduleWithRunLoop((__bridge SCNetworkReachabilityRef)networkReachability, CFRunLoopGetMain(), kCFRunLoopCommonModes);
+
+    switch (self.networkReachabilityAssociation) {
+        case AFNetworkReachabilityForName:
+            break;
+        case AFNetworkReachabilityForAddress:
+        case AFNetworkReachabilityForAddressPair:
+        default: {
+            dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0),^{
+                SCNetworkReachabilityFlags flags;
+                SCNetworkReachabilityGetFlags((__bridge SCNetworkReachabilityRef)networkReachability, &flags);
+                AFNetworkReachabilityStatus status = AFNetworkReachabilityStatusForFlags(flags);
+                dispatch_async(dispatch_get_main_queue(), ^{
+                    callback(status);
+
+                    NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter];
+                    [notificationCenter postNotificationName:AFNetworkingReachabilityDidChangeNotification object:nil userInfo:@{ AFNetworkingReachabilityNotificationStatusItem: @(status) }];
+
+
+                });
+            });
+        }
+            break;
+    }
+}
+
+- (void)stopMonitoring {
+    if (!self.networkReachability) {
+        return;
+    }
+
+    SCNetworkReachabilityUnscheduleFromRunLoop((__bridge SCNetworkReachabilityRef)self.networkReachability, CFRunLoopGetMain(), kCFRunLoopCommonModes);
+}
+
+#pragma mark -
+
+- (NSString *)localizedNetworkReachabilityStatusString {
+    return AFStringFromNetworkReachabilityStatus(self.networkReachabilityStatus);
+}
+
+#pragma mark -
+
+- (void)setReachabilityStatusChangeBlock:(void (^)(AFNetworkReachabilityStatus status))block {
+    self.networkReachabilityStatusBlock = block;
+}
+
+#pragma mark - NSKeyValueObserving
+
++ (NSSet *)keyPathsForValuesAffectingValueForKey:(NSString *)key {
+    if ([key isEqualToString:@"reachable"] || [key isEqualToString:@"reachableViaWWAN"] || [key isEqualToString:@"reachableViaWiFi"]) {
+        return [NSSet setWithObject:@"networkReachabilityStatus"];
+    }
+
+    return [super keyPathsForValuesAffectingValueForKey:key];
+}
+
+@end
+#endif

+ 46 - 0
sdk/Objective-C/PhalApiClient/AFNPhalApiClient/Vendor/AFNetworking-2.6.1/AFNetworking.h

@@ -0,0 +1,46 @@
+// AFNetworking.h
+//
+// Copyright (c) 2013 AFNetworking (http://afnetworking.com/)
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+#import <Foundation/Foundation.h>
+#import <Availability.h>
+
+#ifndef _AFNETWORKING_
+    #define _AFNETWORKING_
+
+    #import "AFURLRequestSerialization.h"
+    #import "AFURLResponseSerialization.h"
+    #import "AFSecurityPolicy.h"
+#if !TARGET_OS_WATCH
+    #import "AFNetworkReachabilityManager.h"
+    #import "AFURLConnectionOperation.h"
+    #import "AFHTTPRequestOperation.h"
+    #import "AFHTTPRequestOperationManager.h"
+#endif
+
+#if ( ( defined(__MAC_OS_X_VERSION_MAX_ALLOWED) && __MAC_OS_X_VERSION_MAX_ALLOWED >= 1090) || \
+      ( defined(__IPHONE_OS_VERSION_MAX_ALLOWED) && __IPHONE_OS_VERSION_MAX_ALLOWED >= 70000 ) || \
+       TARGET_OS_WATCH )
+    #import "AFURLSessionManager.h"
+    #import "AFHTTPSessionManager.h"
+#endif
+
+#endif /* _AFNETWORKING_ */

+ 142 - 0
sdk/Objective-C/PhalApiClient/AFNPhalApiClient/Vendor/AFNetworking-2.6.1/AFSecurityPolicy.h

@@ -0,0 +1,142 @@
+// AFSecurityPolicy.h
+// Copyright (c) 2011–2015 Alamofire Software Foundation (http://alamofire.org/)
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+#import <Foundation/Foundation.h>
+#import <Security/Security.h>
+
+typedef NS_ENUM(NSUInteger, AFSSLPinningMode) {
+    AFSSLPinningModeNone,
+    AFSSLPinningModePublicKey,
+    AFSSLPinningModeCertificate,
+};
+
+/**
+ `AFSecurityPolicy` evaluates server trust against pinned X.509 certificates and public keys over secure connections.
+
+ Adding pinned SSL certificates to your app helps prevent man-in-the-middle attacks and other vulnerabilities. Applications dealing with sensitive customer data or financial information are strongly encouraged to route all communication over an HTTPS connection with SSL pinning configured and enabled.
+ */
+
+NS_ASSUME_NONNULL_BEGIN
+
+@interface AFSecurityPolicy : NSObject
+
+/**
+ The criteria by which server trust should be evaluated against the pinned SSL certificates. Defaults to `AFSSLPinningModeNone`.
+ */
+@property (readonly, nonatomic, assign) AFSSLPinningMode SSLPinningMode;
+
+/**
+ The certificates used to evaluate server trust according to the SSL pinning mode. By default, this property is set to any (`.cer`) certificates included in the app bundle. Note that if you create an array with duplicate certificates, the duplicate certificates will be removed. Note that if pinning is enabled, `evaluateServerTrust:forDomain:` will return true if any pinned certificate matches.
+ */
+@property (nonatomic, strong, nullable) NSArray *pinnedCertificates;
+
+/**
+ Whether or not to trust servers with an invalid or expired SSL certificates. Defaults to `NO`.
+ */
+@property (nonatomic, assign) BOOL allowInvalidCertificates;
+
+/**
+ Whether or not to validate the domain name in the certificate's CN field. Defaults to `YES`.
+ */
+@property (nonatomic, assign) BOOL validatesDomainName;
+
+///-----------------------------------------
+/// @name Getting Specific Security Policies
+///-----------------------------------------
+
+/**
+ Returns the shared default security policy, which does not allow invalid certificates, validates domain name, and does not validate against pinned certificates or public keys.
+
+ @return The default security policy.
+ */
++ (instancetype)defaultPolicy;
+
+///---------------------
+/// @name Initialization
+///---------------------
+
+/**
+ Creates and returns a security policy with the specified pinning mode.
+
+ @param pinningMode The SSL pinning mode.
+
+ @return A new security policy.
+ */
++ (instancetype)policyWithPinningMode:(AFSSLPinningMode)pinningMode;
+
+///------------------------------
+/// @name Evaluating Server Trust
+///------------------------------
+
+/**
+ Whether or not the specified server trust should be accepted, based on the security policy.
+
+ This method should be used when responding to an authentication challenge from a server.
+
+ @param serverTrust The X.509 certificate trust of the server.
+
+ @return Whether or not to trust the server.
+
+ @warning This method has been deprecated in favor of `-evaluateServerTrust:forDomain:`.
+ */
+- (BOOL)evaluateServerTrust:(SecTrustRef)serverTrust DEPRECATED_ATTRIBUTE;
+
+/**
+ Whether or not the specified server trust should be accepted, based on the security policy.
+
+ This method should be used when responding to an authentication challenge from a server.
+
+ @param serverTrust The X.509 certificate trust of the server.
+ @param domain The domain of serverTrust. If `nil`, the domain will not be validated.
+
+ @return Whether or not to trust the server.
+ */
+- (BOOL)evaluateServerTrust:(SecTrustRef)serverTrust
+                  forDomain:(nullable NSString *)domain;
+
+@end
+
+NS_ASSUME_NONNULL_END
+
+///----------------
+/// @name Constants
+///----------------
+
+/**
+ ## SSL Pinning Modes
+
+ The following constants are provided by `AFSSLPinningMode` as possible SSL pinning modes.
+
+ enum {
+ AFSSLPinningModeNone,
+ AFSSLPinningModePublicKey,
+ AFSSLPinningModeCertificate,
+ }
+
+ `AFSSLPinningModeNone`
+ Do not used pinned certificates to validate servers.
+
+ `AFSSLPinningModePublicKey`
+ Validate host certificates against public keys of pinned certificates.
+
+ `AFSSLPinningModeCertificate`
+ Validate host certificates against pinned certificates.
+*/

+ 311 - 0
sdk/Objective-C/PhalApiClient/AFNPhalApiClient/Vendor/AFNetworking-2.6.1/AFSecurityPolicy.m

@@ -0,0 +1,311 @@
+// AFSecurityPolicy.m
+// Copyright (c) 2011–2015 Alamofire Software Foundation (http://alamofire.org/)
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+#import "AFSecurityPolicy.h"
+
+#import <AssertMacros.h>
+
+#if !TARGET_OS_IOS && !TARGET_OS_WATCH
+static NSData * AFSecKeyGetData(SecKeyRef key) {
+    CFDataRef data = NULL;
+
+    __Require_noErr_Quiet(SecItemExport(key, kSecFormatUnknown, kSecItemPemArmour, NULL, &data), _out);
+
+    return (__bridge_transfer NSData *)data;
+
+_out:
+    if (data) {
+        CFRelease(data);
+    }
+
+    return nil;
+}
+#endif
+
+static BOOL AFSecKeyIsEqualToKey(SecKeyRef key1, SecKeyRef key2) {
+#if TARGET_OS_IOS || TARGET_OS_WATCH
+    return [(__bridge id)key1 isEqual:(__bridge id)key2];
+#else
+    return [AFSecKeyGetData(key1) isEqual:AFSecKeyGetData(key2)];
+#endif
+}
+
+static id AFPublicKeyForCertificate(NSData *certificate) {
+    id allowedPublicKey = nil;
+    SecCertificateRef allowedCertificate;
+    SecCertificateRef allowedCertificates[1];
+    CFArrayRef tempCertificates = nil;
+    SecPolicyRef policy = nil;
+    SecTrustRef allowedTrust = nil;
+    SecTrustResultType result;
+
+    allowedCertificate = SecCertificateCreateWithData(NULL, (__bridge CFDataRef)certificate);
+    __Require_Quiet(allowedCertificate != NULL, _out);
+
+    allowedCertificates[0] = allowedCertificate;
+    tempCertificates = CFArrayCreate(NULL, (const void **)allowedCertificates, 1, NULL);
+
+    policy = SecPolicyCreateBasicX509();
+    __Require_noErr_Quiet(SecTrustCreateWithCertificates(tempCertificates, policy, &allowedTrust), _out);
+    __Require_noErr_Quiet(SecTrustEvaluate(allowedTrust, &result), _out);
+
+    allowedPublicKey = (__bridge_transfer id)SecTrustCopyPublicKey(allowedTrust);
+
+_out:
+    if (allowedTrust) {
+        CFRelease(allowedTrust);
+    }
+
+    if (policy) {
+        CFRelease(policy);
+    }
+
+    if (tempCertificates) {
+        CFRelease(tempCertificates);
+    }
+
+    if (allowedCertificate) {
+        CFRelease(allowedCertificate);
+    }
+
+    return allowedPublicKey;
+}
+
+static BOOL AFServerTrustIsValid(SecTrustRef serverTrust) {
+    BOOL isValid = NO;
+    SecTrustResultType result;
+    __Require_noErr_Quiet(SecTrustEvaluate(serverTrust, &result), _out);
+
+    isValid = (result == kSecTrustResultUnspecified || result == kSecTrustResultProceed);
+
+_out:
+    return isValid;
+}
+
+static NSArray * AFCertificateTrustChainForServerTrust(SecTrustRef serverTrust) {
+    CFIndex certificateCount = SecTrustGetCertificateCount(serverTrust);
+    NSMutableArray *trustChain = [NSMutableArray arrayWithCapacity:(NSUInteger)certificateCount];
+
+    for (CFIndex i = 0; i < certificateCount; i++) {
+        SecCertificateRef certificate = SecTrustGetCertificateAtIndex(serverTrust, i);
+        [trustChain addObject:(__bridge_transfer NSData *)SecCertificateCopyData(certificate)];
+    }
+
+    return [NSArray arrayWithArray:trustChain];
+}
+
+static NSArray * AFPublicKeyTrustChainForServerTrust(SecTrustRef serverTrust) {
+    SecPolicyRef policy = SecPolicyCreateBasicX509();
+    CFIndex certificateCount = SecTrustGetCertificateCount(serverTrust);
+    NSMutableArray *trustChain = [NSMutableArray arrayWithCapacity:(NSUInteger)certificateCount];
+    for (CFIndex i = 0; i < certificateCount; i++) {
+        SecCertificateRef certificate = SecTrustGetCertificateAtIndex(serverTrust, i);
+
+        SecCertificateRef someCertificates[] = {certificate};
+        CFArrayRef certificates = CFArrayCreate(NULL, (const void **)someCertificates, 1, NULL);
+
+        SecTrustRef trust;
+        __Require_noErr_Quiet(SecTrustCreateWithCertificates(certificates, policy, &trust), _out);
+
+        SecTrustResultType result;
+        __Require_noErr_Quiet(SecTrustEvaluate(trust, &result), _out);
+
+        [trustChain addObject:(__bridge_transfer id)SecTrustCopyPublicKey(trust)];
+
+    _out:
+        if (trust) {
+            CFRelease(trust);
+        }
+
+        if (certificates) {
+            CFRelease(certificates);
+        }
+
+        continue;
+    }
+    CFRelease(policy);
+
+    return [NSArray arrayWithArray:trustChain];
+}
+
+#pragma mark -
+
+@interface AFSecurityPolicy()
+@property (readwrite, nonatomic, assign) AFSSLPinningMode SSLPinningMode;
+@property (readwrite, nonatomic, strong) NSArray *pinnedPublicKeys;
+@end
+
+@implementation AFSecurityPolicy
+
++ (NSArray *)defaultPinnedCertificates {
+    static NSArray *_defaultPinnedCertificates = nil;
+    static dispatch_once_t onceToken;
+    dispatch_once(&onceToken, ^{
+        NSBundle *bundle = [NSBundle bundleForClass:[self class]];
+        NSArray *paths = [bundle pathsForResourcesOfType:@"cer" inDirectory:@"."];
+
+        NSMutableArray *certificates = [NSMutableArray arrayWithCapacity:[paths count]];
+        for (NSString *path in paths) {
+            NSData *certificateData = [NSData dataWithContentsOfFile:path];
+            [certificates addObject:certificateData];
+        }
+
+        _defaultPinnedCertificates = [[NSArray alloc] initWithArray:certificates];
+    });
+
+    return _defaultPinnedCertificates;
+}
+
++ (instancetype)defaultPolicy {
+    AFSecurityPolicy *securityPolicy = [[self alloc] init];
+    securityPolicy.SSLPinningMode = AFSSLPinningModeNone;
+
+    return securityPolicy;
+}
+
++ (instancetype)policyWithPinningMode:(AFSSLPinningMode)pinningMode {
+    AFSecurityPolicy *securityPolicy = [[self alloc] init];
+    securityPolicy.SSLPinningMode = pinningMode;
+
+    [securityPolicy setPinnedCertificates:[self defaultPinnedCertificates]];
+
+    return securityPolicy;
+}
+
+- (id)init {
+    self = [super init];
+    if (!self) {
+        return nil;
+    }
+
+    self.validatesDomainName = YES;
+
+    return self;
+}
+
+- (void)setPinnedCertificates:(NSArray *)pinnedCertificates {
+    _pinnedCertificates = [[NSOrderedSet orderedSetWithArray:pinnedCertificates] array];
+
+    if (self.pinnedCertificates) {
+        NSMutableArray *mutablePinnedPublicKeys = [NSMutableArray arrayWithCapacity:[self.pinnedCertificates count]];
+        for (NSData *certificate in self.pinnedCertificates) {
+            id publicKey = AFPublicKeyForCertificate(certificate);
+            if (!publicKey) {
+                continue;
+            }
+            [mutablePinnedPublicKeys addObject:publicKey];
+        }
+        self.pinnedPublicKeys = [NSArray arrayWithArray:mutablePinnedPublicKeys];
+    } else {
+        self.pinnedPublicKeys = nil;
+    }
+}
+
+#pragma mark -
+
+- (BOOL)evaluateServerTrust:(SecTrustRef)serverTrust {
+    return [self evaluateServerTrust:serverTrust forDomain:nil];
+}
+
+- (BOOL)evaluateServerTrust:(SecTrustRef)serverTrust
+                  forDomain:(NSString *)domain
+{
+    if (domain && self.allowInvalidCertificates && self.validatesDomainName && (self.SSLPinningMode == AFSSLPinningModeNone || [self.pinnedCertificates count] == 0)) {
+        // https://developer.apple.com/library/mac/documentation/NetworkingInternet/Conceptual/NetworkingTopics/Articles/OverridingSSLChainValidationCorrectly.html
+        //  According to the docs, you should only trust your provided certs for evaluation.
+        //  Pinned certificates are added to the trust. Without pinned certificates,
+        //  there is nothing to evaluate against.
+        //
+        //  From Apple Docs:
+        //          "Do not implicitly trust self-signed certificates as anchors (kSecTrustOptionImplicitAnchors).
+        //           Instead, add your own (self-signed) CA certificate to the list of trusted anchors."
+        NSLog(@"In order to validate a domain name for self signed certificates, you MUST use pinning.");
+        return NO;
+    }
+
+    NSMutableArray *policies = [NSMutableArray array];
+    if (self.validatesDomainName) {
+        [policies addObject:(__bridge_transfer id)SecPolicyCreateSSL(true, (__bridge CFStringRef)domain)];
+    } else {
+        [policies addObject:(__bridge_transfer id)SecPolicyCreateBasicX509()];
+    }
+
+    SecTrustSetPolicies(serverTrust, (__bridge CFArrayRef)policies);
+
+    if (self.SSLPinningMode == AFSSLPinningModeNone) {
+        if (self.allowInvalidCertificates || AFServerTrustIsValid(serverTrust)){
+            return YES;
+        } else {
+            return NO;
+        }
+    } else if (!AFServerTrustIsValid(serverTrust) && !self.allowInvalidCertificates) {
+        return NO;
+    }
+
+    NSArray *serverCertificates = AFCertificateTrustChainForServerTrust(serverTrust);
+    switch (self.SSLPinningMode) {
+        case AFSSLPinningModeNone:
+        default:
+            return NO;
+        case AFSSLPinningModeCertificate: {
+            NSMutableArray *pinnedCertificates = [NSMutableArray array];
+            for (NSData *certificateData in self.pinnedCertificates) {
+                [pinnedCertificates addObject:(__bridge_transfer id)SecCertificateCreateWithData(NULL, (__bridge CFDataRef)certificateData)];
+            }
+            SecTrustSetAnchorCertificates(serverTrust, (__bridge CFArrayRef)pinnedCertificates);
+
+            if (!AFServerTrustIsValid(serverTrust)) {
+                return NO;
+            }
+
+            NSUInteger trustedCertificateCount = 0;
+            for (NSData *trustChainCertificate in serverCertificates) {
+                if ([self.pinnedCertificates containsObject:trustChainCertificate]) {
+                    trustedCertificateCount++;
+                }
+            }
+            return trustedCertificateCount > 0;
+        }
+        case AFSSLPinningModePublicKey: {
+            NSUInteger trustedPublicKeyCount = 0;
+            NSArray *publicKeys = AFPublicKeyTrustChainForServerTrust(serverTrust);
+
+            for (id trustChainPublicKey in publicKeys) {
+                for (id pinnedPublicKey in self.pinnedPublicKeys) {
+                    if (AFSecKeyIsEqualToKey((__bridge SecKeyRef)trustChainPublicKey, (__bridge SecKeyRef)pinnedPublicKey)) {
+                        trustedPublicKeyCount += 1;
+                    }
+                }
+            }
+            return trustedPublicKeyCount > 0;
+        }
+    }
+    
+    return NO;
+}
+
+#pragma mark - NSKeyValueObserving
+
++ (NSSet *)keyPathsForValuesAffectingPinnedPublicKeys {
+    return [NSSet setWithObject:@"pinnedCertificates"];
+}
+
+@end

File diff suppressed because it is too large
+ 344 - 0
sdk/Objective-C/PhalApiClient/AFNPhalApiClient/Vendor/AFNetworking-2.6.1/AFURLConnectionOperation.h


+ 792 - 0
sdk/Objective-C/PhalApiClient/AFNPhalApiClient/Vendor/AFNetworking-2.6.1/AFURLConnectionOperation.m

@@ -0,0 +1,792 @@
+// AFURLConnectionOperation.m
+// Copyright (c) 2011–2015 Alamofire Software Foundation (http://alamofire.org/)
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+#import "AFURLConnectionOperation.h"
+
+#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED)
+#import <UIKit/UIKit.h>
+#endif
+
+#if !__has_feature(objc_arc)
+#error AFNetworking must be built with ARC.
+// You can turn on ARC for only AFNetworking files by adding -fobjc-arc to the build phase for each of its files.
+#endif
+
+typedef NS_ENUM(NSInteger, AFOperationState) {
+    AFOperationPausedState      = -1,
+    AFOperationReadyState       = 1,
+    AFOperationExecutingState   = 2,
+    AFOperationFinishedState    = 3,
+};
+
+static dispatch_group_t url_request_operation_completion_group() {
+    static dispatch_group_t af_url_request_operation_completion_group;
+    static dispatch_once_t onceToken;
+    dispatch_once(&onceToken, ^{
+        af_url_request_operation_completion_group = dispatch_group_create();
+    });
+
+    return af_url_request_operation_completion_group;
+}
+
+static dispatch_queue_t url_request_operation_completion_queue() {
+    static dispatch_queue_t af_url_request_operation_completion_queue;
+    static dispatch_once_t onceToken;
+    dispatch_once(&onceToken, ^{
+        af_url_request_operation_completion_queue = dispatch_queue_create("com.alamofire.networking.operation.queue", DISPATCH_QUEUE_CONCURRENT );
+    });
+
+    return af_url_request_operation_completion_queue;
+}
+
+static NSString * const kAFNetworkingLockName = @"com.alamofire.networking.operation.lock";
+
+NSString * const AFNetworkingOperationDidStartNotification = @"com.alamofire.networking.operation.start";
+NSString * const AFNetworkingOperationDidFinishNotification = @"com.alamofire.networking.operation.finish";
+
+typedef void (^AFURLConnectionOperationProgressBlock)(NSUInteger bytes, long long totalBytes, long long totalBytesExpected);
+typedef void (^AFURLConnectionOperationAuthenticationChallengeBlock)(NSURLConnection *connection, NSURLAuthenticationChallenge *challenge);
+typedef NSCachedURLResponse * (^AFURLConnectionOperationCacheResponseBlock)(NSURLConnection *connection, NSCachedURLResponse *cachedResponse);
+typedef NSURLRequest * (^AFURLConnectionOperationRedirectResponseBlock)(NSURLConnection *connection, NSURLRequest *request, NSURLResponse *redirectResponse);
+typedef void (^AFURLConnectionOperationBackgroundTaskCleanupBlock)();
+
+static inline NSString * AFKeyPathFromOperationState(AFOperationState state) {
+    switch (state) {
+        case AFOperationReadyState:
+            return @"isReady";
+        case AFOperationExecutingState:
+            return @"isExecuting";
+        case AFOperationFinishedState:
+            return @"isFinished";
+        case AFOperationPausedState:
+            return @"isPaused";
+        default: {
+#pragma clang diagnostic push
+#pragma clang diagnostic ignored "-Wunreachable-code"
+            return @"state";
+#pragma clang diagnostic pop
+        }
+    }
+}
+
+static inline BOOL AFStateTransitionIsValid(AFOperationState fromState, AFOperationState toState, BOOL isCancelled) {
+    switch (fromState) {
+        case AFOperationReadyState:
+            switch (toState) {
+                case AFOperationPausedState:
+                case AFOperationExecutingState:
+                    return YES;
+                case AFOperationFinishedState:
+                    return isCancelled;
+                default:
+                    return NO;
+            }
+        case AFOperationExecutingState:
+            switch (toState) {
+                case AFOperationPausedState:
+                case AFOperationFinishedState:
+                    return YES;
+                default:
+                    return NO;
+            }
+        case AFOperationFinishedState:
+            return NO;
+        case AFOperationPausedState:
+            return toState == AFOperationReadyState;
+        default: {
+#pragma clang diagnostic push
+#pragma clang diagnostic ignored "-Wunreachable-code"
+            switch (toState) {
+                case AFOperationPausedState:
+                case AFOperationReadyState:
+                case AFOperationExecutingState:
+                case AFOperationFinishedState:
+                    return YES;
+                default:
+                    return NO;
+            }
+        }
+#pragma clang diagnostic pop
+    }
+}
+
+@interface AFURLConnectionOperation ()
+@property (readwrite, nonatomic, assign) AFOperationState state;
+@property (readwrite, nonatomic, strong) NSRecursiveLock *lock;
+@property (readwrite, nonatomic, strong) NSURLConnection *connection;
+@property (readwrite, nonatomic, strong) NSURLRequest *request;
+@property (readwrite, nonatomic, strong) NSURLResponse *response;
+@property (readwrite, nonatomic, strong) NSError *error;
+@property (readwrite, nonatomic, strong) NSData *responseData;
+@property (readwrite, nonatomic, copy) NSString *responseString;
+@property (readwrite, nonatomic, assign) NSStringEncoding responseStringEncoding;
+@property (readwrite, nonatomic, assign) long long totalBytesRead;
+@property (readwrite, nonatomic, copy) AFURLConnectionOperationBackgroundTaskCleanupBlock backgroundTaskCleanup;
+@property (readwrite, nonatomic, copy) AFURLConnectionOperationProgressBlock uploadProgress;
+@property (readwrite, nonatomic, copy) AFURLConnectionOperationProgressBlock downloadProgress;
+@property (readwrite, nonatomic, copy) AFURLConnectionOperationAuthenticationChallengeBlock authenticationChallenge;
+@property (readwrite, nonatomic, copy) AFURLConnectionOperationCacheResponseBlock cacheResponse;
+@property (readwrite, nonatomic, copy) AFURLConnectionOperationRedirectResponseBlock redirectResponse;
+
+- (void)operationDidStart;
+- (void)finish;
+- (void)cancelConnection;
+@end
+
+@implementation AFURLConnectionOperation
+@synthesize outputStream = _outputStream;
+
++ (void)networkRequestThreadEntryPoint:(id)__unused object {
+    @autoreleasepool {
+        [[NSThread currentThread] setName:@"AFNetworking"];
+
+        NSRunLoop *runLoop = [NSRunLoop currentRunLoop];
+        [runLoop addPort:[NSMachPort port] forMode:NSDefaultRunLoopMode];
+        [runLoop run];
+    }
+}
+
++ (NSThread *)networkRequestThread {
+    static NSThread *_networkRequestThread = nil;
+    static dispatch_once_t oncePredicate;
+    dispatch_once(&oncePredicate, ^{
+        _networkRequestThread = [[NSThread alloc] initWithTarget:self selector:@selector(networkRequestThreadEntryPoint:) object:nil];
+        [_networkRequestThread start];
+    });
+
+    return _networkRequestThread;
+}
+
+- (instancetype)initWithRequest:(NSURLRequest *)urlRequest {
+    NSParameterAssert(urlRequest);
+
+    self = [super init];
+    if (!self) {
+		return nil;
+    }
+
+    _state = AFOperationReadyState;
+
+    self.lock = [[NSRecursiveLock alloc] init];
+    self.lock.name = kAFNetworkingLockName;
+
+    self.runLoopModes = [NSSet setWithObject:NSRunLoopCommonModes];
+
+    self.request = urlRequest;
+
+    self.shouldUseCredentialStorage = YES;
+
+    self.securityPolicy = [AFSecurityPolicy defaultPolicy];
+
+    return self;
+}
+
+- (instancetype)init NS_UNAVAILABLE
+{
+    return nil;
+}
+
+- (void)dealloc {
+    if (_outputStream) {
+        [_outputStream close];
+        _outputStream = nil;
+    }
+    
+    if (_backgroundTaskCleanup) {
+        _backgroundTaskCleanup();
+    }
+}
+
+#pragma mark -
+
+- (void)setResponseData:(NSData *)responseData {
+    [self.lock lock];
+    if (!responseData) {
+        _responseData = nil;
+    } else {
+        _responseData = [NSData dataWithBytes:responseData.bytes length:responseData.length];
+    }
+    [self.lock unlock];
+}
+
+- (NSString *)responseString {
+    [self.lock lock];
+    if (!_responseString && self.response && self.responseData) {
+        self.responseString = [[NSString alloc] initWithData:self.responseData encoding:self.responseStringEncoding];
+    }
+    [self.lock unlock];
+
+    return _responseString;
+}
+
+- (NSStringEncoding)responseStringEncoding {
+    [self.lock lock];
+    if (!_responseStringEncoding && self.response) {
+        NSStringEncoding stringEncoding = NSUTF8StringEncoding;
+        if (self.response.textEncodingName) {
+            CFStringEncoding IANAEncoding = CFStringConvertIANACharSetNameToEncoding((__bridge CFStringRef)self.response.textEncodingName);
+            if (IANAEncoding != kCFStringEncodingInvalidId) {
+                stringEncoding = CFStringConvertEncodingToNSStringEncoding(IANAEncoding);
+            }
+        }
+
+        self.responseStringEncoding = stringEncoding;
+    }
+    [self.lock unlock];
+
+    return _responseStringEncoding;
+}
+
+- (NSInputStream *)inputStream {
+    return self.request.HTTPBodyStream;
+}
+
+- (void)setInputStream:(NSInputStream *)inputStream {
+    NSMutableURLRequest *mutableRequest = [self.request mutableCopy];
+    mutableRequest.HTTPBodyStream = inputStream;
+    self.request = mutableRequest;
+}
+
+- (NSOutputStream *)outputStream {
+    if (!_outputStream) {
+        self.outputStream = [NSOutputStream outputStreamToMemory];
+    }
+
+    return _outputStream;
+}
+
+- (void)setOutputStream:(NSOutputStream *)outputStream {
+    [self.lock lock];
+    if (outputStream != _outputStream) {
+        if (_outputStream) {
+            [_outputStream close];
+        }
+
+        _outputStream = outputStream;
+    }
+    [self.lock unlock];
+}
+
+#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED)
+- (void)setShouldExecuteAsBackgroundTaskWithExpirationHandler:(void (^)(void))handler {
+    [self.lock lock];
+    if (!self.backgroundTaskCleanup) {
+        UIApplication *application = [UIApplication sharedApplication];
+        UIBackgroundTaskIdentifier __block backgroundTaskIdentifier = UIBackgroundTaskInvalid;
+        __weak __typeof(self)weakSelf = self;
+        
+        self.backgroundTaskCleanup = ^(){
+            if (backgroundTaskIdentifier != UIBackgroundTaskInvalid) {
+                [[UIApplication sharedApplication] endBackgroundTask:backgroundTaskIdentifier];
+                backgroundTaskIdentifier = UIBackgroundTaskInvalid;
+            }
+        };
+        
+        backgroundTaskIdentifier = [application beginBackgroundTaskWithExpirationHandler:^{
+            __strong __typeof(weakSelf)strongSelf = weakSelf;
+
+            if (handler) {
+                handler();
+            }
+
+            if (strongSelf) {
+                [strongSelf cancel];
+                strongSelf.backgroundTaskCleanup();
+            }
+        }];
+    }
+    [self.lock unlock];
+}
+#endif
+
+#pragma mark -
+
+- (void)setState:(AFOperationState)state {
+    if (!AFStateTransitionIsValid(self.state, state, [self isCancelled])) {
+        return;
+    }
+
+    [self.lock lock];
+    NSString *oldStateKey = AFKeyPathFromOperationState(self.state);
+    NSString *newStateKey = AFKeyPathFromOperationState(state);
+
+    [self willChangeValueForKey:newStateKey];
+    [self willChangeValueForKey:oldStateKey];
+    _state = state;
+    [self didChangeValueForKey:oldStateKey];
+    [self didChangeValueForKey:newStateKey];
+    [self.lock unlock];
+}
+
+- (void)pause {
+    if ([self isPaused] || [self isFinished] || [self isCancelled]) {
+        return;
+    }
+
+    [self.lock lock];
+    if ([self isExecuting]) {
+        [self performSelector:@selector(operationDidPause) onThread:[[self class] networkRequestThread] withObject:nil waitUntilDone:NO modes:[self.runLoopModes allObjects]];
+
+        dispatch_async(dispatch_get_main_queue(), ^{
+            NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter];
+            [notificationCenter postNotificationName:AFNetworkingOperationDidFinishNotification object:self];
+        });
+    }
+
+    self.state = AFOperationPausedState;
+    [self.lock unlock];
+}
+
+- (void)operationDidPause {
+    [self.lock lock];
+    [self.connection cancel];
+    [self.lock unlock];
+}
+
+- (BOOL)isPaused {
+    return self.state == AFOperationPausedState;
+}
+
+- (void)resume {
+    if (![self isPaused]) {
+        return;
+    }
+
+    [self.lock lock];
+    self.state = AFOperationReadyState;
+
+    [self start];
+    [self.lock unlock];
+}
+
+#pragma mark -
+
+- (void)setUploadProgressBlock:(void (^)(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite))block {
+    self.uploadProgress = block;
+}
+
+- (void)setDownloadProgressBlock:(void (^)(NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead))block {
+    self.downloadProgress = block;
+}
+
+- (void)setWillSendRequestForAuthenticationChallengeBlock:(void (^)(NSURLConnection *connection, NSURLAuthenticationChallenge *challenge))block {
+    self.authenticationChallenge = block;
+}
+
+- (void)setCacheResponseBlock:(NSCachedURLResponse * (^)(NSURLConnection *connection, NSCachedURLResponse *cachedResponse))block {
+    self.cacheResponse = block;
+}
+
+- (void)setRedirectResponseBlock:(NSURLRequest * (^)(NSURLConnection *connection, NSURLRequest *request, NSURLResponse *redirectResponse))block {
+    self.redirectResponse = block;
+}
+
+#pragma mark - NSOperation
+
+- (void)setCompletionBlock:(void (^)(void))block {
+    [self.lock lock];
+    if (!block) {
+        [super setCompletionBlock:nil];
+    } else {
+        __weak __typeof(self)weakSelf = self;
+        [super setCompletionBlock:^ {
+            __strong __typeof(weakSelf)strongSelf = weakSelf;
+
+#pragma clang diagnostic push
+#pragma clang diagnostic ignored "-Wgnu"
+            dispatch_group_t group = strongSelf.completionGroup ?: url_request_operation_completion_group();
+            dispatch_queue_t queue = strongSelf.completionQueue ?: dispatch_get_main_queue();
+#pragma clang diagnostic pop
+
+            dispatch_group_async(group, queue, ^{
+                block();
+            });
+
+            dispatch_group_notify(group, url_request_operation_completion_queue(), ^{
+                [strongSelf setCompletionBlock:nil];
+            });
+        }];
+    }
+    [self.lock unlock];
+}
+
+- (BOOL)isReady {
+    return self.state == AFOperationReadyState && [super isReady];
+}
+
+- (BOOL)isExecuting {
+    return self.state == AFOperationExecutingState;
+}
+
+- (BOOL)isFinished {
+    return self.state == AFOperationFinishedState;
+}
+
+- (BOOL)isConcurrent {
+    return YES;
+}
+
+- (void)start {
+    [self.lock lock];
+    if ([self isCancelled]) {
+        [self performSelector:@selector(cancelConnection) onThread:[[self class] networkRequestThread] withObject:nil waitUntilDone:NO modes:[self.runLoopModes allObjects]];
+    } else if ([self isReady]) {
+        self.state = AFOperationExecutingState;
+
+        [self performSelector:@selector(operationDidStart) onThread:[[self class] networkRequestThread] withObject:nil waitUntilDone:NO modes:[self.runLoopModes allObjects]];
+    }
+    [self.lock unlock];
+}
+
+- (void)operationDidStart {
+    [self.lock lock];
+    if (![self isCancelled]) {
+        self.connection = [[NSURLConnection alloc] initWithRequest:self.request delegate:self startImmediately:NO];
+
+        NSRunLoop *runLoop = [NSRunLoop currentRunLoop];
+        for (NSString *runLoopMode in self.runLoopModes) {
+            [self.connection scheduleInRunLoop:runLoop forMode:runLoopMode];
+            [self.outputStream scheduleInRunLoop:runLoop forMode:runLoopMode];
+        }
+
+        [self.outputStream open];
+        [self.connection start];
+    }
+    [self.lock unlock];
+
+    dispatch_async(dispatch_get_main_queue(), ^{
+        [[NSNotificationCenter defaultCenter] postNotificationName:AFNetworkingOperationDidStartNotification object:self];
+    });
+}
+
+- (void)finish {
+    [self.lock lock];
+    self.state = AFOperationFinishedState;
+    [self.lock unlock];
+
+    dispatch_async(dispatch_get_main_queue(), ^{
+        [[NSNotificationCenter defaultCenter] postNotificationName:AFNetworkingOperationDidFinishNotification object:self];
+    });
+}
+
+- (void)cancel {
+    [self.lock lock];
+    if (![self isFinished] && ![self isCancelled]) {
+        [super cancel];
+
+        if ([self isExecuting]) {
+            [self performSelector:@selector(cancelConnection) onThread:[[self class] networkRequestThread] withObject:nil waitUntilDone:NO modes:[self.runLoopModes allObjects]];
+        }
+    }
+    [self.lock unlock];
+}
+
+- (void)cancelConnection {
+    NSDictionary *userInfo = nil;
+    if ([self.request URL]) {
+        userInfo = @{NSURLErrorFailingURLErrorKey : [self.request URL]};
+    }
+    NSError *error = [NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorCancelled userInfo:userInfo];
+
+    if (![self isFinished]) {
+        if (self.connection) {
+            [self.connection cancel];
+            [self performSelector:@selector(connection:didFailWithError:) withObject:self.connection withObject:error];
+        } else {
+            // Accommodate race condition where `self.connection` has not yet been set before cancellation
+            self.error = error;
+            [self finish];
+        }
+    }
+}
+
+#pragma mark -
+
++ (NSArray *)batchOfRequestOperations:(NSArray *)operations
+                        progressBlock:(void (^)(NSUInteger numberOfFinishedOperations, NSUInteger totalNumberOfOperations))progressBlock
+                      completionBlock:(void (^)(NSArray *operations))completionBlock
+{
+    if (!operations || [operations count] == 0) {
+        return @[[NSBlockOperation blockOperationWithBlock:^{
+            dispatch_async(dispatch_get_main_queue(), ^{
+                if (completionBlock) {
+                    completionBlock(@[]);
+                }
+            });
+        }]];
+    }
+
+    __block dispatch_group_t group = dispatch_group_create();
+    NSBlockOperation *batchedOperation = [NSBlockOperation blockOperationWithBlock:^{
+        dispatch_group_notify(group, dispatch_get_main_queue(), ^{
+            if (completionBlock) {
+                completionBlock(operations);
+            }
+        });
+    }];
+
+    for (AFURLConnectionOperation *operation in operations) {
+        operation.completionGroup = group;
+        void (^originalCompletionBlock)(void) = [operation.completionBlock copy];
+        __weak __typeof(operation)weakOperation = operation;
+        operation.completionBlock = ^{
+            __strong __typeof(weakOperation)strongOperation = weakOperation;
+#pragma clang diagnostic push
+#pragma clang diagnostic ignored "-Wgnu"
+            dispatch_queue_t queue = strongOperation.completionQueue ?: dispatch_get_main_queue();
+#pragma clang diagnostic pop
+            dispatch_group_async(group, queue, ^{
+                if (originalCompletionBlock) {
+                    originalCompletionBlock();
+                }
+
+                NSUInteger numberOfFinishedOperations = [[operations indexesOfObjectsPassingTest:^BOOL(id op, NSUInteger __unused idx,  BOOL __unused *stop) {
+                    return [op isFinished];
+                }] count];
+
+                if (progressBlock) {
+                    progressBlock(numberOfFinishedOperations, [operations count]);
+                }
+
+                dispatch_group_leave(group);
+            });
+        };
+
+        dispatch_group_enter(group);
+        [batchedOperation addDependency:operation];
+    }
+
+    return [operations arrayByAddingObject:batchedOperation];
+}
+
+#pragma mark - NSObject
+
+- (NSString *)description {
+    [self.lock lock];
+    NSString *description = [NSString stringWithFormat:@"<%@: %p, state: %@, cancelled: %@ request: %@, response: %@>", NSStringFromClass([self class]), self, AFKeyPathFromOperationState(self.state), ([self isCancelled] ? @"YES" : @"NO"), self.request, self.response];
+    [self.lock unlock];
+    return description;
+}
+
+#pragma mark - NSURLConnectionDelegate
+
+- (void)connection:(NSURLConnection *)connection
+willSendRequestForAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge
+{
+    if (self.authenticationChallenge) {
+        self.authenticationChallenge(connection, challenge);
+        return;
+    }
+
+    if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) {
+        if ([self.securityPolicy evaluateServerTrust:challenge.protectionSpace.serverTrust forDomain:challenge.protectionSpace.host]) {
+            NSURLCredential *credential = [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust];
+            [[challenge sender] useCredential:credential forAuthenticationChallenge:challenge];
+        } else {
+            [[challenge sender] cancelAuthenticationChallenge:challenge];
+        }
+    } else {
+        if ([challenge previousFailureCount] == 0) {
+            if (self.credential) {
+                [[challenge sender] useCredential:self.credential forAuthenticationChallenge:challenge];
+            } else {
+                [[challenge sender] continueWithoutCredentialForAuthenticationChallenge:challenge];
+            }
+        } else {
+            [[challenge sender] continueWithoutCredentialForAuthenticationChallenge:challenge];
+        }
+    }
+}
+
+- (BOOL)connectionShouldUseCredentialStorage:(NSURLConnection __unused *)connection {
+    return self.shouldUseCredentialStorage;
+}
+
+- (NSURLRequest *)connection:(NSURLConnection *)connection
+             willSendRequest:(NSURLRequest *)request
+            redirectResponse:(NSURLResponse *)redirectResponse
+{
+    if (self.redirectResponse) {
+        return self.redirectResponse(connection, request, redirectResponse);
+    } else {
+        return request;
+    }
+}
+
+- (void)connection:(NSURLConnection __unused *)connection
+   didSendBodyData:(NSInteger)bytesWritten
+ totalBytesWritten:(NSInteger)totalBytesWritten
+totalBytesExpectedToWrite:(NSInteger)totalBytesExpectedToWrite
+{
+    dispatch_async(dispatch_get_main_queue(), ^{
+        if (self.uploadProgress) {
+            self.uploadProgress((NSUInteger)bytesWritten, totalBytesWritten, totalBytesExpectedToWrite);
+        }
+    });
+}
+
+- (void)connection:(NSURLConnection __unused *)connection
+didReceiveResponse:(NSURLResponse *)response
+{
+    self.response = response;
+}
+
+- (void)connection:(NSURLConnection __unused *)connection
+    didReceiveData:(NSData *)data
+{
+    NSUInteger length = [data length];
+    while (YES) {
+        NSInteger totalNumberOfBytesWritten = 0;
+        if ([self.outputStream hasSpaceAvailable]) {
+            const uint8_t *dataBuffer = (uint8_t *)[data bytes];
+
+            NSInteger numberOfBytesWritten = 0;
+            while (totalNumberOfBytesWritten < (NSInteger)length) {
+                numberOfBytesWritten = [self.outputStream write:&dataBuffer[(NSUInteger)totalNumberOfBytesWritten] maxLength:(length - (NSUInteger)totalNumberOfBytesWritten)];
+                if (numberOfBytesWritten == -1) {
+                    break;
+                }
+
+                totalNumberOfBytesWritten += numberOfBytesWritten;
+            }
+
+            break;
+        } else {
+            [self.connection cancel];
+            if (self.outputStream.streamError) {
+                [self performSelector:@selector(connection:didFailWithError:) withObject:self.connection withObject:self.outputStream.streamError];
+            }
+            return;
+        }
+    }
+
+    dispatch_async(dispatch_get_main_queue(), ^{
+        self.totalBytesRead += (long long)length;
+
+        if (self.downloadProgress) {
+            self.downloadProgress(length, self.totalBytesRead, self.response.expectedContentLength);
+        }
+    });
+}
+
+- (void)connectionDidFinishLoading:(NSURLConnection __unused *)connection {
+    self.responseData = [self.outputStream propertyForKey:NSStreamDataWrittenToMemoryStreamKey];
+
+    [self.outputStream close];
+    if (self.responseData) {
+       self.outputStream = nil;
+    }
+
+    self.connection = nil;
+
+    [self finish];
+}
+
+- (void)connection:(NSURLConnection __unused *)connection
+  didFailWithError:(NSError *)error
+{
+    self.error = error;
+
+    [self.outputStream close];
+    if (self.responseData) {
+        self.outputStream = nil;
+    }
+
+    self.connection = nil;
+
+    [self finish];
+}
+
+- (NSCachedURLResponse *)connection:(NSURLConnection *)connection
+                  willCacheResponse:(NSCachedURLResponse *)cachedResponse
+{
+    if (self.cacheResponse) {
+        return self.cacheResponse(connection, cachedResponse);
+    } else {
+        if ([self isCancelled]) {
+            return nil;
+        }
+
+        return cachedResponse;
+    }
+}
+
+#pragma mark - NSSecureCoding
+
++ (BOOL)supportsSecureCoding {
+    return YES;
+}
+
+- (id)initWithCoder:(NSCoder *)decoder {
+    NSURLRequest *request = [decoder decodeObjectOfClass:[NSURLRequest class] forKey:NSStringFromSelector(@selector(request))];
+
+    self = [self initWithRequest:request];
+    if (!self) {
+        return nil;
+    }
+
+    self.state = [[decoder decodeObjectOfClass:[NSNumber class] forKey:NSStringFromSelector(@selector(state))] integerValue];
+    self.response = [decoder decodeObjectOfClass:[NSHTTPURLResponse class] forKey:NSStringFromSelector(@selector(response))];
+    self.error = [decoder decodeObjectOfClass:[NSError class] forKey:NSStringFromSelector(@selector(error))];
+    self.responseData = [decoder decodeObjectOfClass:[NSData class] forKey:NSStringFromSelector(@selector(responseData))];
+    self.totalBytesRead = [[decoder decodeObjectOfClass:[NSNumber class] forKey:NSStringFromSelector(@selector(totalBytesRead))] longLongValue];
+
+    return self;
+}
+
+- (void)encodeWithCoder:(NSCoder *)coder {
+    [self pause];
+
+    [coder encodeObject:self.request forKey:NSStringFromSelector(@selector(request))];
+
+    switch (self.state) {
+        case AFOperationExecutingState:
+        case AFOperationPausedState:
+            [coder encodeInteger:AFOperationReadyState forKey:NSStringFromSelector(@selector(state))];
+            break;
+        default:
+            [coder encodeInteger:self.state forKey:NSStringFromSelector(@selector(state))];
+            break;
+    }
+
+    [coder encodeObject:self.response forKey:NSStringFromSelector(@selector(response))];
+    [coder encodeObject:self.error forKey:NSStringFromSelector(@selector(error))];
+    [coder encodeObject:self.responseData forKey:NSStringFromSelector(@selector(responseData))];
+    [coder encodeInt64:self.totalBytesRead forKey:NSStringFromSelector(@selector(totalBytesRead))];
+}
+
+#pragma mark - NSCopying
+
+- (id)copyWithZone:(NSZone *)zone {
+    AFURLConnectionOperation *operation = [(AFURLConnectionOperation *)[[self class] allocWithZone:zone] initWithRequest:self.request];
+
+    operation.uploadProgress = self.uploadProgress;
+    operation.downloadProgress = self.downloadProgress;
+    operation.authenticationChallenge = self.authenticationChallenge;
+    operation.cacheResponse = self.cacheResponse;
+    operation.redirectResponse = self.redirectResponse;
+    operation.completionQueue = self.completionQueue;
+    operation.completionGroup = self.completionGroup;
+
+    return operation;
+}
+
+@end

File diff suppressed because it is too large
+ 473 - 0
sdk/Objective-C/PhalApiClient/AFNPhalApiClient/Vendor/AFNetworking-2.6.1/AFURLRequestSerialization.h


File diff suppressed because it is too large
+ 1425 - 0
sdk/Objective-C/PhalApiClient/AFNPhalApiClient/Vendor/AFNetworking-2.6.1/AFURLRequestSerialization.m


+ 311 - 0
sdk/Objective-C/PhalApiClient/AFNPhalApiClient/Vendor/AFNetworking-2.6.1/AFURLResponseSerialization.h

@@ -0,0 +1,311 @@
+// AFURLResponseSerialization.h
+// Copyright (c) 2011–2015 Alamofire Software Foundation (http://alamofire.org/)
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+#import <Foundation/Foundation.h>
+#import <CoreGraphics/CoreGraphics.h>
+
+NS_ASSUME_NONNULL_BEGIN
+
+/**
+ The `AFURLResponseSerialization` protocol is adopted by an object that decodes data into a more useful object representation, according to details in the server response. Response serializers may additionally perform validation on the incoming response and data.
+
+ For example, a JSON response serializer may check for an acceptable status code (`2XX` range) and content type (`application/json`), decoding a valid JSON response into an object.
+ */
+@protocol AFURLResponseSerialization <NSObject, NSSecureCoding, NSCopying>
+
+/**
+ The response object decoded from the data associated with a specified response.
+
+ @param response The response to be processed.
+ @param data The response data to be decoded.
+ @param error The error that occurred while attempting to decode the response data.
+
+ @return The object decoded from the specified response data.
+ */
+- (nullable id)responseObjectForResponse:(nullable NSURLResponse *)response
+                           data:(nullable NSData *)data
+                          error:(NSError * __nullable __autoreleasing *)error;
+
+@end
+
+#pragma mark -
+
+/**
+ `AFHTTPResponseSerializer` conforms to the `AFURLRequestSerialization` & `AFURLResponseSerialization` protocols, offering a concrete base implementation of query string / URL form-encoded parameter serialization and default request headers, as well as response status code and content type validation.
+
+ Any request or response serializer dealing with HTTP is encouraged to subclass `AFHTTPResponseSerializer` in order to ensure consistent default behavior.
+ */
+@interface AFHTTPResponseSerializer : NSObject <AFURLResponseSerialization>
+
+- (instancetype)init;
+
+/**
+ The string encoding used to serialize data received from the server, when no string encoding is specified by the response. `NSUTF8StringEncoding` by default.
+ */
+@property (nonatomic, assign) NSStringEncoding stringEncoding;
+
+/**
+ Creates and returns a serializer with default configuration.
+ */
++ (instancetype)serializer;
+
+///-----------------------------------------
+/// @name Configuring Response Serialization
+///-----------------------------------------
+
+/**
+ The acceptable HTTP status codes for responses. When non-`nil`, responses with status codes not contained by the set will result in an error during validation.
+
+ See http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
+ */
+@property (nonatomic, copy, nullable) NSIndexSet *acceptableStatusCodes;
+
+/**
+ The acceptable MIME types for responses. When non-`nil`, responses with a `Content-Type` with MIME types that do not intersect with the set will result in an error during validation.
+ */
+@property (nonatomic, copy, nullable) NSSet *acceptableContentTypes;
+
+/**
+ Validates the specified response and data.
+
+ In its base implementation, this method checks for an acceptable status code and content type. Subclasses may wish to add other domain-specific checks.
+
+ @param response The response to be validated.
+ @param data The data associated with the response.
+ @param error The error that occurred while attempting to validate the response.
+
+ @return `YES` if the response is valid, otherwise `NO`.
+ */
+- (BOOL)validateResponse:(nullable NSHTTPURLResponse *)response
+                    data:(nullable NSData *)data
+                   error:(NSError * __nullable __autoreleasing *)error;
+
+@end
+
+#pragma mark -
+
+
+/**
+ `AFJSONResponseSerializer` is a subclass of `AFHTTPResponseSerializer` that validates and decodes JSON responses.
+
+ By default, `AFJSONResponseSerializer` accepts the following MIME types, which includes the official standard, `application/json`, as well as other commonly-used types:
+
+ - `application/json`
+ - `text/json`
+ - `text/javascript`
+ */
+@interface AFJSONResponseSerializer : AFHTTPResponseSerializer
+
+- (instancetype)init;
+
+/**
+ Options for reading the response JSON data and creating the Foundation objects. For possible values, see the `NSJSONSerialization` documentation section "NSJSONReadingOptions". `0` by default.
+ */
+@property (nonatomic, assign) NSJSONReadingOptions readingOptions;
+
+/**
+ Whether to remove keys with `NSNull` values from response JSON. Defaults to `NO`.
+ */
+@property (nonatomic, assign) BOOL removesKeysWithNullValues;
+
+/**
+ Creates and returns a JSON serializer with specified reading and writing options.
+
+ @param readingOptions The specified JSON reading options.
+ */
++ (instancetype)serializerWithReadingOptions:(NSJSONReadingOptions)readingOptions;
+
+@end
+
+#pragma mark -
+
+/**
+ `AFXMLParserResponseSerializer` is a subclass of `AFHTTPResponseSerializer` that validates and decodes XML responses as an `NSXMLParser` objects.
+
+ By default, `AFXMLParserResponseSerializer` accepts the following MIME types, which includes the official standard, `application/xml`, as well as other commonly-used types:
+
+ - `application/xml`
+ - `text/xml`
+ */
+@interface AFXMLParserResponseSerializer : AFHTTPResponseSerializer
+
+@end
+
+#pragma mark -
+
+#ifdef __MAC_OS_X_VERSION_MIN_REQUIRED
+
+/**
+ `AFXMLDocumentResponseSerializer` is a subclass of `AFHTTPResponseSerializer` that validates and decodes XML responses as an `NSXMLDocument` objects.
+
+ By default, `AFXMLDocumentResponseSerializer` accepts the following MIME types, which includes the official standard, `application/xml`, as well as other commonly-used types:
+
+ - `application/xml`
+ - `text/xml`
+ */
+@interface AFXMLDocumentResponseSerializer : AFHTTPResponseSerializer
+
+- (instancetype)init;
+
+/**
+ Input and output options specifically intended for `NSXMLDocument` objects. For possible values, see the `NSJSONSerialization` documentation section "NSJSONReadingOptions". `0` by default.
+ */
+@property (nonatomic, assign) NSUInteger options;
+
+/**
+ Creates and returns an XML document serializer with the specified options.
+
+ @param mask The XML document options.
+ */
++ (instancetype)serializerWithXMLDocumentOptions:(NSUInteger)mask;
+
+@end
+
+#endif
+
+#pragma mark -
+
+/**
+ `AFPropertyListResponseSerializer` is a subclass of `AFHTTPResponseSerializer` that validates and decodes XML responses as an `NSXMLDocument` objects.
+
+ By default, `AFPropertyListResponseSerializer` accepts the following MIME types:
+
+ - `application/x-plist`
+ */
+@interface AFPropertyListResponseSerializer : AFHTTPResponseSerializer
+
+- (instancetype)init;
+
+/**
+ The property list format. Possible values are described in "NSPropertyListFormat".
+ */
+@property (nonatomic, assign) NSPropertyListFormat format;
+
+/**
+ The property list reading options. Possible values are described in "NSPropertyListMutabilityOptions."
+ */
+@property (nonatomic, assign) NSPropertyListReadOptions readOptions;
+
+/**
+ Creates and returns a property list serializer with a specified format, read options, and write options.
+
+ @param format The property list format.
+ @param readOptions The property list reading options.
+ */
++ (instancetype)serializerWithFormat:(NSPropertyListFormat)format
+                         readOptions:(NSPropertyListReadOptions)readOptions;
+
+@end
+
+#pragma mark -
+
+/**
+ `AFImageResponseSerializer` is a subclass of `AFHTTPResponseSerializer` that validates and decodes image responses.
+
+ By default, `AFImageResponseSerializer` accepts the following MIME types, which correspond to the image formats supported by UIImage or NSImage:
+
+ - `image/tiff`
+ - `image/jpeg`
+ - `image/gif`
+ - `image/png`
+ - `image/ico`
+ - `image/x-icon`
+ - `image/bmp`
+ - `image/x-bmp`
+ - `image/x-xbitmap`
+ - `image/x-win-bitmap`
+ */
+@interface AFImageResponseSerializer : AFHTTPResponseSerializer
+
+#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED)
+/**
+ The scale factor used when interpreting the image data to construct `responseImage`. Specifying a scale factor of 1.0 results in an image whose size matches the pixel-based dimensions of the image. Applying a different scale factor changes the size of the image as reported by the size property. This is set to the value of scale of the main screen by default, which automatically scales images for retina displays, for instance.
+ */
+@property (nonatomic, assign) CGFloat imageScale;
+
+/**
+ Whether to automatically inflate response image data for compressed formats (such as PNG or JPEG). Enabling this can significantly improve drawing performance on iOS when used with `setCompletionBlockWithSuccess:failure:`, as it allows a bitmap representation to be constructed in the background rather than on the main thread. `YES` by default.
+ */
+@property (nonatomic, assign) BOOL automaticallyInflatesResponseImage;
+#endif
+
+@end
+
+#pragma mark -
+
+/**
+ `AFCompoundSerializer` is a subclass of `AFHTTPResponseSerializer` that delegates the response serialization to the first `AFHTTPResponseSerializer` object that returns an object for `responseObjectForResponse:data:error:`, falling back on the default behavior of `AFHTTPResponseSerializer`. This is useful for supporting multiple potential types and structures of server responses with a single serializer.
+ */
+@interface AFCompoundResponseSerializer : AFHTTPResponseSerializer
+
+/**
+ The component response serializers.
+ */
+@property (readonly, nonatomic, copy) NSArray *responseSerializers;
+
+/**
+ Creates and returns a compound serializer comprised of the specified response serializers.
+
+ @warning Each response serializer specified must be a subclass of `AFHTTPResponseSerializer`, and response to `-validateResponse:data:error:`.
+ */
++ (instancetype)compoundSerializerWithResponseSerializers:(NSArray *)responseSerializers;
+
+@end
+
+///----------------
+/// @name Constants
+///----------------
+
+/**
+ ## Error Domains
+
+ The following error domain is predefined.
+
+ - `NSString * const AFURLResponseSerializationErrorDomain`
+
+ ### Constants
+
+ `AFURLResponseSerializationErrorDomain`
+ AFURLResponseSerializer errors. Error codes for `AFURLResponseSerializationErrorDomain` correspond to codes in `NSURLErrorDomain`.
+ */
+FOUNDATION_EXPORT NSString * const AFURLResponseSerializationErrorDomain;
+
+/**
+ ## User info dictionary keys
+
+ These keys may exist in the user info dictionary, in addition to those defined for NSError.
+
+ - `NSString * const AFNetworkingOperationFailingURLResponseErrorKey`
+ - `NSString * const AFNetworkingOperationFailingURLResponseDataErrorKey`
+
+ ### Constants
+
+ `AFNetworkingOperationFailingURLResponseErrorKey`
+ The corresponding value is an `NSURLResponse` containing the response of the operation associated with an error. This key is only present in the `AFURLResponseSerializationErrorDomain`.
+
+ `AFNetworkingOperationFailingURLResponseDataErrorKey`
+ The corresponding value is an `NSData` containing the original data of the operation associated with an error. This key is only present in the `AFURLResponseSerializationErrorDomain`.
+ */
+FOUNDATION_EXPORT NSString * const AFNetworkingOperationFailingURLResponseErrorKey;
+
+FOUNDATION_EXPORT NSString * const AFNetworkingOperationFailingURLResponseDataErrorKey;
+
+NS_ASSUME_NONNULL_END

+ 825 - 0
sdk/Objective-C/PhalApiClient/AFNPhalApiClient/Vendor/AFNetworking-2.6.1/AFURLResponseSerialization.m

@@ -0,0 +1,825 @@
+// AFURLResponseSerialization.m
+// Copyright (c) 2011–2015 Alamofire Software Foundation (http://alamofire.org/)
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+#import "AFURLResponseSerialization.h"
+
+#if TARGET_OS_IOS
+#import <UIKit/UIKit.h>
+#elif TARGET_OS_WATCH
+#import <WatchKit/WatchKit.h>
+#elif defined(__MAC_OS_X_VERSION_MIN_REQUIRED)
+#import <Cocoa/Cocoa.h>
+#endif
+
+NSString * const AFURLResponseSerializationErrorDomain = @"com.alamofire.error.serialization.response";
+NSString * const AFNetworkingOperationFailingURLResponseErrorKey = @"com.alamofire.serialization.response.error.response";
+NSString * const AFNetworkingOperationFailingURLResponseDataErrorKey = @"com.alamofire.serialization.response.error.data";
+
+static NSError * AFErrorWithUnderlyingError(NSError *error, NSError *underlyingError) {
+    if (!error) {
+        return underlyingError;
+    }
+
+    if (!underlyingError || error.userInfo[NSUnderlyingErrorKey]) {
+        return error;
+    }
+
+    NSMutableDictionary *mutableUserInfo = [error.userInfo mutableCopy];
+    mutableUserInfo[NSUnderlyingErrorKey] = underlyingError;
+
+    return [[NSError alloc] initWithDomain:error.domain code:error.code userInfo:mutableUserInfo];
+}
+
+static BOOL AFErrorOrUnderlyingErrorHasCodeInDomain(NSError *error, NSInteger code, NSString *domain) {
+    if ([error.domain isEqualToString:domain] && error.code == code) {
+        return YES;
+    } else if (error.userInfo[NSUnderlyingErrorKey]) {
+        return AFErrorOrUnderlyingErrorHasCodeInDomain(error.userInfo[NSUnderlyingErrorKey], code, domain);
+    }
+
+    return NO;
+}
+
+static id AFJSONObjectByRemovingKeysWithNullValues(id JSONObject, NSJSONReadingOptions readingOptions) {
+    if ([JSONObject isKindOfClass:[NSArray class]]) {
+        NSMutableArray *mutableArray = [NSMutableArray arrayWithCapacity:[(NSArray *)JSONObject count]];
+        for (id value in (NSArray *)JSONObject) {
+            [mutableArray addObject:AFJSONObjectByRemovingKeysWithNullValues(value, readingOptions)];
+        }
+
+        return (readingOptions & NSJSONReadingMutableContainers) ? mutableArray : [NSArray arrayWithArray:mutableArray];
+    } else if ([JSONObject isKindOfClass:[NSDictionary class]]) {
+        NSMutableDictionary *mutableDictionary = [NSMutableDictionary dictionaryWithDictionary:JSONObject];
+        for (id <NSCopying> key in [(NSDictionary *)JSONObject allKeys]) {
+            id value = (NSDictionary *)JSONObject[key];
+            if (!value || [value isEqual:[NSNull null]]) {
+                [mutableDictionary removeObjectForKey:key];
+            } else if ([value isKindOfClass:[NSArray class]] || [value isKindOfClass:[NSDictionary class]]) {
+                mutableDictionary[key] = AFJSONObjectByRemovingKeysWithNullValues(value, readingOptions);
+            }
+        }
+
+        return (readingOptions & NSJSONReadingMutableContainers) ? mutableDictionary : [NSDictionary dictionaryWithDictionary:mutableDictionary];
+    }
+
+    return JSONObject;
+}
+
+@implementation AFHTTPResponseSerializer
+
++ (instancetype)serializer {
+    return [[self alloc] init];
+}
+
+- (instancetype)init {
+    self = [super init];
+    if (!self) {
+        return nil;
+    }
+
+    self.stringEncoding = NSUTF8StringEncoding;
+
+    self.acceptableStatusCodes = [NSIndexSet indexSetWithIndexesInRange:NSMakeRange(200, 100)];
+    self.acceptableContentTypes = nil;
+
+    return self;
+}
+
+#pragma mark -
+
+- (BOOL)validateResponse:(NSHTTPURLResponse *)response
+                    data:(NSData *)data
+                   error:(NSError * __autoreleasing *)error
+{
+    BOOL responseIsValid = YES;
+    NSError *validationError = nil;
+
+    if (response && [response isKindOfClass:[NSHTTPURLResponse class]]) {
+        if (self.acceptableContentTypes && ![self.acceptableContentTypes containsObject:[response MIMEType]]) {
+            if ([data length] > 0 && [response URL]) {
+                NSMutableDictionary *mutableUserInfo = [@{
+                                                          NSLocalizedDescriptionKey: [NSString stringWithFormat:NSLocalizedStringFromTable(@"Request failed: unacceptable content-type: %@", @"AFNetworking", nil), [response MIMEType]],
+                                                          NSURLErrorFailingURLErrorKey:[response URL],
+                                                          AFNetworkingOperationFailingURLResponseErrorKey: response,
+                                                        } mutableCopy];
+                if (data) {
+                    mutableUserInfo[AFNetworkingOperationFailingURLResponseDataErrorKey] = data;
+                }
+
+                validationError = AFErrorWithUnderlyingError([NSError errorWithDomain:AFURLResponseSerializationErrorDomain code:NSURLErrorCannotDecodeContentData userInfo:mutableUserInfo], validationError);
+            }
+
+            responseIsValid = NO;
+        }
+
+        if (self.acceptableStatusCodes && ![self.acceptableStatusCodes containsIndex:(NSUInteger)response.statusCode] && [response URL]) {
+            NSMutableDictionary *mutableUserInfo = [@{
+                                               NSLocalizedDescriptionKey: [NSString stringWithFormat:NSLocalizedStringFromTable(@"Request failed: %@ (%ld)", @"AFNetworking", nil), [NSHTTPURLResponse localizedStringForStatusCode:response.statusCode], (long)response.statusCode],
+                                               NSURLErrorFailingURLErrorKey:[response URL],
+                                               AFNetworkingOperationFailingURLResponseErrorKey: response,
+                                       } mutableCopy];
+
+            if (data) {
+                mutableUserInfo[AFNetworkingOperationFailingURLResponseDataErrorKey] = data;
+            }
+
+            validationError = AFErrorWithUnderlyingError([NSError errorWithDomain:AFURLResponseSerializationErrorDomain code:NSURLErrorBadServerResponse userInfo:mutableUserInfo], validationError);
+
+            responseIsValid = NO;
+        }
+    }
+
+    if (error && !responseIsValid) {
+        *error = validationError;
+    }
+
+    return responseIsValid;
+}
+
+#pragma mark - AFURLResponseSerialization
+
+- (id)responseObjectForResponse:(NSURLResponse *)response
+                           data:(NSData *)data
+                          error:(NSError *__autoreleasing *)error
+{
+    [self validateResponse:(NSHTTPURLResponse *)response data:data error:error];
+
+    return data;
+}
+
+#pragma mark - NSSecureCoding
+
++ (BOOL)supportsSecureCoding {
+    return YES;
+}
+
+- (id)initWithCoder:(NSCoder *)decoder {
+    self = [self init];
+    if (!self) {
+        return nil;
+    }
+
+    self.acceptableStatusCodes = [decoder decodeObjectOfClass:[NSIndexSet class] forKey:NSStringFromSelector(@selector(acceptableStatusCodes))];
+    self.acceptableContentTypes = [decoder decodeObjectOfClass:[NSIndexSet class] forKey:NSStringFromSelector(@selector(acceptableContentTypes))];
+
+    return self;
+}
+
+- (void)encodeWithCoder:(NSCoder *)coder {
+    [coder encodeObject:self.acceptableStatusCodes forKey:NSStringFromSelector(@selector(acceptableStatusCodes))];
+    [coder encodeObject:self.acceptableContentTypes forKey:NSStringFromSelector(@selector(acceptableContentTypes))];
+}
+
+#pragma mark - NSCopying
+
+- (id)copyWithZone:(NSZone *)zone {
+    AFHTTPResponseSerializer *serializer = [[[self class] allocWithZone:zone] init];
+    serializer.acceptableStatusCodes = [self.acceptableStatusCodes copyWithZone:zone];
+    serializer.acceptableContentTypes = [self.acceptableContentTypes copyWithZone:zone];
+
+    return serializer;
+}
+
+@end
+
+#pragma mark -
+
+@implementation AFJSONResponseSerializer
+
++ (instancetype)serializer {
+    return [self serializerWithReadingOptions:(NSJSONReadingOptions)0];
+}
+
++ (instancetype)serializerWithReadingOptions:(NSJSONReadingOptions)readingOptions {
+    AFJSONResponseSerializer *serializer = [[self alloc] init];
+    serializer.readingOptions = readingOptions;
+
+    return serializer;
+}
+
+- (instancetype)init {
+    self = [super init];
+    if (!self) {
+        return nil;
+    }
+
+    self.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", nil];
+
+    return self;
+}
+
+#pragma mark - AFURLResponseSerialization
+
+- (id)responseObjectForResponse:(NSURLResponse *)response
+                           data:(NSData *)data
+                          error:(NSError *__autoreleasing *)error
+{
+    if (![self validateResponse:(NSHTTPURLResponse *)response data:data error:error]) {
+        if (!error || AFErrorOrUnderlyingErrorHasCodeInDomain(*error, NSURLErrorCannotDecodeContentData, AFURLResponseSerializationErrorDomain)) {
+            return nil;
+        }
+    }
+
+    // Workaround for behavior of Rails to return a single space for `head :ok` (a workaround for a bug in Safari), which is not interpreted as valid input by NSJSONSerialization.
+    // See https://github.com/rails/rails/issues/1742
+    NSStringEncoding stringEncoding = self.stringEncoding;
+    if (response.textEncodingName) {
+        CFStringEncoding encoding = CFStringConvertIANACharSetNameToEncoding((CFStringRef)response.textEncodingName);
+        if (encoding != kCFStringEncodingInvalidId) {
+            stringEncoding = CFStringConvertEncodingToNSStringEncoding(encoding);
+        }
+    }
+
+    id responseObject = nil;
+    NSError *serializationError = nil;
+    @autoreleasepool {
+        NSString *responseString = [[NSString alloc] initWithData:data encoding:stringEncoding];
+        if (responseString && ![responseString isEqualToString:@" "]) {
+            // Workaround for a bug in NSJSONSerialization when Unicode character escape codes are used instead of the actual character
+            // See http://stackoverflow.com/a/12843465/157142
+            data = [responseString dataUsingEncoding:NSUTF8StringEncoding];
+
+            if (data) {
+                if ([data length] > 0) {
+                    responseObject = [NSJSONSerialization JSONObjectWithData:data options:self.readingOptions error:&serializationError];
+                } else {
+                    return nil;
+                }
+            } else {
+                NSDictionary *userInfo = @{
+                                           NSLocalizedDescriptionKey: NSLocalizedStringFromTable(@"Data failed decoding as a UTF-8 string", @"AFNetworking", nil),
+                                           NSLocalizedFailureReasonErrorKey: [NSString stringWithFormat:NSLocalizedStringFromTable(@"Could not decode string: %@", @"AFNetworking", nil), responseString]
+                                           };
+
+                serializationError = [NSError errorWithDomain:AFURLResponseSerializationErrorDomain code:NSURLErrorCannotDecodeContentData userInfo:userInfo];
+            }
+        }
+    }
+
+    if (self.removesKeysWithNullValues && responseObject) {
+        responseObject = AFJSONObjectByRemovingKeysWithNullValues(responseObject, self.readingOptions);
+    }
+
+    if (error) {
+        *error = AFErrorWithUnderlyingError(serializationError, *error);
+    }
+
+    return responseObject;
+}
+
+#pragma mark - NSSecureCoding
+
+- (id)initWithCoder:(NSCoder *)decoder {
+    self = [super initWithCoder:decoder];
+    if (!self) {
+        return nil;
+    }
+
+    self.readingOptions = [[decoder decodeObjectOfClass:[NSNumber class] forKey:NSStringFromSelector(@selector(readingOptions))] unsignedIntegerValue];
+    self.removesKeysWithNullValues = [[decoder decodeObjectOfClass:[NSNumber class] forKey:NSStringFromSelector(@selector(removesKeysWithNullValues))] boolValue];
+
+    return self;
+}
+
+- (void)encodeWithCoder:(NSCoder *)coder {
+    [super encodeWithCoder:coder];
+
+    [coder encodeObject:@(self.readingOptions) forKey:NSStringFromSelector(@selector(readingOptions))];
+    [coder encodeObject:@(self.removesKeysWithNullValues) forKey:NSStringFromSelector(@selector(removesKeysWithNullValues))];
+}
+
+#pragma mark - NSCopying
+
+- (id)copyWithZone:(NSZone *)zone {
+    AFJSONResponseSerializer *serializer = [[[self class] allocWithZone:zone] init];
+    serializer.readingOptions = self.readingOptions;
+    serializer.removesKeysWithNullValues = self.removesKeysWithNullValues;
+
+    return serializer;
+}
+
+@end
+
+#pragma mark -
+
+@implementation AFXMLParserResponseSerializer
+
++ (instancetype)serializer {
+    AFXMLParserResponseSerializer *serializer = [[self alloc] init];
+
+    return serializer;
+}
+
+- (instancetype)init {
+    self = [super init];
+    if (!self) {
+        return nil;
+    }
+
+    self.acceptableContentTypes = [[NSSet alloc] initWithObjects:@"application/xml", @"text/xml", nil];
+
+    return self;
+}
+
+#pragma mark - AFURLResponseSerialization
+
+- (id)responseObjectForResponse:(NSHTTPURLResponse *)response
+                           data:(NSData *)data
+                          error:(NSError *__autoreleasing *)error
+{
+    if (![self validateResponse:(NSHTTPURLResponse *)response data:data error:error]) {
+        if (!error || AFErrorOrUnderlyingErrorHasCodeInDomain(*error, NSURLErrorCannotDecodeContentData, AFURLResponseSerializationErrorDomain)) {
+            return nil;
+        }
+    }
+
+    return [[NSXMLParser alloc] initWithData:data];
+}
+
+@end
+
+#pragma mark -
+
+#ifdef __MAC_OS_X_VERSION_MIN_REQUIRED
+
+@implementation AFXMLDocumentResponseSerializer
+
++ (instancetype)serializer {
+    return [self serializerWithXMLDocumentOptions:0];
+}
+
++ (instancetype)serializerWithXMLDocumentOptions:(NSUInteger)mask {
+    AFXMLDocumentResponseSerializer *serializer = [[self alloc] init];
+    serializer.options = mask;
+
+    return serializer;
+}
+
+- (instancetype)init {
+    self = [super init];
+    if (!self) {
+        return nil;
+    }
+
+    self.acceptableContentTypes = [[NSSet alloc] initWithObjects:@"application/xml", @"text/xml", nil];
+
+    return self;
+}
+
+#pragma mark - AFURLResponseSerialization
+
+- (id)responseObjectForResponse:(NSURLResponse *)response
+                           data:(NSData *)data
+                          error:(NSError *__autoreleasing *)error
+{
+    if (![self validateResponse:(NSHTTPURLResponse *)response data:data error:error]) {
+        if (!error || AFErrorOrUnderlyingErrorHasCodeInDomain(*error, NSURLErrorCannotDecodeContentData, AFURLResponseSerializationErrorDomain)) {
+            return nil;
+        }
+    }
+
+    NSError *serializationError = nil;
+    NSXMLDocument *document = [[NSXMLDocument alloc] initWithData:data options:self.options error:&serializationError];
+
+    if (error) {
+        *error = AFErrorWithUnderlyingError(serializationError, *error);
+    }
+
+    return document;
+}
+
+#pragma mark - NSSecureCoding
+
+- (id)initWithCoder:(NSCoder *)decoder {
+    self = [super initWithCoder:decoder];
+    if (!self) {
+        return nil;
+    }
+
+    self.options = [[decoder decodeObjectOfClass:[NSNumber class] forKey:NSStringFromSelector(@selector(options))] unsignedIntegerValue];
+
+    return self;
+}
+
+- (void)encodeWithCoder:(NSCoder *)coder {
+    [super encodeWithCoder:coder];
+
+    [coder encodeObject:@(self.options) forKey:NSStringFromSelector(@selector(options))];
+}
+
+#pragma mark - NSCopying
+
+- (id)copyWithZone:(NSZone *)zone {
+    AFXMLDocumentResponseSerializer *serializer = [[[self class] allocWithZone:zone] init];
+    serializer.options = self.options;
+
+    return serializer;
+}
+
+@end
+
+#endif
+
+#pragma mark -
+
+@implementation AFPropertyListResponseSerializer
+
++ (instancetype)serializer {
+    return [self serializerWithFormat:NSPropertyListXMLFormat_v1_0 readOptions:0];
+}
+
++ (instancetype)serializerWithFormat:(NSPropertyListFormat)format
+                         readOptions:(NSPropertyListReadOptions)readOptions
+{
+    AFPropertyListResponseSerializer *serializer = [[self alloc] init];
+    serializer.format = format;
+    serializer.readOptions = readOptions;
+
+    return serializer;
+}
+
+- (instancetype)init {
+    self = [super init];
+    if (!self) {
+        return nil;
+    }
+
+    self.acceptableContentTypes = [[NSSet alloc] initWithObjects:@"application/x-plist", nil];
+
+    return self;
+}
+
+#pragma mark - AFURLResponseSerialization
+
+- (id)responseObjectForResponse:(NSURLResponse *)response
+                           data:(NSData *)data
+                          error:(NSError *__autoreleasing *)error
+{
+    if (![self validateResponse:(NSHTTPURLResponse *)response data:data error:error]) {
+        if (!error || AFErrorOrUnderlyingErrorHasCodeInDomain(*error, NSURLErrorCannotDecodeContentData, AFURLResponseSerializationErrorDomain)) {
+            return nil;
+        }
+    }
+
+    id responseObject;
+    NSError *serializationError = nil;
+
+    if (data) {
+        responseObject = [NSPropertyListSerialization propertyListWithData:data options:self.readOptions format:NULL error:&serializationError];
+    }
+
+    if (error) {
+        *error = AFErrorWithUnderlyingError(serializationError, *error);
+    }
+
+    return responseObject;
+}
+
+#pragma mark - NSSecureCoding
+
+- (id)initWithCoder:(NSCoder *)decoder {
+    self = [super initWithCoder:decoder];
+    if (!self) {
+        return nil;
+    }
+
+    self.format = [[decoder decodeObjectOfClass:[NSNumber class] forKey:NSStringFromSelector(@selector(format))] unsignedIntegerValue];
+    self.readOptions = [[decoder decodeObjectOfClass:[NSNumber class] forKey:NSStringFromSelector(@selector(readOptions))] unsignedIntegerValue];
+
+    return self;
+}
+
+- (void)encodeWithCoder:(NSCoder *)coder {
+    [super encodeWithCoder:coder];
+
+    [coder encodeObject:@(self.format) forKey:NSStringFromSelector(@selector(format))];
+    [coder encodeObject:@(self.readOptions) forKey:NSStringFromSelector(@selector(readOptions))];
+}
+
+#pragma mark - NSCopying
+
+- (id)copyWithZone:(NSZone *)zone {
+    AFPropertyListResponseSerializer *serializer = [[[self class] allocWithZone:zone] init];
+    serializer.format = self.format;
+    serializer.readOptions = self.readOptions;
+
+    return serializer;
+}
+
+@end
+
+#pragma mark -
+
+#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED)
+#import <CoreGraphics/CoreGraphics.h>
+
+@interface UIImage (AFNetworkingSafeImageLoading)
++ (UIImage *)af_safeImageWithData:(NSData *)data;
+@end
+
+static NSLock* imageLock = nil;
+
+@implementation UIImage (AFNetworkingSafeImageLoading)
+
++ (UIImage *)af_safeImageWithData:(NSData *)data {
+    UIImage* image = nil;
+    static dispatch_once_t onceToken;
+    dispatch_once(&onceToken, ^{
+        imageLock = [[NSLock alloc] init];
+    });
+    
+    [imageLock lock];
+    image = [UIImage imageWithData:data];
+    [imageLock unlock];
+    return image;
+}
+
+@end
+
+static UIImage * AFImageWithDataAtScale(NSData *data, CGFloat scale) {
+    UIImage *image = [UIImage af_safeImageWithData:data];
+    if (image.images) {
+        return image;
+    }
+    
+    return [[UIImage alloc] initWithCGImage:[image CGImage] scale:scale orientation:image.imageOrientation];
+}
+
+static UIImage * AFInflatedImageFromResponseWithDataAtScale(NSHTTPURLResponse *response, NSData *data, CGFloat scale) {
+    if (!data || [data length] == 0) {
+        return nil;
+    }
+
+    CGImageRef imageRef = NULL;
+    CGDataProviderRef dataProvider = CGDataProviderCreateWithCFData((__bridge CFDataRef)data);
+
+    if ([response.MIMEType isEqualToString:@"image/png"]) {
+        imageRef = CGImageCreateWithPNGDataProvider(dataProvider,  NULL, true, kCGRenderingIntentDefault);
+    } else if ([response.MIMEType isEqualToString:@"image/jpeg"]) {
+        imageRef = CGImageCreateWithJPEGDataProvider(dataProvider, NULL, true, kCGRenderingIntentDefault);
+
+        if (imageRef) {
+            CGColorSpaceRef imageColorSpace = CGImageGetColorSpace(imageRef);
+            CGColorSpaceModel imageColorSpaceModel = CGColorSpaceGetModel(imageColorSpace);
+
+            // CGImageCreateWithJPEGDataProvider does not properly handle CMKY, so fall back to AFImageWithDataAtScale
+            if (imageColorSpaceModel == kCGColorSpaceModelCMYK) {
+                CGImageRelease(imageRef);
+                imageRef = NULL;
+            }
+        }
+    }
+
+    CGDataProviderRelease(dataProvider);
+
+    UIImage *image = AFImageWithDataAtScale(data, scale);
+    if (!imageRef) {
+        if (image.images || !image) {
+            return image;
+        }
+
+        imageRef = CGImageCreateCopy([image CGImage]);
+        if (!imageRef) {
+            return nil;
+        }
+    }
+
+    size_t width = CGImageGetWidth(imageRef);
+    size_t height = CGImageGetHeight(imageRef);
+    size_t bitsPerComponent = CGImageGetBitsPerComponent(imageRef);
+
+    if (width * height > 1024 * 1024 || bitsPerComponent > 8) {
+        CGImageRelease(imageRef);
+
+        return image;
+    }
+
+    // CGImageGetBytesPerRow() calculates incorrectly in iOS 5.0, so defer to CGBitmapContextCreate
+    size_t bytesPerRow = 0;
+    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
+    CGColorSpaceModel colorSpaceModel = CGColorSpaceGetModel(colorSpace);
+    CGBitmapInfo bitmapInfo = CGImageGetBitmapInfo(imageRef);
+
+    if (colorSpaceModel == kCGColorSpaceModelRGB) {
+        uint32_t alpha = (bitmapInfo & kCGBitmapAlphaInfoMask);
+#pragma clang diagnostic push
+#pragma clang diagnostic ignored "-Wassign-enum"
+        if (alpha == kCGImageAlphaNone) {
+            bitmapInfo &= ~kCGBitmapAlphaInfoMask;
+            bitmapInfo |= kCGImageAlphaNoneSkipFirst;
+        } else if (!(alpha == kCGImageAlphaNoneSkipFirst || alpha == kCGImageAlphaNoneSkipLast)) {
+            bitmapInfo &= ~kCGBitmapAlphaInfoMask;
+            bitmapInfo |= kCGImageAlphaPremultipliedFirst;
+        }
+#pragma clang diagnostic pop
+    }
+
+    CGContextRef context = CGBitmapContextCreate(NULL, width, height, bitsPerComponent, bytesPerRow, colorSpace, bitmapInfo);
+
+    CGColorSpaceRelease(colorSpace);
+
+    if (!context) {
+        CGImageRelease(imageRef);
+
+        return image;
+    }
+
+    CGContextDrawImage(context, CGRectMake(0.0f, 0.0f, width, height), imageRef);
+    CGImageRef inflatedImageRef = CGBitmapContextCreateImage(context);
+
+    CGContextRelease(context);
+
+    UIImage *inflatedImage = [[UIImage alloc] initWithCGImage:inflatedImageRef scale:scale orientation:image.imageOrientation];
+
+    CGImageRelease(inflatedImageRef);
+    CGImageRelease(imageRef);
+
+    return inflatedImage;
+}
+#endif
+
+
+@implementation AFImageResponseSerializer
+
+- (instancetype)init {
+    self = [super init];
+    if (!self) {
+        return nil;
+    }
+
+    self.acceptableContentTypes = [[NSSet alloc] initWithObjects:@"image/tiff", @"image/jpeg", @"image/gif", @"image/png", @"image/ico", @"image/x-icon", @"image/bmp", @"image/x-bmp", @"image/x-xbitmap", @"image/x-win-bitmap", nil];
+
+#if TARGET_OS_IOS
+    self.imageScale = [[UIScreen mainScreen] scale];
+    self.automaticallyInflatesResponseImage = YES;
+#elif  TARGET_OS_WATCH
+    self.imageScale = [[WKInterfaceDevice currentDevice] screenScale];
+    self.automaticallyInflatesResponseImage = YES;
+#endif
+
+    return self;
+}
+
+#pragma mark - AFURLResponseSerializer
+
+- (id)responseObjectForResponse:(NSURLResponse *)response
+                           data:(NSData *)data
+                          error:(NSError *__autoreleasing *)error
+{
+    if (![self validateResponse:(NSHTTPURLResponse *)response data:data error:error]) {
+        if (!error || AFErrorOrUnderlyingErrorHasCodeInDomain(*error, NSURLErrorCannotDecodeContentData, AFURLResponseSerializationErrorDomain)) {
+            return nil;
+        }
+    }
+
+#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED)
+    if (self.automaticallyInflatesResponseImage) {
+        return AFInflatedImageFromResponseWithDataAtScale((NSHTTPURLResponse *)response, data, self.imageScale);
+    } else {
+        return AFImageWithDataAtScale(data, self.imageScale);
+    }
+#elif defined(__MAC_OS_X_VERSION_MIN_REQUIRED)
+    // Ensure that the image is set to it's correct pixel width and height
+    NSBitmapImageRep *bitimage = [[NSBitmapImageRep alloc] initWithData:data];
+    NSImage *image = [[NSImage alloc] initWithSize:NSMakeSize([bitimage pixelsWide], [bitimage pixelsHigh])];
+    [image addRepresentation:bitimage];
+
+    return image;
+#endif
+
+    return nil;
+}
+
+#pragma mark - NSSecureCoding
+
+- (id)initWithCoder:(NSCoder *)decoder {
+    self = [super initWithCoder:decoder];
+    if (!self) {
+        return nil;
+    }
+
+#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED)
+    NSNumber *imageScale = [decoder decodeObjectOfClass:[NSNumber class] forKey:NSStringFromSelector(@selector(imageScale))];
+#if CGFLOAT_IS_DOUBLE
+    self.imageScale = [imageScale doubleValue];
+#else
+    self.imageScale = [imageScale floatValue];
+#endif
+
+    self.automaticallyInflatesResponseImage = [decoder decodeBoolForKey:NSStringFromSelector(@selector(automaticallyInflatesResponseImage))];
+#endif
+
+    return self;
+}
+
+- (void)encodeWithCoder:(NSCoder *)coder {
+    [super encodeWithCoder:coder];
+
+#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED)
+    [coder encodeObject:@(self.imageScale) forKey:NSStringFromSelector(@selector(imageScale))];
+    [coder encodeBool:self.automaticallyInflatesResponseImage forKey:NSStringFromSelector(@selector(automaticallyInflatesResponseImage))];
+#endif
+}
+
+#pragma mark - NSCopying
+
+- (id)copyWithZone:(NSZone *)zone {
+    AFImageResponseSerializer *serializer = [[[self class] allocWithZone:zone] init];
+
+#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED)
+    serializer.imageScale = self.imageScale;
+    serializer.automaticallyInflatesResponseImage = self.automaticallyInflatesResponseImage;
+#endif
+
+    return serializer;
+}
+
+@end
+
+#pragma mark -
+
+@interface AFCompoundResponseSerializer ()
+@property (readwrite, nonatomic, copy) NSArray *responseSerializers;
+@end
+
+@implementation AFCompoundResponseSerializer
+
++ (instancetype)compoundSerializerWithResponseSerializers:(NSArray *)responseSerializers {
+    AFCompoundResponseSerializer *serializer = [[self alloc] init];
+    serializer.responseSerializers = responseSerializers;
+
+    return serializer;
+}
+
+#pragma mark - AFURLResponseSerialization
+
+- (id)responseObjectForResponse:(NSURLResponse *)response
+                           data:(NSData *)data
+                          error:(NSError *__autoreleasing *)error
+{
+    for (id <AFURLResponseSerialization> serializer in self.responseSerializers) {
+        if (![serializer isKindOfClass:[AFHTTPResponseSerializer class]]) {
+            continue;
+        }
+
+        NSError *serializerError = nil;
+        id responseObject = [serializer responseObjectForResponse:response data:data error:&serializerError];
+        if (responseObject) {
+            if (error) {
+                *error = AFErrorWithUnderlyingError(serializerError, *error);
+            }
+
+            return responseObject;
+        }
+    }
+
+    return [super responseObjectForResponse:response data:data error:error];
+}
+
+#pragma mark - NSSecureCoding
+
+- (id)initWithCoder:(NSCoder *)decoder {
+    self = [super initWithCoder:decoder];
+    if (!self) {
+        return nil;
+    }
+
+    self.responseSerializers = [decoder decodeObjectOfClass:[NSArray class] forKey:NSStringFromSelector(@selector(responseSerializers))];
+
+    return self;
+}
+
+- (void)encodeWithCoder:(NSCoder *)coder {
+    [super encodeWithCoder:coder];
+
+    [coder encodeObject:self.responseSerializers forKey:NSStringFromSelector(@selector(responseSerializers))];
+}
+
+#pragma mark - NSCopying
+
+- (id)copyWithZone:(NSZone *)zone {
+    AFCompoundResponseSerializer *serializer = [[[self class] allocWithZone:zone] init];
+    serializer.responseSerializers = self.responseSerializers;
+
+    return serializer;
+}
+
+@end

File diff suppressed because it is too large
+ 554 - 0
sdk/Objective-C/PhalApiClient/AFNPhalApiClient/Vendor/AFNetworking-2.6.1/AFURLSessionManager.h


File diff suppressed because it is too large
+ 1171 - 0
sdk/Objective-C/PhalApiClient/AFNPhalApiClient/Vendor/AFNetworking-2.6.1/AFURLSessionManager.m


+ 131 - 0
sdk/Objective-C/PhalApiClient/PhalApiClient.h

@@ -0,0 +1,131 @@
+//
+//  PhalApiClient.h
+//  PhalApiClientDemo
+//
+//  Created by Aevit on 15/10/17.
+//  Copyright © 2015年 Aevit. All rights reserved.
+//
+
+#import <Foundation/Foundation.h>
+#import "PhalApiClientFilter.h"
+
+#if 1
+#   define PALog(x, ...) NSLog(x, ## __VA_ARGS__);
+#else
+#   define PALog(x, ...)
+#endif
+
+typedef void(^HttpCompleteBlock)(id resultObject);
+typedef void(^HttpFailureBlock)(id error);
+typedef void(^FormDataBlock)(id formData);
+
+@interface PhalApiClient : NSObject
+
+
+@property (nonatomic, copy) NSString *host;
+@property (nonatomic, copy) NSString *service;
+@property (nonatomic, strong) NSMutableDictionary *params;
+@property (nonatomic, assign) float timeout;
+
+@property (nonatomic, strong) PhalApiClientFilter *filter;
+
+
+#pragma mark - generate a client
+/**
+ *  生成单例
+ *
+ *  @return 单例PhalApiClient
+ */
++ (PhalApiClient*)sharedClient;
+
+/**
+ *  生成非单例
+ *
+ *  @return 非单例PhalApiClient
+ */
++ (PhalApiClient*)create;
+
+#pragma mark - configure url and params
+/**
+ *  重复查询时须重置请求状态,包括接口服务名称、接口参数和超时时间
+ *
+ *  @return PhalApiClient实例
+ */
+- (PhalApiClient*)reset;
+
+/**
+ *  设置接口域名
+ *  如果整个客户端只有一个接口host,可以在"commonInit"方法设置好host,这样外部就可以不用调用withHost方法了
+ *
+ *  @param host 域名
+ *
+ *  @return PhalApiClient实例
+ */
+- (PhalApiClient*)withHost:(NSString*)host;
+
+/**
+ *  设置将在调用的接口服务名称,如:Default.Index
+ *
+ *  @param service 接口服务名称
+ *
+ *  @return PhalApiClient实例
+ */
+- (PhalApiClient*)withService:(NSString*)service;
+
+/**
+ *  设置接口参数,此方法是唯一一个可以多次调用并累加参数的操作
+ *
+ *  @param params 参数
+ *
+ *  @return PhalApiClient实例
+ */
+- (PhalApiClient*)withParams:(NSDictionary*)params;
+
+/**
+ *  设置过滤器,与服务器的DI().filter对应
+ *
+ *  @return PhalApiClient实例
+ */
+- (PhalApiClient*)withFilter:(PhalApiClientFilter*)filter;
+
+/**
+ *  设置超时时间,单位毫秒
+ *
+ *  @param timeout 超时时间,单位秒
+ *
+ *  @return PhalApiClient实例
+ */
+- (PhalApiClient*)withTimeout:(float)timeout;
+
+#pragma mark - request
+/**
+ *  发起接口请求(POST请求)
+ *
+ *  @param completeBlock 请求成功的回调
+ *  @param failureBlock  请求失败的回调
+ *
+ *  @return 请求实例
+ */
+- (id)request:(HttpCompleteBlock)completeBlock failureBlock:(HttpFailureBlock)failureBlock;
+
+/**
+ *  发起接口请求(提交表单)
+ *
+ *  @param formDataBlock 表单内容
+ *  @param completeBlock 请求成功的回调
+ *  @param failureBlock  请求失败的回调
+ *
+ *  @return 请求实例
+ */
+- (id)requestWithFormDataBlock:(FormDataBlock)formDataBlock completeBlock:(HttpCompleteBlock)completeBlock failureBlock:(HttpFailureBlock)failureBlock;
+
+
+#pragma mark - utils
+/**
+ *  以get形式打印整个url,方便服务端开发人员调试
+ *
+ *  @return 整个url
+ */
+- (NSString*)printTotalUrlStr;
+
+@end

+ 226 - 0
sdk/Objective-C/PhalApiClient/PhalApiClient.m

@@ -0,0 +1,226 @@
+//
+//  PhalApiClient.m
+//  PhalApiClientDemo
+//
+//  Created by Aevit on 15/10/17.
+//  Copyright © 2015年 Aevit. All rights reserved.
+//
+
+#import "PhalApiClient.h"
+
+@interface PhalApiClient()
+
+@end
+
+@implementation PhalApiClient
+
+- (instancetype)init {
+    self = [super init];
+    if (self) {
+        [self commonInit];
+    }
+    return self;
+}
+
+- (void)commonInit {
+    [self reset];
+    /**
+     *  如果整个客户端只有一个接口host,可以在reset后设置好host,这样外部就可以不用调用withHost方法了
+     *  e.g. [self withHost:@"http://api.your_host.com/project_name/"];
+     */
+}
+
+#pragma mark - generate a client
+/**
+ *  生成单例
+ *
+ *  @return 单例PhalApiClient
+ */
++ (PhalApiClient*)sharedClient {
+    static PhalApiClient *_sharedClient;
+    static dispatch_once_t onceToken;
+    dispatch_once(&onceToken, ^{
+        _sharedClient = [[PhalApiClient alloc] init];
+    });
+    return _sharedClient;
+}
+
+/**
+ *  生成非单例
+ *
+ *  @return 非单例PhalApiClient
+ */
++ (PhalApiClient*)create {
+    PhalApiClient *client = [[PhalApiClient alloc] init];
+    return client;
+}
+
+#pragma mark - configure url and params
+/**
+ *  重复查询时须重置请求状态,包括接口服务名称、接口参数和超时时间
+ *
+ *  @return PhalApiClient实例
+ */
+- (PhalApiClient*)reset {
+    self.host = nil;
+    self.service = nil;
+    self.params = nil;
+    self.timeout = 0;
+    return self;
+}
+
+/**
+ *  设置接口域名
+ *  如果整个客户端只有一个接口host,可以在"commonInit"方法设置好host,这样外部就可以不用调用withHost方法了
+ *
+ *  @param host 域名
+ *
+ *  @return PhalApiClient实例
+ */
+- (PhalApiClient*)withHost:(NSString*)host {
+    self.host = nil;
+    self.host = host;
+    return self;
+}
+
+- (NSString *)host {
+    if ([[_host substringFromIndex:(_host.length - 1)] isEqualToString:@"/"]) {
+        return _host;
+    }
+    _host = [NSString stringWithFormat:@"%@/", _host];
+    return _host;
+}
+
+/**
+ *  设置将在调用的接口服务名称,如:Default.Index
+ *
+ *  @param service 接口服务名称
+ *
+ *  @return PhalApiClient实例
+ */
+- (PhalApiClient*)withService:(NSString*)service {
+    self.service = nil;
+    self.service = service;
+    return self;
+}
+
+/**
+ *  设置接口参数,此方法是唯一一个可以多次调用并累加参数的操作
+ *
+ *  @param params 参数
+ *
+ *  @return PhalApiClient实例
+ */
+- (PhalApiClient*)withParams:(NSDictionary*)params {
+    self.params = nil;
+    if (!params) {
+        return self;
+    }
+    self.params = [NSMutableDictionary dictionaryWithDictionary:params];
+    return self;
+}
+
+/**
+ *  设置过滤器,与服务器的DI().filter对应
+ *
+ *  @return PhalApiClient实例
+ */
+- (PhalApiClient*)withFilter:(PhalApiClientFilter*)filter {
+    self.filter = filter;
+    return self;
+}
+
+/**
+ *  设置超时时间,单位毫秒
+ *
+ *  @param timeout 超时时间,单位秒
+ *
+ *  @return PhalApiClient实例
+ */
+- (PhalApiClient*)withTimeout:(float)timeout {
+    self.timeout = timeout;
+    return self;
+}
+
+- (float)timeout {
+    // 默认60s超时
+    return (_timeout > 0 ? _timeout : 60);
+}
+
+#pragma mark - request
+/**
+ *  发起接口请求(POST请求)
+ *
+ *  @param completeBlock 请求成功的回调
+ *  @param failureBlock  请求失败的回调
+ *
+ *  @return 请求实例
+ */
+- (id)request:(HttpCompleteBlock)completeBlock failureBlock:(HttpFailureBlock)failureBlock {
+    /**
+     *  请求方式,可以使用系统的NSURLSession,或第三方的网络请求库等
+     *  这里我们使用第三方的AFNetworking,进行二次封装(https://github.com/AFNetworking/AFNetworking)
+     *  新建子类(AFNPhalApiClient,继承自PhalApiClient),重写此request方法
+     *  如需使用其他网络请求方式(如NSURLSession),请继承自PhalApiClient,重写此request即可,可参考AFNPhalApiClient
+     */
+    return [self requestWithFormDataBlock:nil completeBlock:completeBlock failureBlock:failureBlock];
+}
+
+/**
+ *  发起接口请求(提交表单)
+ *
+ *  @param formDataBlock 表单内容
+ *  @param completeBlock 请求成功的回调
+ *  @param failureBlock  请求失败的回调
+ *
+ *  @return 请求实例
+ */
+- (id)requestWithFormDataBlock:(FormDataBlock)formDataBlock completeBlock:(HttpCompleteBlock)completeBlock failureBlock:(HttpFailureBlock)failureBlock {
+    /**
+     *  请求方式,可以使用系统的NSURLSession,第三方的网络请求库等
+     *  这里我们使用第三方的AFNetworking,进行二次封装(https://github.com/AFNetworking/AFNetworking)
+     *  新建子类(AFNPhalApiClient,继承自PhalApiClient),重写此request方法
+     *  如需使用其他网络请求方式(如NSURLSession),请继承自PhalApiClient,重写此request即可,可参考AFNPhalApiClient
+     */
+    return nil;
+}
+
+
+#pragma mark - utils
+/**
+ *  以get形式打印整个url,方便服务端开发人员调试
+ *
+ *  @return 整个url
+ */
+- (NSString*)printTotalUrlStr {
+    
+    if (!_host || _host.length <= 0) {
+        return @"empty host";
+    }
+    
+    NSMutableString *finalStr = [NSMutableString stringWithString:_host];
+    [finalStr appendFormat:@"?service=%@&", _service];
+    
+    if (_params) {
+        for (NSString *key in [_params allKeys]) {
+            [finalStr appendString:key];
+            [finalStr appendString:@"="];
+            id value = [_params objectForKey:key];
+            NSString *valueStr = @"";
+            if ([value isKindOfClass:[NSNumber class]]) {
+                valueStr = [value stringValue];
+            } else if ([value isKindOfClass:[NSString class]]) {
+                valueStr = value;
+            } else {
+                PALog(@"什么鬼?!");
+            }
+            [finalStr appendString:valueStr];
+            [finalStr appendString:@"&"];
+        }
+    }
+    return [finalStr substringWithRange:NSMakeRange(0, finalStr.length - 1)];
+}
+
+@end
+
+

+ 22 - 0
sdk/Objective-C/PhalApiClient/PhalApiClientFilter.h

@@ -0,0 +1,22 @@
+//
+//  PhalApiClientFilter.h
+//  PhalApiClientDemo
+//
+//  Created by Aevit on 15/10/18.
+//  Copyright © 2015年 Aevit. All rights reserved.
+//
+
+#import <Foundation/Foundation.h>
+
+@interface PhalApiClientFilter : NSObject
+
+/**
+ *  接口过滤器
+ *  可用于接口签名生成
+ *
+ *  @param service 接口服务名称
+ *  @param params  接口参数,注意是mutable变量,可以直接修改
+ */
+- (void)filter:(NSString*)service params:(NSMutableDictionary*)params;
+
+@end

+ 24 - 0
sdk/Objective-C/PhalApiClient/PhalApiClientFilter.m

@@ -0,0 +1,24 @@
+//
+//  PhalApiClientFilter.m
+//  PhalApiClientDemo
+//
+//  Created by Aevit on 15/10/18.
+//  Copyright © 2015年 Aevit. All rights reserved.
+//
+
+#import "PhalApiClientFilter.h"
+
+@implementation PhalApiClientFilter
+
+/**
+ *  接口过滤器
+ *  可用于接口签名生成
+ *
+ *  @param service 接口服务名称
+ *  @param params  接口参数,注意是mutable变量,可以直接修改
+ */
+- (void)filter:(NSString*)service params:(NSMutableDictionary*)params {
+    // 在此对接口进行过滤
+}
+
+@end

+ 97 - 0
sdk/Objective-C/PhalApiClient/README.md

@@ -0,0 +1,97 @@
+
+```
+该文档由 @Aevit 提供
+```
+## 使用说明
+将框架目录下的 ./SDK/Objective-C/ 目录中的全部代码拷贝到项目里面即可使用。如:  
+![](http://aevit.qiniudn.com/PhalApiClient-SDK-files.jpeg)  
+
+```
+请求方式,可以使用系统的NSURLSession,或第三方的网络请求库等
+这里我们使用第三方的AFNetworking,进行二次封装(https://github.com/AFNetworking/AFNetworking)
+如需使用其他网络请求方式(如官方的NSURLSession),请继承自PhalApiClient,重写request方法即可,可参考AFNPhalApiClient
+```  
+
+## 代码示例
+如下是使用的代码场景片段。  
+  
+首先,我们需要导入SDK包:
+```Objective-C
+#import "AFNPhalApiClient.h"
+```
+  
+然后,准备按以下方法实现接口请求即可:  
+```Objective-C
+// 待POST的参数
+NSDictionary *params = @{@"demo_key_1": @"your_key", @"demo_key_2": @"1.0"};
+
+// 使用AFNPhalApiClient
+[[[[[AFNPhalApiClient sharedClient] withHost:@"http://api1.aevit.xyz/"] withService:@"Default.Index"] withParams:params] requestWithFormDataBlock:^(id formData) {
+	// 如需上传文件(图片等),请参照如下格式
+    [formData appendPartWithFileData:UIImageJPEGRepresentation([UIImage imageNamed:@"head.JPG"], 1) name:@"file" fileName:@"image.jpg" mimeType:@"image/jpeg"];
+} completeBlock:^(id resultObject) {
+    PALog(@"resultObject: %@", resultObject);
+} failureBlock:^(NSError *error) {
+    PALog(@"error: %@", error);
+}];
+
+// 打印url查看
+PALog(@"total url: %@", [[AFNPhalApiClient sharedClient] printTotalUrlStr]);
+```
+
+
+## 运行效果
+运行后,查询log,可以看到:  
+![](http://aevit.qiniudn.com/PhalApiClient-SDK-demo-result.jpg)  
+
+  
+可以注意到,调用完成后,会有接口请求的链接和返回的结果,如:  
+```
+2015-10-19 18:28:01.503 PhalApiClientDemo[23161:1199740] total url: http://api1.aevit.xyz/?service=Default.Index&amp;demo_key_2=1.0&amp;demo_key_1=your_key
+
+2015-10-19 18:28:01.536 PhalApiClientDemo[23161:1199740] resultObject: {
+    data =     {
+        content = "PHPer\U60a8\U597d\Uff0c\U6b22\U8fce\U4f7f\U7528PhalApi\Uff01";
+        time = 1445250481;
+        title = "Hello World!";
+        version = "1.2.1";
+    };
+    msg = "";
+    ret = 200;
+}
+```
+
+## 扩展你的过滤器和结果解析器
+### (1)扩展过滤器
+当服务端接口需要接口签名验证,或者接口参数加密传送,或者压缩传送时,可以实现此过滤器,以便和服务端操持一致。  
+  
+当需要扩展时,分两步。首先,需要实现过滤器接口:  
+```Objective-C
+
+@interface MyFilter : PhalApiClientFilter
+@end
+
+@implementation PhalApiClientFilter
+/**
+ *  接口过滤器
+ *  可用于接口签名生成
+ *
+ *  @param service 接口服务名称
+ *  @param params  接口参数,注意是mutable变量,可以直接修改
+ */
+- (void)filter:(NSString*)service params:(NSMutableDictionary*)params {
+    // 在此对接口进行过滤
+}
+@end
+```
+然后设置过滤器:
+```Objective-C
+[[[[[[AFNPhalApiClient sharedClient] withHost:@"http://api1.aevit.xyz/"] withService:@"Default.Index"] withParams:params]
+      withFilter:[MyFilter new]] // filter
+     requestWithFormDataBlock:^(id formData) {
+    } completeBlock:^(id resultObject) {
+    } failureBlock:^(NSError *error) {
+}];
+```
+### (2)扩展结果解析器
+当返回的接口结果不是JSON格式时,如XML,请上google搜索“AFNetworking XML”相关资料即可。  

File diff suppressed because it is too large
+ 112 - 0
sdk/Objective-C/XSHttpTool/AFNetworking/AFDownloadRequestOperation/AFDownloadRequestOperation.h


+ 327 - 0
sdk/Objective-C/XSHttpTool/AFNetworking/AFDownloadRequestOperation/AFDownloadRequestOperation.m

@@ -0,0 +1,327 @@
+// AFDownloadRequestOperation.m
+//
+// Copyright (c) 2012 Peter Steinberger (http://petersteinberger.com)
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+#import "AFDownloadRequestOperation.h"
+#import "AFURLConnectionOperation.h"
+#import <CommonCrypto/CommonDigest.h>
+#include <fcntl.h>
+#include <unistd.h>
+
+#if !__has_feature(objc_arc)
+#error "Compile this file with ARC"
+#endif
+
+@interface AFURLConnectionOperation (AFInternal)
+@property (nonatomic, strong) NSURLRequest *request;
+@property (readonly, nonatomic, assign) long long totalBytesRead;
+@end
+
+typedef void (^AFURLConnectionProgressiveOperationProgressBlock)(AFDownloadRequestOperation *operation, NSInteger bytes, long long totalBytes, long long totalBytesExpected, long long totalBytesReadForFile, long long totalBytesExpectedToReadForFile);
+
+@interface AFDownloadRequestOperation() {
+    NSError *_fileError;
+    id _responseObject;
+}
+@property (nonatomic, strong) NSString *tempPath;
+@property (assign) long long totalContentLength;
+@property (nonatomic, assign) long long totalBytesReadPerDownload;
+@property (assign) long long offsetContentLength;
+@property (nonatomic, copy) AFURLConnectionProgressiveOperationProgressBlock progressiveDownloadProgress;
+@end
+
+@implementation AFDownloadRequestOperation
+
+#pragma mark - NSObject
+
+- (void)dealloc {
+    if (_progressiveDownloadCallbackQueue) {
+#if !OS_OBJECT_USE_OBJC
+        dispatch_release(_progressiveDownloadCallbackQueue);
+#endif
+        _progressiveDownloadCallbackQueue = NULL;
+    }
+}
+
+- (id)initWithRequest:(NSURLRequest *)urlRequest targetPath:(NSString *)targetPath shouldResume:(BOOL)shouldResume {
+    if ((self = [super initWithRequest:urlRequest])) {
+        NSParameterAssert(targetPath != nil && urlRequest != nil);
+        _shouldResume = shouldResume;
+
+        // Ee assume that at least the directory has to exist on the targetPath
+        BOOL isDirectory;
+        if(![[NSFileManager defaultManager] fileExistsAtPath:targetPath isDirectory:&isDirectory]) {
+            isDirectory = NO;
+        }
+        // \If targetPath is a directory, use the file name we got from the urlRequest.
+        if (isDirectory) {
+            NSString *fileName = [urlRequest.URL lastPathComponent];
+            _targetPath = [NSString pathWithComponents:@[targetPath, fileName]];
+        }else {
+            _targetPath = targetPath;
+        }
+
+        // Download is saved into a temorary file and renamed upon completion.
+        NSString *tempPath = [self tempPath];
+
+        // Do we need to resume the file?
+        BOOL isResuming = [self updateByteStartRangeForRequest];
+        
+        // Try to create/open a file at the target location
+        if (!isResuming) {
+            int fileDescriptor = open([tempPath UTF8String], O_CREAT | O_EXCL | O_RDWR, 0666);
+            if (fileDescriptor > 0) close(fileDescriptor);
+        }
+
+        self.outputStream = [NSOutputStream outputStreamToFileAtPath:tempPath append:isResuming];
+        // If the output stream can't be created, instantly destroy the object.
+        if (!self.outputStream) return nil;
+        
+        // Give the object its default completionBlock.
+        [self setCompletionBlockWithSuccess:nil failure:nil];
+    }
+    return self;
+}
+
+// updates the current request to set the correct start-byte-range.
+- (BOOL)updateByteStartRangeForRequest {
+    BOOL isResuming = NO;
+    if (self.shouldResume) {
+        unsigned long long downloadedBytes = [self fileSizeForPath:[self tempPath]];
+        if (downloadedBytes > 1) {
+
+            // If the the current download-request's data has been fully downloaded, but other causes of the operation failed (such as the inability of the incomplete temporary file copied to the target location), next, retry this download-request, the starting-value (equal to the incomplete temporary file size) will lead to an HTTP 416 out of range error, unless we subtract one byte here. (We don't know the final size before sending the request)
+            downloadedBytes--;
+
+            NSMutableURLRequest *mutableURLRequest = [self.request mutableCopy];
+            NSString *requestRange = [NSString stringWithFormat:@"bytes=%llu-", downloadedBytes];
+            [mutableURLRequest setValue:requestRange forHTTPHeaderField:@"Range"];
+            self.request = mutableURLRequest;
+            isResuming = YES;
+        }
+    }
+    return isResuming;
+}
+
+#pragma mark - Public
+
+- (BOOL)deleteTempFileWithError:(NSError *__autoreleasing*)error {
+    NSFileManager *fileManager = [NSFileManager new];
+    BOOL success = YES;
+    @synchronized(self) {
+        NSString *tempPath = [self tempPath];
+        if ([fileManager fileExistsAtPath:tempPath]) {
+            success = [fileManager removeItemAtPath:[self tempPath] error:error];
+        }
+    }
+    return success;
+}
+
+- (NSString *)tempPath {
+    NSString *tempPath = nil;
+    if (self.targetPath) {
+        NSString *md5URLString = [[self class] md5StringForString:self.targetPath];
+        tempPath = [[[self class] cacheFolder] stringByAppendingPathComponent:md5URLString];
+    }
+    return tempPath;
+}
+
+
+- (void)setProgressiveDownloadProgressBlock:(void (^)(AFDownloadRequestOperation *operation, NSInteger bytesRead, long long totalBytesRead, long long totalBytesExpected, long long totalBytesReadForFile, long long totalBytesExpectedToReadForFile))block {
+    self.progressiveDownloadProgress = block;
+}
+
+- (void)setProgressiveDownloadCallbackQueue:(dispatch_queue_t)progressiveDownloadCallbackQueue {
+    if (progressiveDownloadCallbackQueue != _progressiveDownloadCallbackQueue) {
+        if (_progressiveDownloadCallbackQueue) {
+#if !OS_OBJECT_USE_OBJC
+            dispatch_release(_progressiveDownloadCallbackQueue);
+#endif
+            _progressiveDownloadCallbackQueue = NULL;
+        }
+        
+        if (progressiveDownloadCallbackQueue) {
+#if !OS_OBJECT_USE_OBJC
+            dispatch_retain(progressiveDownloadCallbackQueue);
+#endif
+            _progressiveDownloadCallbackQueue = progressiveDownloadCallbackQueue;
+        }
+    }
+}
+
+
+#pragma mark - Private
+
+- (unsigned long long)fileSizeForPath:(NSString *)path {
+    signed long long fileSize = 0;
+    NSFileManager *fileManager = [NSFileManager new]; // default is not thread safe
+    if ([fileManager fileExistsAtPath:path]) {
+        NSError *error = nil;
+        NSDictionary *fileDict = [fileManager attributesOfItemAtPath:path error:&error];
+        if (!error && fileDict) {
+            fileSize = [fileDict fileSize];
+        }
+    }
+    return fileSize;
+}
+
+#pragma mark - AFHTTPRequestOperation
+
++ (NSIndexSet *)acceptableStatusCodes {
+	NSMutableIndexSet *acceptableStatusCodes = [NSMutableIndexSet indexSetWithIndexesInRange:NSMakeRange(200, 100)];
+	[acceptableStatusCodes addIndex:416];
+	
+	return acceptableStatusCodes;
+}
+
+#pragma mark - AFURLRequestOperation
+
+- (void)pause {
+    [super pause];
+    [self updateByteStartRangeForRequest];
+}
+
+- (id)responseObject {
+    @synchronized(self) {
+        if (!_responseObject && [self isFinished] && !self.error) {
+            NSError *localError = nil;
+            if ([self isCancelled]) {
+                // should we clean up? most likely we don't.
+                if (self.isDeletingTempFileOnCancel) {
+                    [self deleteTempFileWithError:&localError];
+                    if (localError) {
+                        _fileError = localError;
+                    }
+                }
+                
+                // loss of network connections = error set, but not cancel
+            }else if(!self.error) {
+                // move file to final position and capture error
+                NSFileManager *fileManager = [NSFileManager new];
+                if (self.shouldOverwrite) {
+                    [fileManager removeItemAtPath:_targetPath error:NULL]; // avoid "File exists" error
+                }
+                [fileManager moveItemAtPath:[self tempPath] toPath:_targetPath error:&localError];
+                if (localError) {
+                    _fileError = localError;
+                } else {
+                    _responseObject = _targetPath;
+                }
+            }
+        }
+    }
+    
+    return _responseObject;
+}
+
+- (NSError *)error {
+    return _fileError ?: [super error];
+}
+
+#pragma mark - NSURLConnectionDelegate
+
+- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
+    [super connection:connection didReceiveResponse:response];
+
+    // check if we have the correct response
+    NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
+    if (![httpResponse isKindOfClass:[NSHTTPURLResponse class]]) return;
+
+    // check for valid response to resume the download if possible
+    long long totalContentLength = self.response.expectedContentLength;
+    long long fileOffset = 0;
+    if(httpResponse.statusCode == 206) {
+        NSString *contentRange = [httpResponse.allHeaderFields valueForKey:@"Content-Range"];
+        if ([contentRange hasPrefix:@"bytes"]) {
+            NSArray *bytes = [contentRange componentsSeparatedByCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@" -/"]];
+            if ([bytes count] == 4) {
+                fileOffset = [bytes[1] longLongValue];
+                totalContentLength = [bytes[3] longLongValue]; // if this is *, it's converted to 0
+            }
+        }
+    }
+
+    self.totalBytesReadPerDownload = 0;
+    self.offsetContentLength = MAX(fileOffset, 0);
+    self.totalContentLength = totalContentLength;
+    
+    // Truncate cache file to offset provided by server.
+    // Using self.outputStream setProperty:@(_offsetContentLength) forKey:NSStreamFileCurrentOffsetKey]; will not work (in contrary to the documentation)
+    NSString *tempPath = [self tempPath];
+    if ([self fileSizeForPath:tempPath] != _offsetContentLength) {
+        [self.outputStream close];
+        BOOL isResuming = _offsetContentLength > 0;
+        if (isResuming) {
+            NSFileHandle *file = [NSFileHandle fileHandleForWritingAtPath:tempPath];
+            [file truncateFileAtOffset:_offsetContentLength];
+            [file closeFile];
+        }
+        self.outputStream = [NSOutputStream outputStreamToFileAtPath:tempPath append:isResuming];
+        [self.outputStream open];
+    }
+}
+
+- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data  {
+    if (![self.responseSerializer validateResponse:self.response data:nil error:NULL])
+        return; // don't write to output stream if any error occurs
+
+    [super connection:connection didReceiveData:data];
+
+    // track custom bytes read because totalBytesRead persists between pause/resume.
+    self.totalBytesReadPerDownload += [data length];
+
+    if (self.progressiveDownloadProgress) {
+        dispatch_async(self.progressiveDownloadCallbackQueue ?: dispatch_get_main_queue(), ^{
+            self.progressiveDownloadProgress(self,(NSInteger)[data length], self.totalBytesRead, self.response.expectedContentLength,self.totalBytesReadPerDownload + self.offsetContentLength, self.totalContentLength);
+        });
+    }
+}
+
+#pragma mark - Static
+
++ (NSString *)cacheFolder {
+    NSFileManager *filemgr = [NSFileManager new];
+    static NSString *cacheFolder;
+
+    if (!cacheFolder) {
+        NSString *cacheDir = NSTemporaryDirectory();
+        cacheFolder = [cacheDir stringByAppendingPathComponent:kAFNetworkingIncompleteDownloadFolderName];
+    }
+
+    // ensure all cache directories are there
+    NSError *error = nil;
+    if(![filemgr createDirectoryAtPath:cacheFolder withIntermediateDirectories:YES attributes:nil error:&error]) {
+        NSLog(@"Failed to create cache directory at %@", cacheFolder);
+        cacheFolder = nil;
+    }
+    return cacheFolder;
+}
+
+// calculates the MD5 hash of a key
++ (NSString *)md5StringForString:(NSString *)string {
+    const char *str = [string UTF8String];
+    unsigned char r[CC_MD5_DIGEST_LENGTH];
+    CC_MD5(str, (uint32_t)strlen(str), r);
+    return [NSString stringWithFormat:@"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
+            r[0], r[1], r[2], r[3], r[4], r[5], r[6], r[7], r[8], r[9], r[10], r[11], r[12], r[13], r[14], r[15]];
+}
+
+@end

File diff suppressed because it is too large
+ 66 - 0
sdk/Objective-C/XSHttpTool/AFNetworking/AFHTTPRequestOperation.h


+ 206 - 0
sdk/Objective-C/XSHttpTool/AFNetworking/AFHTTPRequestOperation.m

@@ -0,0 +1,206 @@
+// AFHTTPRequestOperation.m
+// Copyright (c) 2011–2015 Alamofire Software Foundation (http://alamofire.org/)
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+#import "AFHTTPRequestOperation.h"
+
+static dispatch_queue_t http_request_operation_processing_queue() {
+    static dispatch_queue_t af_http_request_operation_processing_queue;
+    static dispatch_once_t onceToken;
+    dispatch_once(&onceToken, ^{
+        af_http_request_operation_processing_queue = dispatch_queue_create("com.alamofire.networking.http-request.processing", DISPATCH_QUEUE_CONCURRENT);
+    });
+
+    return af_http_request_operation_processing_queue;
+}
+
+static dispatch_group_t http_request_operation_completion_group() {
+    static dispatch_group_t af_http_request_operation_completion_group;
+    static dispatch_once_t onceToken;
+    dispatch_once(&onceToken, ^{
+        af_http_request_operation_completion_group = dispatch_group_create();
+    });
+
+    return af_http_request_operation_completion_group;
+}
+
+#pragma mark -
+
+@interface AFURLConnectionOperation ()
+@property (readwrite, nonatomic, strong) NSURLRequest *request;
+@property (readwrite, nonatomic, strong) NSURLResponse *response;
+@end
+
+@interface AFHTTPRequestOperation ()
+@property (readwrite, nonatomic, strong) NSHTTPURLResponse *response;
+@property (readwrite, nonatomic, strong) id responseObject;
+@property (readwrite, nonatomic, strong) NSError *responseSerializationError;
+@property (readwrite, nonatomic, strong) NSRecursiveLock *lock;
+@end
+
+@implementation AFHTTPRequestOperation
+@dynamic response;
+@dynamic lock;
+
+- (instancetype)initWithRequest:(NSURLRequest *)urlRequest {
+    self = [super initWithRequest:urlRequest];
+    if (!self) {
+        return nil;
+    }
+
+    self.responseSerializer = [AFHTTPResponseSerializer serializer];
+
+    return self;
+}
+
+- (void)setResponseSerializer:(AFHTTPResponseSerializer <AFURLResponseSerialization> *)responseSerializer {
+    NSParameterAssert(responseSerializer);
+
+    [self.lock lock];
+    _responseSerializer = responseSerializer;
+    self.responseObject = nil;
+    self.responseSerializationError = nil;
+    [self.lock unlock];
+}
+
+- (id)responseObject {
+    [self.lock lock];
+    if (!_responseObject && [self isFinished] && !self.error) {
+        NSError *error = nil;
+        self.responseObject = [self.responseSerializer responseObjectForResponse:self.response data:self.responseData error:&error];
+        if (error) {
+            self.responseSerializationError = error;
+        }
+    }
+    [self.lock unlock];
+
+    return _responseObject;
+}
+
+- (NSError *)error {
+    if (_responseSerializationError) {
+        return _responseSerializationError;
+    } else {
+        return [super error];
+    }
+}
+
+#pragma mark - AFHTTPRequestOperation
+
+- (void)setCompletionBlockWithSuccess:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
+                              failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure
+{
+    // completionBlock is manually nilled out in AFURLConnectionOperation to break the retain cycle.
+#pragma clang diagnostic push
+#pragma clang diagnostic ignored "-Warc-retain-cycles"
+#pragma clang diagnostic ignored "-Wgnu"
+    self.completionBlock = ^{
+        if (self.completionGroup) {
+            dispatch_group_enter(self.completionGroup);
+        }
+
+        dispatch_async(http_request_operation_processing_queue(), ^{
+            if (self.error) {
+                if (failure) {
+                    dispatch_group_async(self.completionGroup ?: http_request_operation_completion_group(), self.completionQueue ?: dispatch_get_main_queue(), ^{
+                        failure(self, self.error);
+                    });
+                }
+            } else {
+                id responseObject = self.responseObject;
+                if (self.error) {
+                    if (failure) {
+                        dispatch_group_async(self.completionGroup ?: http_request_operation_completion_group(), self.completionQueue ?: dispatch_get_main_queue(), ^{
+                            failure(self, self.error);
+                        });
+                    }
+                } else {
+                    if (success) {
+                        dispatch_group_async(self.completionGroup ?: http_request_operation_completion_group(), self.completionQueue ?: dispatch_get_main_queue(), ^{
+                            success(self, responseObject);
+                        });
+                    }
+                }
+            }
+
+            if (self.completionGroup) {
+                dispatch_group_leave(self.completionGroup);
+            }
+        });
+    };
+#pragma clang diagnostic pop
+}
+
+#pragma mark - AFURLRequestOperation
+
+- (void)pause {
+    [super pause];
+
+    u_int64_t offset = 0;
+    if ([self.outputStream propertyForKey:NSStreamFileCurrentOffsetKey]) {
+        offset = [(NSNumber *)[self.outputStream propertyForKey:NSStreamFileCurrentOffsetKey] unsignedLongLongValue];
+    } else {
+        offset = [(NSData *)[self.outputStream propertyForKey:NSStreamDataWrittenToMemoryStreamKey] length];
+    }
+
+    NSMutableURLRequest *mutableURLRequest = [self.request mutableCopy];
+    if ([self.response respondsToSelector:@selector(allHeaderFields)] && [[self.response allHeaderFields] valueForKey:@"ETag"]) {
+        [mutableURLRequest setValue:[[self.response allHeaderFields] valueForKey:@"ETag"] forHTTPHeaderField:@"If-Range"];
+    }
+    [mutableURLRequest setValue:[NSString stringWithFormat:@"bytes=%llu-", offset] forHTTPHeaderField:@"Range"];
+    self.request = mutableURLRequest;
+}
+
+#pragma mark - NSSecureCoding
+
++ (BOOL)supportsSecureCoding {
+    return YES;
+}
+
+- (id)initWithCoder:(NSCoder *)decoder {
+    self = [super initWithCoder:decoder];
+    if (!self) {
+        return nil;
+    }
+
+    self.responseSerializer = [decoder decodeObjectOfClass:[AFHTTPResponseSerializer class] forKey:NSStringFromSelector(@selector(responseSerializer))];
+
+    return self;
+}
+
+- (void)encodeWithCoder:(NSCoder *)coder {
+    [super encodeWithCoder:coder];
+
+    [coder encodeObject:self.responseSerializer forKey:NSStringFromSelector(@selector(responseSerializer))];
+}
+
+#pragma mark - NSCopying
+
+- (id)copyWithZone:(NSZone *)zone {
+    AFHTTPRequestOperation *operation = [super copyWithZone:zone];
+
+    operation.responseSerializer = [self.responseSerializer copyWithZone:zone];
+    operation.completionQueue = self.completionQueue;
+    operation.completionGroup = self.completionGroup;
+
+    return operation;
+}
+
+@end

+ 0 - 0
sdk/Objective-C/XSHttpTool/AFNetworking/AFHTTPRequestOperationManager.h


Some files were not shown because too many files changed in this diff