public function apicall($version, $action, $params)
{
$justone = is_string($params);
$params = self::paramify($params);
if (!array_key_exists('urls', $params)) {
$params['urls'] = array();
}
if (!is_array($params['urls'])) {
$urls = array($params['urls']);
$params['urls'] = $urls;
}
if (array_key_exists('url', $params) && $params['url']) {
array_push($params['urls'], $params['url']);
unset($params['url']);
}
$rejects = array();
if ($this->key) {
$params['key'] = $this->key;
} else {
$regex = $this->services_regex();
foreach ($params['urls'] as $i => $url) {
$match = preg_match($regex, $url);
if (!$match) {
unset($params['urls'][$i]);
$rejects[$i] = (object) array('error_code' => '401', 'error_message' => 'This service requires an Embedly key', 'type' => 'error');
}
}
}
$result = array();
$merged_result = array();
if (sizeof($rejects) < sizeof($params['urls'])) {
if (count($params['urls']) > 20) {
throw new \Exception(sprintf("Max of 20 urls can be queried at once, %s passed", count($params['urls'])));
}
$path = sprintf("%s/%s", $version, $action);
$url_parts = $this->parse_host($this->hostname);
$apiUrl = sprintf("%s%s?%s", $url_parts['url'], $path, $this->q($params));
$ch = curl_init($apiUrl);
$this->setCurlOptions($ch, array(sprintf('Host: %s', $url_parts['hostname']), sprintf('User-Agent: %s', $this->user_agent)));
$response_arr = $this->curlExec($ch);
$http_code = $response_arr["http_code"];
$res = $response_arr["response"];
$result = json_decode($res) ?: array();
// if there's an http error code, return the error in all results
if ($http_code !== 200) {
// if error is returned in response use that one otherwise create new one
if (count($result) > 0) {
$error_obj = $result;
// all results will be in rejected array
$result = array();
} else {
$error_obj = (object) array('error_code' => $http_code, 'error_message' => sprintf('HTTP error code %s', $http_code), 'type' => 'error');
}
// set errors in every result object
foreach ($params["urls"] as $i => $url) {
$rejects[$i] = $error_obj;
}
}
}
foreach ($result as $i => $v) {
if (array_key_exists($i, $rejects)) {
array_push($merged_result, array_shift($rejects));
}
array_push($merged_result, $v);
}
// grab any leftovers
foreach ($rejects as $obj) {
array_push($merged_result, $obj);
}
if ($justone) {
return array_shift($merged_result);
}
return $merged_result;
}