PageRenderTime 35ms CodeModel.GetById 38ms RepoModel.GetById 0ms app.codeStats 0ms

/package/app/app/deployment/uiconf/KalturaClientBase.php

https://github.com/richhl/kalturaCE
PHP | 606 lines | 375 code | 74 blank | 157 comment | 35 complexity | beb8a6973552c14d92aef5326bdfc27d MD5 | raw file
  1. <?php
  2. class KalturaClientBase
  3. {
  4. const KALTURA_API_VERSION = "3.0";
  5. const KALTURA_SERVICE_FORMAT_JSON = 1;
  6. const KALTURA_SERVICE_FORMAT_XML = 2;
  7. const KALTURA_SERVICE_FORMAT_PHP = 3;
  8. /**
  9. * @var KalturaConfiguration
  10. */
  11. private $config;
  12. /**
  13. * @var string
  14. */
  15. private $ks;
  16. /**
  17. * @var boolean
  18. */
  19. private $shouldLog = false;
  20. /**
  21. * @var bool
  22. */
  23. private $isMultiRequest = false;
  24. /**
  25. * @var unknown_type
  26. */
  27. private $callsQueue = array();
  28. /**
  29. * Kaltura client constructor
  30. *
  31. * @param KalturaConfiguration $config
  32. */
  33. public function __construct(KalturaConfiguration $config)
  34. {
  35. $this->config = $config;
  36. $logger = $this->config->getLogger();
  37. if ($logger)
  38. {
  39. $this->shouldLog = true;
  40. }
  41. }
  42. public function queueServiceActionCall($service, $action, $params = array(), $files = array())
  43. {
  44. // in start session partner id is optional (default -1). if partner id was not set, use the one in the config
  45. if (!isset($params["partnerId"]) || $params["partnerId"] === -1)
  46. $params["partnerId"] = $this->config->partnerId;
  47. $this->addParam($params, "ks", $this->ks);
  48. $call = new KalturaServiceActionCall($service, $action, $params, $files);
  49. $this->callsQueue[] = $call;
  50. }
  51. /**
  52. * Call all API service that are in queue
  53. *
  54. * @return unknown
  55. */
  56. public function doQueue()
  57. {
  58. if (count($this->callsQueue) == 0)
  59. {
  60. $this->isMultiRequest = false;
  61. return null;
  62. }
  63. $startTime = microtime(true);
  64. $params = array();
  65. $files = array();
  66. $this->log("service url: [" . $this->config->serviceUrl . "]");
  67. // append the basic params
  68. $this->addParam($params, "apiVersion", self::KALTURA_API_VERSION);
  69. $this->addParam($params, "format", $this->config->format);
  70. $this->addParam($params, "clientTag", $this->config->clientTag);
  71. $url = $this->config->serviceUrl."/api_v3/index.php?service=";
  72. if ($this->isMultiRequest)
  73. {
  74. $url .= "multirequest";
  75. $i = 1;
  76. foreach ($this->callsQueue as $call)
  77. {
  78. $callParams = $call->getParamsForMultiRequest($i++);
  79. $params = array_merge($params, $callParams);
  80. $files = array_merge($files, $call->files);
  81. }
  82. }
  83. else
  84. {
  85. $call = $this->callsQueue[0];
  86. $url .= $call->service."&action=".$call->action;
  87. $params = array_merge($params, $call->params);
  88. $files = $call->files;
  89. }
  90. // reset
  91. $this->callsQueue = array();
  92. $this->isMultiRequest = false;
  93. $signature = $this->signature($params);
  94. $this->addParam($params, "kalsig", $signature);
  95. list($postResult, $error) = $this->doHttpRequest($url, $params, $files);
  96. if ($error)
  97. {
  98. throw new KalturaClientException($error, KalturaClientException::ERROR_GENERIC);
  99. }
  100. else
  101. {
  102. $this->log("result (serialized): " . $postResult);
  103. if ($this->config->format == self::KALTURA_SERVICE_FORMAT_PHP)
  104. {
  105. $result = @unserialize($postResult);
  106. if ($result === false && serialize(false) !== $postResult)
  107. {
  108. throw new KalturaClientException("failed to unserialize server result\n$postResult", KalturaClientException::ERROR_UNSERIALIZE_FAILED);
  109. }
  110. $dump = print_r($result, true);
  111. $this->log("result (object dump): " . $dump);
  112. }
  113. else
  114. {
  115. throw new KalturaClientException("unsupported format: $postResult", KalturaClientException::ERROR_FORMAT_NOT_SUPPORTED);
  116. }
  117. }
  118. $endTime = microtime (true);
  119. $this->log("execution time for [".$url."]: [" . ($endTime - $startTime) . "]");
  120. return $result;
  121. }
  122. /**
  123. * Sign array of parameters
  124. *
  125. * @param array $params
  126. * @return string
  127. */
  128. private function signature($params)
  129. {
  130. ksort($params);
  131. $str = "";
  132. foreach ($params as $k => $v)
  133. {
  134. $str .= $k.$v;
  135. }
  136. return md5($str);
  137. }
  138. /**
  139. * Send http request by using curl (if available) or php stream_context
  140. *
  141. * @param string $url
  142. * @param parameters $params
  143. * @return array of result and error
  144. */
  145. private function doHttpRequest($url, $params = array(), $files = array())
  146. {
  147. if (function_exists('curl_init'))
  148. return $this->doCurl($url, $params, $files);
  149. else
  150. return $this->doPostRequest($url, $params, $files);
  151. }
  152. /**
  153. * Curl HTTP POST Request
  154. *
  155. * @param string $url
  156. * @param array $params
  157. * @return array of result and error
  158. */
  159. private function doCurl($url, $params = array(), $files = array())
  160. {
  161. $ch = curl_init();
  162. curl_setopt($ch, CURLOPT_URL, $url);
  163. curl_setopt($ch, CURLOPT_POST, 1);
  164. if (count($files) > 0)
  165. {
  166. foreach($files as &$file)
  167. $file = "@".$file; // let curl know its a file
  168. curl_setopt($ch, CURLOPT_POSTFIELDS, array_merge($params, $files));
  169. }
  170. else
  171. {
  172. $opt = http_build_query($params, null, "&");
  173. $this->log("curl: $url&$opt");
  174. curl_setopt($ch, CURLOPT_POSTFIELDS, $opt);
  175. }
  176. curl_setopt($ch, CURLOPT_ENCODING, 'gzip,deflate');
  177. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  178. curl_setopt($ch, CURLOPT_USERAGENT, '');
  179. if (count($files) > 0)
  180. curl_setopt($ch, CURLOPT_TIMEOUT, 0);
  181. else
  182. curl_setopt($ch, CURLOPT_TIMEOUT, $this->config->curlTimeout);
  183. $result = curl_exec($ch);
  184. $curlError = curl_error($ch);
  185. curl_close($ch);
  186. return array($result, $curlError);
  187. }
  188. /**
  189. * HTTP stream context request
  190. *
  191. * @param string $url
  192. * @param array $params
  193. * @return array of result and error
  194. */
  195. private function doPostRequest($url, $params = array(), $files = array())
  196. {
  197. if (count($files) > 0)
  198. throw new KalturaClientException("Uploading files is not supported with stream context http request, please use curl", KalturaClientException::ERROR_UPLOAD_NOT_SUPPORTED);
  199. $formattedData = http_build_query($params , "", "&");
  200. $params = array('http' => array(
  201. "method" => "POST",
  202. "Accept-language: en\r\n".
  203. "Content-type: application/x-www-form-urlencoded\r\n",
  204. "content" => $formattedData
  205. ));
  206. $ctx = stream_context_create($params);
  207. $fp = @fopen($url, 'rb', false, $ctx);
  208. if (!$fp) {
  209. $phpErrorMsg = "";
  210. throw new KalturaClientException("Problem with $url, $phpErrorMsg", KalturaClientException::ERROR_CONNECTION_FAILED);
  211. }
  212. $response = @stream_get_contents($fp);
  213. if ($response === false) {
  214. throw new KalturaClientException("Problem reading data from $url, $phpErrorMsg", KalturaClientException::ERROR_READ_FAILED);
  215. }
  216. return array($response, '');
  217. }
  218. /**
  219. * @return string
  220. */
  221. public function getKs()
  222. {
  223. return $this->ks;
  224. }
  225. /**
  226. * @param string $ks
  227. */
  228. public function setKs($ks)
  229. {
  230. $this->ks = $ks;
  231. }
  232. /**
  233. * @return KalturaConfiguration
  234. */
  235. public function getConfig()
  236. {
  237. return $this->config;
  238. }
  239. /**
  240. * @param KalturaConfiguration $config
  241. */
  242. public function setConfig(KalturaConfiguration $config)
  243. {
  244. $this->config = $config;
  245. $logger = $this->config->getLogger();
  246. if ($logger instanceof IKalturaLogger)
  247. {
  248. $this->shouldLog = true;
  249. }
  250. }
  251. /**
  252. * Add parameter to array of parameters that is passed by reference
  253. *
  254. * @param arrat $params
  255. * @param string $paramName
  256. * @param string $paramValue
  257. */
  258. public function addParam(&$params, $paramName, $paramValue)
  259. {
  260. if ($paramValue === null)
  261. return;
  262. if(!is_array($paramValue))
  263. {
  264. $params[$paramName] = $paramValue;
  265. return;
  266. }
  267. foreach($paramValue as $subParamName => $subParamValue)
  268. $this->addParam($params, "$paramName:$subParamName", $subParamValue);
  269. }
  270. /**
  271. * Validate the result object and throw exception if its an error
  272. *
  273. * @param object $resultObject
  274. */
  275. public function throwExceptionIfError($resultObject)
  276. {
  277. if ($this->isError($resultObject))
  278. {
  279. throw new KalturaException($resultObject["message"], $resultObject["code"]);
  280. }
  281. }
  282. /**
  283. * Checks whether the result object is an error
  284. *
  285. * @param object $resultObject
  286. */
  287. public function isError($resultObject)
  288. {
  289. return (is_array($resultObject) && isset($resultObject["message"]) && isset($resultObject["code"]));
  290. }
  291. /**
  292. * Validate that the passed object type is of the expected type
  293. *
  294. * @param unknown_type $resultObject
  295. * @param unknown_type $objectType
  296. */
  297. public function validateObjectType($resultObject, $objectType)
  298. {
  299. if (is_object($resultObject))
  300. {
  301. if (!($resultObject instanceof $objectType))
  302. throw new KalturaClientException("Invalid object type", KalturaClientException::ERROR_INVALID_OBJECT_TYPE);
  303. }
  304. else if (gettype($resultObject) !== "NULL" && gettype($resultObject) !== $objectType)
  305. {
  306. throw new KalturaClientException("Invalid object type", KalturaClientException::ERROR_INVALID_OBJECT_TYPE);
  307. }
  308. }
  309. public function startMultiRequest()
  310. {
  311. $this->isMultiRequest = true;
  312. }
  313. public function doMultiRequest()
  314. {
  315. return $this->doQueue();
  316. }
  317. public function isMultiRequest()
  318. {
  319. return $this->isMultiRequest;
  320. }
  321. /**
  322. * @param string $msg
  323. */
  324. protected function log($msg)
  325. {
  326. if ($this->shouldLog)
  327. $this->config->getLogger()->log($msg);
  328. }
  329. public function KalturaCreateKS($sessionType, $puserId, $privileges, $adminSecret, $expiry = 7200)
  330. {
  331. $rand = rand(0, 32000);
  332. $rand = microtime(true);
  333. $expiry = time()+$expiry;
  334. $fields = array ( $this->config->partnerId , '' , $expiry , $sessionType, $rand , $puserId , $privileges );
  335. $str = implode ( ";" , $fields );
  336. $salt = $adminSecret;
  337. $hashed_str = $this->hash ( $salt , $str ) . "|" . $str ;
  338. $decoded_str = base64_encode( $hashed_str );
  339. return $decoded_str;
  340. }
  341. function hash ( $salt , $str )
  342. {
  343. return sha1($salt.$str);
  344. }
  345. }
  346. class KalturaServiceActionCall
  347. {
  348. /**
  349. * @var string
  350. */
  351. public $service;
  352. /**
  353. * @var string
  354. */
  355. public $action;
  356. /**
  357. * @var array
  358. */
  359. public $params;
  360. /**
  361. * @var array
  362. */
  363. public $files;
  364. /**
  365. * Contruct new Kaltura service action call, if params array contain sub arrays (for objects), it will be flattened
  366. *
  367. * @param string $service
  368. * @param string $action
  369. * @param array $params
  370. * @param array $files
  371. */
  372. public function __construct($service, $action, $params = array(), $files = array())
  373. {
  374. $this->service = $service;
  375. $this->action = $action;
  376. $this->params = $this->parseParams($params);
  377. $this->files = $files;
  378. }
  379. /**
  380. * Parse params array and sub arrays (for objects)
  381. *
  382. * @param array $params
  383. */
  384. public function parseParams(array $params)
  385. {
  386. $newParams = array();
  387. foreach($params as $key => $val)
  388. {
  389. if (is_array($val))
  390. {
  391. $newParams[$key] = $this->parseParams($val);
  392. }
  393. else
  394. {
  395. $newParams[$key] = $val;
  396. }
  397. }
  398. return $newParams;
  399. }
  400. /**
  401. * Return the parameters for a multi request
  402. *
  403. * @param int $multiRequestIndex
  404. */
  405. public function getParamsForMultiRequest($multiRequestIndex)
  406. {
  407. $multiRequestParams = array();
  408. $multiRequestParams[$multiRequestIndex.":service"] = $this->service;
  409. $multiRequestParams[$multiRequestIndex.":action"] = $this->action;
  410. foreach($this->params as $key => $val)
  411. {
  412. $multiRequestParams[$multiRequestIndex.":".$key] = $val;
  413. }
  414. return $multiRequestParams;
  415. }
  416. }
  417. /**
  418. * Abstract base class for all client services
  419. *
  420. */
  421. abstract class KalturaServiceBase
  422. {
  423. /**
  424. * @var KalturaClient
  425. */
  426. protected $client;
  427. /**
  428. * Initialize the service keeping reference to the KalturaClient
  429. *
  430. * @param KalturaClient $client
  431. */
  432. public function __construct(KalturaClient $client)
  433. {
  434. $this->client = $client;
  435. }
  436. }
  437. /**
  438. * Abstract base class for all client objects
  439. *
  440. */
  441. abstract class KalturaObjectBase
  442. {
  443. protected function addIfNotNull(&$params, $paramName, $paramValue)
  444. {
  445. if ($paramValue !== null)
  446. {
  447. if($paramValue instanceof KalturaObjectBase)
  448. {
  449. $params[$paramName] = $paramValue->toParams();
  450. }
  451. else
  452. {
  453. $params[$paramName] = $paramValue;
  454. }
  455. }
  456. }
  457. public function toParams()
  458. {
  459. $params = array();
  460. $params["objectType"] = get_class($this);
  461. foreach($this as $prop => $val)
  462. {
  463. $this->addIfNotNull($params, $prop, $val);
  464. }
  465. return $params;
  466. }
  467. }
  468. class KalturaException extends Exception
  469. {
  470. public function __construct($message, $code)
  471. {
  472. $this->code = $code;
  473. parent::__construct($message);
  474. }
  475. }
  476. class KalturaClientException extends Exception
  477. {
  478. const ERROR_GENERIC = -1;
  479. const ERROR_UNSERIALIZE_FAILED = -2;
  480. const ERROR_FORMAT_NOT_SUPPORTED = -3;
  481. const ERROR_UPLOAD_NOT_SUPPORTED = -4;
  482. const ERROR_CONNECTION_FAILED = -5;
  483. const ERROR_READ_FAILED = -6;
  484. const ERROR_INVALID_PARTNER_ID = -7;
  485. const ERROR_INVALID_OBJECT_TYPE = -8;
  486. }
  487. class KalturaConfiguration
  488. {
  489. private $logger;
  490. public $serviceUrl = "http://www.kaltura.com/";
  491. public $partnerId = null;
  492. public $format = 3;
  493. public $clientTag = "php5";
  494. public $curlTimeout = 10;
  495. /**
  496. * Constructs new Kaltura configuration object
  497. *
  498. */
  499. public function __construct($partnerId = -1)
  500. {
  501. if (!is_numeric($partnerId))
  502. throw new KalturaClientException("Invalid partner id", KalturaClientException::ERROR_INVALID_PARTNER_ID);
  503. $this->partnerId = $partnerId;
  504. }
  505. /**
  506. * Set logger to get kaltura client debug logs
  507. *
  508. * @param IKalturaLogger $log
  509. */
  510. public function setLogger(IKalturaLogger $log)
  511. {
  512. $this->logger = $log;
  513. }
  514. /**
  515. * Gets the logger (Internal client use)
  516. *
  517. * @return IKalturaLogger
  518. */
  519. public function getLogger()
  520. {
  521. return $this->logger;
  522. }
  523. }
  524. /**
  525. * Implement to get Kaltura Client logs
  526. *
  527. */
  528. interface IKalturaLogger
  529. {
  530. function log($msg);
  531. }
  532. ?>