public function upload($content, $mimeType, $name = null) { if (!$this->getUploadUrl()) { throw new \RuntimeException("Please initialize with pre-signed url."); } $headers[] = "User-Agent: " . Client::getVersionString(); $headers[] = "Content-Type: {$mimeType}"; $url = $this->getUploadUrl(); $ch = curl_init($url); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true); curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT"); curl_setopt($ch, CURLOPT_POSTFIELDS, $content); $resp = curl_exec($ch); $respCode = curl_getinfo($ch, CURLINFO_HTTP_CODE); $respType = curl_getinfo($ch, CURLINFO_CONTENT_TYPE); $error = curl_errno($ch); $errno = curl_errno($ch); curl_close($ch); if ($errno > 0) { throw new \RuntimeException("CURL ({$url}) error: " . "{$errno} {$error}", $errno); } if ($respCode >= "300") { $S3Error = simplexml_load_string($resp); throw new \RuntimeException("Upload to S3 ({$url}) failed: " . "{$S3Error->Code} {$S3Error->Message}"); } return true; }
/** * Upload file to qiniu * * @param string $content File content * @param string $mimeType MIME type of file * @param string $key Generated file name */ public function upload($content, $mimeType, $key) { $boundary = md5(microtime(true)); $body = $this->multipartEncode(array("name" => $key, "mimeType" => $mimeType, "content" => $content), array("token" => $this->getAuthToken(), "key" => $key, "crc32" => $this->crc32Data($content)), $boundary); $headers[] = "User-Agent: " . Client::getVersionString(); $headers[] = "Content-Type: multipart/form-data;" . " boundary={$boundary}"; $headers[] = "Content-Length: " . strlen($body); $url = $this->getUploadUrl(); $ch = curl_init($url); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true); curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, $body); $resp = curl_exec($ch); $respCode = curl_getinfo($ch, CURLINFO_HTTP_CODE); $respType = curl_getinfo($ch, CURLINFO_CONTENT_TYPE); $error = curl_errno($ch); $errno = curl_errno($ch); curl_close($ch); /** type of error: * - curl error * - http status error 4xx, 5xx * - rest api error */ if ($errno > 0) { throw new \RuntimeException("CURL ({$url}) error: " . "{$errno} {$error}", $errno); } $data = json_decode($resp, true); if (isset($data["error"])) { $code = isset($data["code"]) ? $data["code"] : 1; throw new \RuntimeException("Upload to Qiniu ({$url}) failed: " . "{$code} {$data['error']}", $code); } return $data; }
public function testSetWhere() { $push = new Push(array("alert" => "Hello world!")); $query = new Query("_Installation"); $date = new DateTime(); $query->lessThan("updatedAt", $date); $push->setWhere($query); $out = $push->encode(); $this->assertEquals(array("updatedAt" => array('$lt' => Client::encode($date))), $out["where"]); }
public function testOperationEncode() { $op = new SetOperation("name", "alice"); $this->assertEquals($op->encode(), "alice"); $op = new SetOperation("score", 70.0); $this->assertEquals($op->encode(), 70.0); $date = new DateTime(); $op = new SetOperation("released", $date); $out = $op->encode(); $this->assertEquals($out['__type'], "Date"); $this->assertEquals($out['iso'], Client::formatDate($date)); }
public static function setUpBeforeClass() { Client::initialize(getenv("LC_APP_ID"), getenv("LC_APP_KEY"), getenv("LC_APP_MASTER_KEY")); Client::useRegion(getenv("LC_API_REGION")); Client::setStorage(new SessionStorage()); // Try to make a default user so we can login $user = new User(); $user->setUsername("alice"); $user->setPassword("blabla"); try { $user->signUp(); } catch (CloudException $ex) { // skip } }
private function request($url, $method, $data = null) { $appUrl = "http://" . getenv("LC_APP_HOST") . ":" . getenv("LC_APP_PORT"); $url = $appUrl . $url; $headers = Client::buildHeaders(null, true); $headers["Content-Type"] = "application/json;charset=utf-8"; $headers["Origin"] = getenv("LC_APP_HOST"); // emulate CORS $h = array_map(function ($k, $v) { return "{$k}: {$v}"; }, array_keys($headers), $headers); $req = curl_init($url); curl_setopt($req, CURLOPT_HTTPHEADER, $h); curl_setopt($req, CURLOPT_RETURNTRANSFER, true); if ($method == "POST") { curl_setopt($req, CURLOPT_POST, 1); curl_setopt($req, CURLOPT_POSTFIELDS, json_encode($data)); } else { // GET if ($data) { curl_setopt($req, CURLOPT_URL, $url . "?" . http_build_query($data)); } } $resp = curl_exec($req); $errno = curl_errno($req); curl_close($req); if ($errno > 0) { throw new \RuntimeException("CURL connection error {$errno}: {$url}"); } $data = json_decode($resp, true); if (isset($data["error"])) { $code = isset($data["code"]) ? $data["code"] : -1; throw new CloudException("{$code} {$data['error']}", $code); } return $data; }
/** * Encode to JSON represented operation * * @return array */ public function encode() { return array("__op" => $this->getOpType(), "objects" => Client::encode($this->value)); }
/** * Delete file on cloud * * @throws CloudException */ public function destroy() { if (!$this->getObjectId()) { return false; } Client::delete("/files/{$this->getObjectId()}"); }
/** * Doing a CQL query to retrive objects * * It returns an array that contains: * * * className - Class name of the query * * results - List of objects * * count - Number of objects when it's a count query * * @param string $cql CQL statement * @param array $pvalues Positional values to replace in CQL * @return array * @link https://leancloud.cn/docs/cql_guide.html */ public static function doCloudQuery($cql, $pvalues = array()) { $data = array("cql" => $cql); if (!empty($pvalues)) { $data["pvalues"] = json_encode(Client::encode($pvalues)); } $resp = Client::get('/cloudQuery', $data); $objects = array(); foreach ($resp["results"] as $val) { $obj = Object::create($resp["className"], $val["objectId"]); $obj->mergeAfterFetch($val); $objects[] = $obj; } $resp["results"] = $objects; return $resp; }
/** * Issue a batch request * * @param array $requests Array of requests in batch op * @param string $sessionToken Session token of a User * @param array $headers Optional headers * @param bool $useMasterkey Use master key or not, optional * @return array JSON decoded associated array * @see self::request() */ public static function batch($requests, $sessionToken = null, $headers = array(), $useMasterKey = null) { $response = Client::post("/batch", array("requests" => $requests), $sessionToken, $headers, $useMasterKey); $batchRequestError = new BatchRequestError(); foreach ($requests as $i => $req) { if (isset($response[$i]["error"])) { $batchRequestError->add($req, $response[$i]["error"]); } } if (!$batchRequestError->isEmpty()) { throw $batchRequestError; } return $response; }
/** * Delete objects in batch * * @param array $objects Array of Objects to destroy */ public static function destroyAll($objects) { $batch = array(); foreach ($objects as $obj) { if (!$obj->getObjectId()) { throw new \RuntimeException("Cannot destroy object without ID"); } // Remove duplicate objects by ID $batch[$obj->getObjectId()] = $obj; } if (empty($batch)) { return; } $requests = array(); $objects = array(); foreach ($batch as $obj) { $requests[] = array("path" => "/1.1/classes/{$obj->getClassName()}" . "/{$obj->getObjectId()}", "method" => "DELETE"); $objects[] = $obj; } $sessionToken = User::getCurrentSessionToken(); $response = Client::batch($requests, $sessionToken); }
/** * Dispatch onInsight hook * * @param array $body JSON decoded body params */ private function dispatchOnInsight($body) { if (!Client::verifyHookSign("__on_complete_bigquery_job", $body["__sign"])) { error_log("Invalid hook sign for onComplete Insight" . " from {$this->env['REMOTE_ADDR']}"); $this->renderError("Unauthorized.", 401, 401); } $meta["remoteAddress"] = $this->env["REMOTE_ADDR"]; try { Cloud::runOnInsight($body, $meta); } catch (FunctionError $err) { $this->renderError($err->getMessage(), $err->getCode()); } $this->renderJSON(array("result" => "ok")); }
public function testUserLogin() { $data = array("username" => "testuser", "password" => "5akf#a?^G", "phone" => "18612340000"); $resp = Client::post("/users", $data); $this->assertNotEmpty($resp["objectId"]); $this->assertNotEmpty($resp["sessionToken"]); $id = $resp["objectId"]; $resp = Client::get("/users/me", array("session_token" => $resp["sessionToken"])); $this->assertNotEmpty($resp["objectId"]); Client::delete("/users/{$id}", $resp["sessionToken"]); // Raise 211: Could not find user. $this->setExpectedException("LeanCloud\\CloudException", null, 211); $resp = Client::get("/users/me", array("session_token" => "non-existent-token")); }
public function testEncodeCircularObjectAsPointer() { $a = new Object("TestObject", "id001"); $b = new Object("TestObject", "id002"); $c = new Object("TestObject", "id003"); $a->set("name", "A"); $b->set("name", "B"); $c->set("name", "C"); $a->addIn("likes", $b); $b->addIn("likes", $c); $c->addIn("likes", $a); $jsonA = Client::encode($a, "toFullJSON"); $jsonB = $jsonA["likes"][0]; $jsonC = $jsonB["likes"][0]; $this->assertEquals("Object", $jsonA["__type"]); $this->assertEquals("Object", $jsonB["__type"]); $this->assertEquals("Object", $jsonC["__type"]); $this->assertEquals("Pointer", $jsonC["likes"][0]["__type"]); }
/** * Encode to JSON represented operation * * @return array */ public function encode() { return Client::encode($this->value); }
public static function setUpBeforeClass() { Client::initialize(getenv("LC_APP_ID"), getenv("LC_APP_KEY"), getenv("LC_APP_MASTER_KEY")); Client::useRegion(getenv("LC_API_REGION")); }
<?php require_once "src/autoload.php"; use LeanCloud\Client; use LeanCloud\Engine\LeanEngine; use LeanCloud\Engine\Cloud; Client::initialize(getenv("LC_APP_ID"), getenv("LC_APP_KEY"), getenv("LC_APP_MASTER_KEY")); // define a function Cloud::define("hello", function () { return "hello"; }); // define function with named params Cloud::define("sayHello", function ($params, $user) { return "hello {$params['name']}"; }); Cloud::define("_messageReceived", function ($params, $user) { if ($params["convId"]) { return array("drop" => false); } else { return array("drop" => true); } }); Cloud::define("getMeta", function ($params, $user, $meta) { return array("remoteAddress" => $meta["remoteAddress"]); }); Cloud::define("updateObject", function ($params, $user) { $obj = $params["object"]; $obj->set("__testKey", 42); return $obj; }); Cloud::onLogin(function ($user) {
/** * Verify mobile phone by SMS code * * @param string $smsCode */ public static function verifyMobilePhone($smsCode) { Client::post("/verifyMobilePhone/{$smsCode}", null); }