View source
<?php
require_once 'share_count.php';
class ShareaholicCurlMultiShareCount extends ShareaholicShareCount {
public function get_counts() {
$services_length = count($this->services);
$config = self::get_services_config();
$response = array();
$response['status'] = 200;
$curl_handles = array();
$multi_handle = curl_multi_init();
for ($i = 0; $i < $services_length; $i++) {
$service = $this->services[$i];
if (!isset($config[$service])) {
continue;
}
if (isset($config[$service]['prepare'])) {
$this
->{$config[$service]['prepare']}($this->url, $config);
}
$curl_handles[$service] = curl_init();
$this
->curl_setopts($curl_handles[$service], $config, $service);
curl_multi_add_handle($multi_handle, $curl_handles[$service]);
}
if (count($curl_handles) > 0) {
$running = NULL;
do {
$mrc = curl_multi_exec($multi_handle, $running);
} while ($mrc == CURLM_CALL_MULTI_PERFORM);
while ($running && $mrc == CURLM_OK) {
if (curl_multi_select($multi_handle) == -1) {
usleep(1);
}
do {
$mrc = curl_multi_exec($multi_handle, $running);
} while ($mrc == CURLM_CALL_MULTI_PERFORM);
}
foreach ($curl_handles as $service => $handle) {
if (curl_errno($handle)) {
$response['status'] = 500;
}
$result = array(
'body' => curl_multi_getcontent($handle),
'response' => array(
'code' => curl_getinfo($handle, CURLINFO_HTTP_CODE),
),
);
$callback = $config[$service]['callback'];
$counts = $this
->{$callback}($result);
if (is_numeric($counts)) {
$response['data'][$service] = $counts;
}
$this->raw_response[$service] = $result;
curl_multi_remove_handle($multi_handle, $handle);
curl_close($handle);
}
curl_multi_close($multi_handle);
}
return $response;
}
private function curl_setopts($curl_handle, $config, $service) {
curl_setopt($curl_handle, CURLOPT_URL, str_replace('%s', $this->url, $config[$service]['url']));
$timeout = isset($this->options['timeout']) ? $this->options['timeout'] : 6;
curl_setopt_array($curl_handle, array(
CURLOPT_HEADER => 0,
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_TIMEOUT => $timeout,
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_SSL_VERIFYHOST => false,
));
if ($config[$service]['method'] === 'POST') {
curl_setopt($curl_handle, CURLOPT_POST, 1);
}
$headers = isset($config[$service]['headers']) ? $config[$service]['headers'] : array();
$body = isset($config[$service]['body']) ? $config[$service]['body'] : NULL;
if (isset($body)) {
if (isset($headers['Content-Type']) && $headers['Content-Type'] === 'application/json') {
$data_string = json_encode($body);
curl_setopt($curl_handle, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($data_string),
));
curl_setopt($curl_handle, CURLOPT_POSTFIELDS, $data_string);
}
}
$useragent = isset($config[$service]['User-Agent']) ? $config[$service]['User-Agent'] : 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.8; rv:24.0) Gecko/20100101 Firefox/24.0';
curl_setopt($curl_handle, CURLOPT_USERAGENT, $useragent);
}
}