repository_name stringlengths 5 67 | func_path_in_repository stringlengths 4 234 | func_name stringlengths 0 314 | whole_func_string stringlengths 52 3.87M | language stringclasses 6 values | func_code_string stringlengths 52 3.87M | func_code_tokens listlengths 15 672k | func_documentation_string stringlengths 1 47.2k | func_documentation_tokens listlengths 1 3.92k | split_name stringclasses 1 value | func_code_url stringlengths 85 339 |
|---|---|---|---|---|---|---|---|---|---|---|
mautic/api-library | lib/Api/Api.php | Api.getCustom | public function getCustom($id, array $select = array())
{
$supported = $this->isSupported('get');
return (true === $supported) ? $this->makeRequest("{$this->endpoint}/$id", array('select' => $select)) : $supported;
} | php | public function getCustom($id, array $select = array())
{
$supported = $this->isSupported('get');
return (true === $supported) ? $this->makeRequest("{$this->endpoint}/$id", array('select' => $select)) : $supported;
} | [
"public",
"function",
"getCustom",
"(",
"$",
"id",
",",
"array",
"$",
"select",
"=",
"array",
"(",
")",
")",
"{",
"$",
"supported",
"=",
"$",
"this",
"->",
"isSupported",
"(",
"'get'",
")",
";",
"return",
"(",
"true",
"===",
"$",
"supported",
")",
... | @param $id
@param array $select
@return array|bool | [
"@param",
"$id",
"@param",
"array",
"$select"
] | train | https://github.com/mautic/api-library/blob/54c035bb87051250c2226b46b1b07e28aece1c39/lib/Api/Api.php#L400-L405 |
mautic/api-library | lib/Api/Api.php | Api.getList | public function getList($search = '', $start = 0, $limit = 0, $orderBy = '', $orderByDir = 'ASC', $publishedOnly = false, $minimal = false)
{
$parameters = array(
'search' => $search,
'start' => $start,
'limit' => $limit,
'orderBy' => $orderBy,
'orderByDir' => $orderByDir,
'publishedOnly' => $publishedOnly,
'minimal' => $minimal
);
$parameters = array_filter($parameters);
return $this->makeRequest($this->endpoint, $parameters);
} | php | public function getList($search = '', $start = 0, $limit = 0, $orderBy = '', $orderByDir = 'ASC', $publishedOnly = false, $minimal = false)
{
$parameters = array(
'search' => $search,
'start' => $start,
'limit' => $limit,
'orderBy' => $orderBy,
'orderByDir' => $orderByDir,
'publishedOnly' => $publishedOnly,
'minimal' => $minimal
);
$parameters = array_filter($parameters);
return $this->makeRequest($this->endpoint, $parameters);
} | [
"public",
"function",
"getList",
"(",
"$",
"search",
"=",
"''",
",",
"$",
"start",
"=",
"0",
",",
"$",
"limit",
"=",
"0",
",",
"$",
"orderBy",
"=",
"''",
",",
"$",
"orderByDir",
"=",
"'ASC'",
",",
"$",
"publishedOnly",
"=",
"false",
",",
"$",
"mi... | Get a list of items
@param string $search
@param int $start
@param int $limit
@param string $orderBy
@param string $orderByDir
@param bool $publishedOnly
@param bool $minimal
@return array|mixed | [
"Get",
"a",
"list",
"of",
"items"
] | train | https://github.com/mautic/api-library/blob/54c035bb87051250c2226b46b1b07e28aece1c39/lib/Api/Api.php#L420-L435 |
mautic/api-library | lib/Api/Api.php | Api.getCustomList | public function getCustomList(QueryBuilder $queryBuilder, $start = 0, $limit = 0)
{
$parameters = array(
'select' => $queryBuilder->getSelect(),
'where' => $queryBuilder->getWhere(),
'order' => $queryBuilder->getOrder(),
'start' => $start,
'limit' => $limit,
);
$parameters = array_filter($parameters);
$supported = $this->isSupported('getList');
return (true === $supported) ? $this->makeRequest($this->endpoint, $parameters) : $supported;
} | php | public function getCustomList(QueryBuilder $queryBuilder, $start = 0, $limit = 0)
{
$parameters = array(
'select' => $queryBuilder->getSelect(),
'where' => $queryBuilder->getWhere(),
'order' => $queryBuilder->getOrder(),
'start' => $start,
'limit' => $limit,
);
$parameters = array_filter($parameters);
$supported = $this->isSupported('getList');
return (true === $supported) ? $this->makeRequest($this->endpoint, $parameters) : $supported;
} | [
"public",
"function",
"getCustomList",
"(",
"QueryBuilder",
"$",
"queryBuilder",
",",
"$",
"start",
"=",
"0",
",",
"$",
"limit",
"=",
"0",
")",
"{",
"$",
"parameters",
"=",
"array",
"(",
"'select'",
"=>",
"$",
"queryBuilder",
"->",
"getSelect",
"(",
")",... | @param QueryBuilder $queryBuilder
@param int $start
@param int $limit
@return array|bool | [
"@param",
"QueryBuilder",
"$queryBuilder",
"@param",
"int",
"$start",
"@param",
"int",
"$limit"
] | train | https://github.com/mautic/api-library/blob/54c035bb87051250c2226b46b1b07e28aece1c39/lib/Api/Api.php#L444-L459 |
mautic/api-library | lib/Api/Api.php | Api.getPublishedList | public function getPublishedList($search = '', $start = 0, $limit = 0, $orderBy = '', $orderByDir = 'ASC')
{
return $this->getList($search, $start, $limit, $orderBy, $orderByDir, true);
} | php | public function getPublishedList($search = '', $start = 0, $limit = 0, $orderBy = '', $orderByDir = 'ASC')
{
return $this->getList($search, $start, $limit, $orderBy, $orderByDir, true);
} | [
"public",
"function",
"getPublishedList",
"(",
"$",
"search",
"=",
"''",
",",
"$",
"start",
"=",
"0",
",",
"$",
"limit",
"=",
"0",
",",
"$",
"orderBy",
"=",
"''",
",",
"$",
"orderByDir",
"=",
"'ASC'",
")",
"{",
"return",
"$",
"this",
"->",
"getList... | Proxy function to getList with $publishedOnly set to true
@param string $search
@param int $start
@param int $limit
@param string $orderBy
@param string $orderByDir
@return array|mixed | [
"Proxy",
"function",
"to",
"getList",
"with",
"$publishedOnly",
"set",
"to",
"true"
] | train | https://github.com/mautic/api-library/blob/54c035bb87051250c2226b46b1b07e28aece1c39/lib/Api/Api.php#L472-L475 |
mautic/api-library | lib/Api/Api.php | Api.create | public function create(array $parameters)
{
$supported = $this->isSupported('create');
return (true === $supported) ? $this->makeRequest($this->endpoint.'/new', $parameters, 'POST') : $supported;
} | php | public function create(array $parameters)
{
$supported = $this->isSupported('create');
return (true === $supported) ? $this->makeRequest($this->endpoint.'/new', $parameters, 'POST') : $supported;
} | [
"public",
"function",
"create",
"(",
"array",
"$",
"parameters",
")",
"{",
"$",
"supported",
"=",
"$",
"this",
"->",
"isSupported",
"(",
"'create'",
")",
";",
"return",
"(",
"true",
"===",
"$",
"supported",
")",
"?",
"$",
"this",
"->",
"makeRequest",
"... | Create a new item (if supported)
@param array $parameters
@return array|mixed | [
"Create",
"a",
"new",
"item",
"(",
"if",
"supported",
")"
] | train | https://github.com/mautic/api-library/blob/54c035bb87051250c2226b46b1b07e28aece1c39/lib/Api/Api.php#L484-L489 |
mautic/api-library | lib/Api/Api.php | Api.createBatch | public function createBatch(array $parameters)
{
$supported = $this->isSupported('createBatch');
return (true === $supported) ? $this->makeRequest($this->endpoint.'/batch/new', $parameters, 'POST') : $supported;
} | php | public function createBatch(array $parameters)
{
$supported = $this->isSupported('createBatch');
return (true === $supported) ? $this->makeRequest($this->endpoint.'/batch/new', $parameters, 'POST') : $supported;
} | [
"public",
"function",
"createBatch",
"(",
"array",
"$",
"parameters",
")",
"{",
"$",
"supported",
"=",
"$",
"this",
"->",
"isSupported",
"(",
"'createBatch'",
")",
";",
"return",
"(",
"true",
"===",
"$",
"supported",
")",
"?",
"$",
"this",
"->",
"makeReq... | Create a batch of new items
@param array $parameters
@return array|mixed | [
"Create",
"a",
"batch",
"of",
"new",
"items"
] | train | https://github.com/mautic/api-library/blob/54c035bb87051250c2226b46b1b07e28aece1c39/lib/Api/Api.php#L498-L503 |
mautic/api-library | lib/Api/Api.php | Api.edit | public function edit($id, array $parameters, $createIfNotExists = false)
{
$method = $createIfNotExists ? 'PUT' : 'PATCH';
$supported = $this->isSupported('edit');
return (true === $supported) ? $this->makeRequest($this->endpoint.'/'.$id.'/edit', $parameters, $method) : $supported;
} | php | public function edit($id, array $parameters, $createIfNotExists = false)
{
$method = $createIfNotExists ? 'PUT' : 'PATCH';
$supported = $this->isSupported('edit');
return (true === $supported) ? $this->makeRequest($this->endpoint.'/'.$id.'/edit', $parameters, $method) : $supported;
} | [
"public",
"function",
"edit",
"(",
"$",
"id",
",",
"array",
"$",
"parameters",
",",
"$",
"createIfNotExists",
"=",
"false",
")",
"{",
"$",
"method",
"=",
"$",
"createIfNotExists",
"?",
"'PUT'",
":",
"'PATCH'",
";",
"$",
"supported",
"=",
"$",
"this",
"... | Edit an item with option to create if it doesn't exist
@param int $id
@param array $parameters
@param bool $createIfNotExists = false
@return array|mixed | [
"Edit",
"an",
"item",
"with",
"option",
"to",
"create",
"if",
"it",
"doesn",
"t",
"exist"
] | train | https://github.com/mautic/api-library/blob/54c035bb87051250c2226b46b1b07e28aece1c39/lib/Api/Api.php#L514-L520 |
mautic/api-library | lib/Api/Api.php | Api.editBatch | public function editBatch(array $parameters, $createIfNotExists = false)
{
$method = $createIfNotExists ? 'PUT' : 'PATCH';
$supported = $this->isSupported('editBatch');
return (true === $supported) ? $this->makeRequest($this->endpoint.'/batch/edit', $parameters, $method) : $supported;
} | php | public function editBatch(array $parameters, $createIfNotExists = false)
{
$method = $createIfNotExists ? 'PUT' : 'PATCH';
$supported = $this->isSupported('editBatch');
return (true === $supported) ? $this->makeRequest($this->endpoint.'/batch/edit', $parameters, $method) : $supported;
} | [
"public",
"function",
"editBatch",
"(",
"array",
"$",
"parameters",
",",
"$",
"createIfNotExists",
"=",
"false",
")",
"{",
"$",
"method",
"=",
"$",
"createIfNotExists",
"?",
"'PUT'",
":",
"'PATCH'",
";",
"$",
"supported",
"=",
"$",
"this",
"->",
"isSupport... | Edit a batch of items
@param array $parameters
@param bool $createIfNotExists
@return array|mixed | [
"Edit",
"a",
"batch",
"of",
"items"
] | train | https://github.com/mautic/api-library/blob/54c035bb87051250c2226b46b1b07e28aece1c39/lib/Api/Api.php#L530-L536 |
mautic/api-library | lib/Api/Api.php | Api.delete | public function delete($id)
{
$supported = $this->isSupported('delete');
return (true === $supported) ? $this->makeRequest($this->endpoint.'/'.$id.'/delete', array(), 'DELETE') : $supported;
} | php | public function delete($id)
{
$supported = $this->isSupported('delete');
return (true === $supported) ? $this->makeRequest($this->endpoint.'/'.$id.'/delete', array(), 'DELETE') : $supported;
} | [
"public",
"function",
"delete",
"(",
"$",
"id",
")",
"{",
"$",
"supported",
"=",
"$",
"this",
"->",
"isSupported",
"(",
"'delete'",
")",
";",
"return",
"(",
"true",
"===",
"$",
"supported",
")",
"?",
"$",
"this",
"->",
"makeRequest",
"(",
"$",
"this"... | Delete an item
@param $id
@return array|mixed | [
"Delete",
"an",
"item"
] | train | https://github.com/mautic/api-library/blob/54c035bb87051250c2226b46b1b07e28aece1c39/lib/Api/Api.php#L545-L550 |
mautic/api-library | lib/Api/Api.php | Api.deleteBatch | public function deleteBatch(array $ids)
{
$supported = $this->isSupported('deleteBatch');
return (true === $supported) ? $this->makeRequest($this->endpoint.'/batch/delete', array('ids' => $ids), 'DELETE') : $supported;
} | php | public function deleteBatch(array $ids)
{
$supported = $this->isSupported('deleteBatch');
return (true === $supported) ? $this->makeRequest($this->endpoint.'/batch/delete', array('ids' => $ids), 'DELETE') : $supported;
} | [
"public",
"function",
"deleteBatch",
"(",
"array",
"$",
"ids",
")",
"{",
"$",
"supported",
"=",
"$",
"this",
"->",
"isSupported",
"(",
"'deleteBatch'",
")",
";",
"return",
"(",
"true",
"===",
"$",
"supported",
")",
"?",
"$",
"this",
"->",
"makeRequest",
... | Delete a batch of items
@param $ids
@return array|mixed | [
"Delete",
"a",
"batch",
"of",
"items"
] | train | https://github.com/mautic/api-library/blob/54c035bb87051250c2226b46b1b07e28aece1c39/lib/Api/Api.php#L559-L564 |
mautic/api-library | lib/Api/Api.php | Api.isSupported | protected function isSupported($action)
{
if (empty($this->endpointsSupported) || in_array($action, $this->endpointsSupported)) {
return true;
}
return $this->actionNotSupported($action);
} | php | protected function isSupported($action)
{
if (empty($this->endpointsSupported) || in_array($action, $this->endpointsSupported)) {
return true;
}
return $this->actionNotSupported($action);
} | [
"protected",
"function",
"isSupported",
"(",
"$",
"action",
")",
"{",
"if",
"(",
"empty",
"(",
"$",
"this",
"->",
"endpointsSupported",
")",
"||",
"in_array",
"(",
"$",
"action",
",",
"$",
"this",
"->",
"endpointsSupported",
")",
")",
"{",
"return",
"tru... | Verify that a default endpoint is supported by the API
@param $action
@return bool | [
"Verify",
"that",
"a",
"default",
"endpoint",
"is",
"supported",
"by",
"the",
"API"
] | train | https://github.com/mautic/api-library/blob/54c035bb87051250c2226b46b1b07e28aece1c39/lib/Api/Api.php#L596-L603 |
mautic/api-library | lib/Response.php | Response.decodeFromJson | public function decodeFromJson()
{
$parsed = json_decode($this->body, true);
if (is_null($parsed)) {
throw new UnexpectedResponseFormatException($this);
}
return $parsed;
} | php | public function decodeFromJson()
{
$parsed = json_decode($this->body, true);
if (is_null($parsed)) {
throw new UnexpectedResponseFormatException($this);
}
return $parsed;
} | [
"public",
"function",
"decodeFromJson",
"(",
")",
"{",
"$",
"parsed",
"=",
"json_decode",
"(",
"$",
"this",
"->",
"body",
",",
"true",
")",
";",
"if",
"(",
"is_null",
"(",
"$",
"parsed",
")",
")",
"{",
"throw",
"new",
"UnexpectedResponseFormatException",
... | @return array
@throws UnexpectedResponseFormatException | [
"@return",
"array"
] | train | https://github.com/mautic/api-library/blob/54c035bb87051250c2226b46b1b07e28aece1c39/lib/Response.php#L69-L78 |
mautic/api-library | lib/Response.php | Response.decodeFromUrlParams | public function decodeFromUrlParams()
{
if (strpos($this->body, '=') !== false) {
parse_str($this->body, $parsed);
}
if (empty($parsed)) {
throw new UnexpectedResponseFormatException($this);
}
return $parsed;
} | php | public function decodeFromUrlParams()
{
if (strpos($this->body, '=') !== false) {
parse_str($this->body, $parsed);
}
if (empty($parsed)) {
throw new UnexpectedResponseFormatException($this);
}
return $parsed;
} | [
"public",
"function",
"decodeFromUrlParams",
"(",
")",
"{",
"if",
"(",
"strpos",
"(",
"$",
"this",
"->",
"body",
",",
"'='",
")",
"!==",
"false",
")",
"{",
"parse_str",
"(",
"$",
"this",
"->",
"body",
",",
"$",
"parsed",
")",
";",
"}",
"if",
"(",
... | @return array
@throws UnexpectedResponseFormatException | [
"@return",
"array"
] | train | https://github.com/mautic/api-library/blob/54c035bb87051250c2226b46b1b07e28aece1c39/lib/Response.php#L85-L96 |
mautic/api-library | lib/Response.php | Response.saveToFile | public function saveToFile($path)
{
if (!file_exists($path)) {
if (!@mkdir($path) && !is_dir($path)) {
throw new \Exception('Cannot create directory ' . $path);
};
}
$file = tempnam($path, 'mautic_api_');
if (!is_writable($file)) {
throw new \Exception($file.' is not writable');
}
if (!$handle = fopen($file, 'w')) {
throw new \Exception('Cannot open file '.$file);
}
if (fwrite($handle, $this->body) === false) {
throw new \Exception('Cannot write into file '.$file);
}
fclose($handle);
return array(
'file' => $file,
);
} | php | public function saveToFile($path)
{
if (!file_exists($path)) {
if (!@mkdir($path) && !is_dir($path)) {
throw new \Exception('Cannot create directory ' . $path);
};
}
$file = tempnam($path, 'mautic_api_');
if (!is_writable($file)) {
throw new \Exception($file.' is not writable');
}
if (!$handle = fopen($file, 'w')) {
throw new \Exception('Cannot open file '.$file);
}
if (fwrite($handle, $this->body) === false) {
throw new \Exception('Cannot write into file '.$file);
}
fclose($handle);
return array(
'file' => $file,
);
} | [
"public",
"function",
"saveToFile",
"(",
"$",
"path",
")",
"{",
"if",
"(",
"!",
"file_exists",
"(",
"$",
"path",
")",
")",
"{",
"if",
"(",
"!",
"@",
"mkdir",
"(",
"$",
"path",
")",
"&&",
"!",
"is_dir",
"(",
"$",
"path",
")",
")",
"{",
"throw",
... | @param string $path
@return array | [
"@param",
"string",
"$path"
] | train | https://github.com/mautic/api-library/blob/54c035bb87051250c2226b46b1b07e28aece1c39/lib/Response.php#L127-L153 |
mautic/api-library | lib/Auth/ApiAuth.php | ApiAuth.newAuth | public function newAuth($parameters = array(), $authMethod = 'OAuth')
{
$class = 'Mautic\\Auth\\'.$authMethod;
$authObject = new $class();
$reflection = new \ReflectionMethod($class, 'setup');
$pass = array();
foreach ($reflection->getParameters() as $param) {
if (isset($parameters[$param->getName()])) {
$pass[] = $parameters[$param->getName()];
} else {
$pass[] = null;
}
}
$reflection->invokeArgs($authObject, $pass);
return $authObject;
} | php | public function newAuth($parameters = array(), $authMethod = 'OAuth')
{
$class = 'Mautic\\Auth\\'.$authMethod;
$authObject = new $class();
$reflection = new \ReflectionMethod($class, 'setup');
$pass = array();
foreach ($reflection->getParameters() as $param) {
if (isset($parameters[$param->getName()])) {
$pass[] = $parameters[$param->getName()];
} else {
$pass[] = null;
}
}
$reflection->invokeArgs($authObject, $pass);
return $authObject;
} | [
"public",
"function",
"newAuth",
"(",
"$",
"parameters",
"=",
"array",
"(",
")",
",",
"$",
"authMethod",
"=",
"'OAuth'",
")",
"{",
"$",
"class",
"=",
"'Mautic\\\\Auth\\\\'",
".",
"$",
"authMethod",
";",
"$",
"authObject",
"=",
"new",
"$",
"class",
"(",
... | Get an API Auth object
@param array $parameters
@param string $authMethod
@return AuthInterface | [
"Get",
"an",
"API",
"Auth",
"object"
] | train | https://github.com/mautic/api-library/blob/54c035bb87051250c2226b46b1b07e28aece1c39/lib/Auth/ApiAuth.php#L44-L63 |
mautic/api-library | lib/Auth/AbstractAuth.php | AbstractAuth.makeRequest | public function makeRequest($url, array $parameters = array(), $method = 'GET', array $settings = array())
{
$this->log('makeRequest('.$url.', '.http_build_query($parameters).', '.$method.',...)');
list($url, $parameters) = $this->separateUrlParams($url, $parameters);
//make sure $method is capitalized for congruency
$method = strtoupper($method);
$headers = (isset($settings['headers']) && is_array($settings['headers'])) ? $settings['headers'] : array();
list($headers, $parameters) = $this->prepareRequest($url, $headers, $parameters, $method, $settings);
//Set default CURL options
$options = array(
CURLOPT_RETURNTRANSFER => true,
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_HEADER => true
);
if ($this->_curlTimeout !== null) {
$options[CURLOPT_TIMEOUT] = $this->_curlTimeout;
}
// CURLOPT_FOLLOWLOCATION cannot be activated when an open_basedir is set
$options[CURLOPT_FOLLOWLOCATION] = (ini_get('open_basedir')) ? false : true;
//Set custom REST method if not GET or POST
if (!in_array($method, array('GET', 'POST'))) {
$options[CURLOPT_CUSTOMREQUEST] = $method;
}
//Set post fields for POST/PUT/PATCH requests
$isPost = false;
if (in_array($method, array('POST', 'PUT', 'PATCH'))) {
$isPost = true;
// Set file to upload
// Sending file data requires an array to set
// the Content-Type header to multipart/form-data
if (!empty($parameters['file']) && file_exists($parameters['file'])) {
$options[CURLOPT_INFILESIZE] = filesize($parameters['file']);
$parameters['file'] = $this->createCurlFile($parameters['file']);
$headers[] = "Content-Type: multipart/form-data";
} else {
$parameters = http_build_query($parameters, '', '&');
}
$options[CURLOPT_POST] = true;
$options[CURLOPT_POSTFIELDS] = $parameters;
$this->log('Posted parameters = '.print_r($parameters, true));
}
$query = $this->getQueryParameters($isPost, $parameters);
$this->log('Query parameters = '.print_r($query, true));
//Create a query string for GET/DELETE requests
if (count($query) > 0) {
$queryGlue = strpos($url, '?') === false ? '?' : '&';
$url = $url.$queryGlue.http_build_query($query, '', '&');
$this->log('URL updated to '.$url);
}
// Set the URL
$options[CURLOPT_URL] = $url;
$headers[] = 'Accept: application/json';
$options[CURLOPT_HTTPHEADER] = $headers;
//Make CURL request
$curl = curl_init();
curl_setopt_array($curl, $options);
$response = new Response(curl_exec($curl), curl_getinfo($curl));
$this->_httpResponseHeaders = $response->getHeaders();
$this->_httpResponseInfo = $response->getInfo();
curl_close($curl);
if ($this->_debug) {
$_SESSION['oauth']['debug']['info'] = $response->getInfo();
$_SESSION['oauth']['debug']['returnedHeaders'] = $response->getHeaders();
$_SESSION['oauth']['debug']['returnedBody'] = $response->getBody();
}
// Handle zip file response
if ($response->isZip()) {
$temporaryFilePath = isset($settings['temporaryFilePath']) ? $settings['temporaryFilePath'] : sys_get_temp_dir();
return $response->saveToFile($temporaryFilePath);
} else {
return $response->getDecodedBody();
}
} | php | public function makeRequest($url, array $parameters = array(), $method = 'GET', array $settings = array())
{
$this->log('makeRequest('.$url.', '.http_build_query($parameters).', '.$method.',...)');
list($url, $parameters) = $this->separateUrlParams($url, $parameters);
//make sure $method is capitalized for congruency
$method = strtoupper($method);
$headers = (isset($settings['headers']) && is_array($settings['headers'])) ? $settings['headers'] : array();
list($headers, $parameters) = $this->prepareRequest($url, $headers, $parameters, $method, $settings);
//Set default CURL options
$options = array(
CURLOPT_RETURNTRANSFER => true,
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_HEADER => true
);
if ($this->_curlTimeout !== null) {
$options[CURLOPT_TIMEOUT] = $this->_curlTimeout;
}
// CURLOPT_FOLLOWLOCATION cannot be activated when an open_basedir is set
$options[CURLOPT_FOLLOWLOCATION] = (ini_get('open_basedir')) ? false : true;
//Set custom REST method if not GET or POST
if (!in_array($method, array('GET', 'POST'))) {
$options[CURLOPT_CUSTOMREQUEST] = $method;
}
//Set post fields for POST/PUT/PATCH requests
$isPost = false;
if (in_array($method, array('POST', 'PUT', 'PATCH'))) {
$isPost = true;
// Set file to upload
// Sending file data requires an array to set
// the Content-Type header to multipart/form-data
if (!empty($parameters['file']) && file_exists($parameters['file'])) {
$options[CURLOPT_INFILESIZE] = filesize($parameters['file']);
$parameters['file'] = $this->createCurlFile($parameters['file']);
$headers[] = "Content-Type: multipart/form-data";
} else {
$parameters = http_build_query($parameters, '', '&');
}
$options[CURLOPT_POST] = true;
$options[CURLOPT_POSTFIELDS] = $parameters;
$this->log('Posted parameters = '.print_r($parameters, true));
}
$query = $this->getQueryParameters($isPost, $parameters);
$this->log('Query parameters = '.print_r($query, true));
//Create a query string for GET/DELETE requests
if (count($query) > 0) {
$queryGlue = strpos($url, '?') === false ? '?' : '&';
$url = $url.$queryGlue.http_build_query($query, '', '&');
$this->log('URL updated to '.$url);
}
// Set the URL
$options[CURLOPT_URL] = $url;
$headers[] = 'Accept: application/json';
$options[CURLOPT_HTTPHEADER] = $headers;
//Make CURL request
$curl = curl_init();
curl_setopt_array($curl, $options);
$response = new Response(curl_exec($curl), curl_getinfo($curl));
$this->_httpResponseHeaders = $response->getHeaders();
$this->_httpResponseInfo = $response->getInfo();
curl_close($curl);
if ($this->_debug) {
$_SESSION['oauth']['debug']['info'] = $response->getInfo();
$_SESSION['oauth']['debug']['returnedHeaders'] = $response->getHeaders();
$_SESSION['oauth']['debug']['returnedBody'] = $response->getBody();
}
// Handle zip file response
if ($response->isZip()) {
$temporaryFilePath = isset($settings['temporaryFilePath']) ? $settings['temporaryFilePath'] : sys_get_temp_dir();
return $response->saveToFile($temporaryFilePath);
} else {
return $response->getDecodedBody();
}
} | [
"public",
"function",
"makeRequest",
"(",
"$",
"url",
",",
"array",
"$",
"parameters",
"=",
"array",
"(",
")",
",",
"$",
"method",
"=",
"'GET'",
",",
"array",
"$",
"settings",
"=",
"array",
"(",
")",
")",
"{",
"$",
"this",
"->",
"log",
"(",
"'makeR... | {@inheritdoc}
@throws UnexpectedResponseFormatException|Exception | [
"{",
"@inheritdoc",
"}"
] | train | https://github.com/mautic/api-library/blob/54c035bb87051250c2226b46b1b07e28aece1c39/lib/Auth/AbstractAuth.php#L108-L200 |
mautic/api-library | lib/Auth/AbstractAuth.php | AbstractAuth.createCurlFile | protected function createCurlFile($filename, $mimetype = '', $postname = '')
{
if (!function_exists('curl_file_create')) {
// For PHP < 5.5
return "@$filename;filename="
.($postname ?: basename($filename))
.($mimetype ? ";type=$mimetype" : '');
}
// For PHP >= 5.5
return curl_file_create($filename, $mimetype, $postname);
} | php | protected function createCurlFile($filename, $mimetype = '', $postname = '')
{
if (!function_exists('curl_file_create')) {
// For PHP < 5.5
return "@$filename;filename="
.($postname ?: basename($filename))
.($mimetype ? ";type=$mimetype" : '');
}
// For PHP >= 5.5
return curl_file_create($filename, $mimetype, $postname);
} | [
"protected",
"function",
"createCurlFile",
"(",
"$",
"filename",
",",
"$",
"mimetype",
"=",
"''",
",",
"$",
"postname",
"=",
"''",
")",
"{",
"if",
"(",
"!",
"function_exists",
"(",
"'curl_file_create'",
")",
")",
"{",
"// For PHP < 5.5",
"return",
"\"@$filen... | Build the CURL file based on PHP version
@param string $filename
@param string $mimetype
@param string $postname
@return string|\CURLFile | [
"Build",
"the",
"CURL",
"file",
"based",
"on",
"PHP",
"version"
] | train | https://github.com/mautic/api-library/blob/54c035bb87051250c2226b46b1b07e28aece1c39/lib/Auth/AbstractAuth.php#L225-L236 |
mautic/api-library | lib/Auth/AbstractAuth.php | AbstractAuth.parseHeaders | protected function parseHeaders($headersStr)
{
$headersArr = array();
$headersHlpr = explode("\r\n", $headersStr);
foreach ($headersHlpr as $header) {
$pos = strpos($header, ':');
if ($pos === false) {
$headersArr[] = trim($header);
} else {
$headersArr[trim(substr($header, 0, $pos))] = trim(substr($header, ($pos + 1)));
}
}
return $headersArr;
} | php | protected function parseHeaders($headersStr)
{
$headersArr = array();
$headersHlpr = explode("\r\n", $headersStr);
foreach ($headersHlpr as $header) {
$pos = strpos($header, ':');
if ($pos === false) {
$headersArr[] = trim($header);
} else {
$headersArr[trim(substr($header, 0, $pos))] = trim(substr($header, ($pos + 1)));
}
}
return $headersArr;
} | [
"protected",
"function",
"parseHeaders",
"(",
"$",
"headersStr",
")",
"{",
"$",
"headersArr",
"=",
"array",
"(",
")",
";",
"$",
"headersHlpr",
"=",
"explode",
"(",
"\"\\r\\n\"",
",",
"$",
"headersStr",
")",
";",
"foreach",
"(",
"$",
"headersHlpr",
"as",
... | Build the HTTP response array out of the headers string
@param string $headersStr
@return array | [
"Build",
"the",
"HTTP",
"response",
"array",
"out",
"of",
"the",
"headers",
"string"
] | train | https://github.com/mautic/api-library/blob/54c035bb87051250c2226b46b1b07e28aece1c39/lib/Auth/AbstractAuth.php#L266-L281 |
mautic/api-library | lib/Auth/AbstractAuth.php | AbstractAuth.separateUrlParams | protected function separateUrlParams($url, $params)
{
$a = parse_url($url);
if (!empty($a['query'])) {
parse_str($a['query'], $qparts);
$cleanParams = array();
foreach ($qparts as $k => $v) {
$cleanParams[$k] = $v ? $v : '';
}
$params = array_merge($params, $cleanParams);
$urlParts = explode('?', $url, 2);
$url = $urlParts[0];
}
return array($url, $params);
} | php | protected function separateUrlParams($url, $params)
{
$a = parse_url($url);
if (!empty($a['query'])) {
parse_str($a['query'], $qparts);
$cleanParams = array();
foreach ($qparts as $k => $v) {
$cleanParams[$k] = $v ? $v : '';
}
$params = array_merge($params, $cleanParams);
$urlParts = explode('?', $url, 2);
$url = $urlParts[0];
}
return array($url, $params);
} | [
"protected",
"function",
"separateUrlParams",
"(",
"$",
"url",
",",
"$",
"params",
")",
"{",
"$",
"a",
"=",
"parse_url",
"(",
"$",
"url",
")",
";",
"if",
"(",
"!",
"empty",
"(",
"$",
"a",
"[",
"'query'",
"]",
")",
")",
"{",
"parse_str",
"(",
"$",... | Separates parameters from base URL
@param $url
@param $params
@return array | [
"Separates",
"parameters",
"from",
"base",
"URL"
] | train | https://github.com/mautic/api-library/blob/54c035bb87051250c2226b46b1b07e28aece1c39/lib/Auth/AbstractAuth.php#L291-L307 |
mautic/api-library | lib/Auth/OAuth.php | OAuth.getAccessTokenData | public function getAccessTokenData()
{
if ($this->isOauth1()) {
return array(
'access_token' => $this->_access_token,
'access_token_secret' => $this->_access_token_secret,
'expires' => $this->_expires,
);
}
return array(
'access_token' => $this->_access_token,
'expires' => $this->_expires,
'token_type' => $this->_token_type,
'refresh_token' => $this->_refresh_token
);
} | php | public function getAccessTokenData()
{
if ($this->isOauth1()) {
return array(
'access_token' => $this->_access_token,
'access_token_secret' => $this->_access_token_secret,
'expires' => $this->_expires,
);
}
return array(
'access_token' => $this->_access_token,
'expires' => $this->_expires,
'token_type' => $this->_token_type,
'refresh_token' => $this->_refresh_token
);
} | [
"public",
"function",
"getAccessTokenData",
"(",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"isOauth1",
"(",
")",
")",
"{",
"return",
"array",
"(",
"'access_token'",
"=>",
"$",
"this",
"->",
"_access_token",
",",
"'access_token_secret'",
"=>",
"$",
"this",
"-... | Returns access token data
@return array | [
"Returns",
"access",
"token",
"data"
] | train | https://github.com/mautic/api-library/blob/54c035bb87051250c2226b46b1b07e28aece1c39/lib/Auth/OAuth.php#L140-L156 |
mautic/api-library | lib/Auth/OAuth.php | OAuth.isAuthorized | public function isAuthorized()
{
//Check for existing access token
if (!empty($this->_request_token_url)) {
if (strlen($this->_access_token) > 0 && strlen($this->_access_token_secret) > 0) {
return true;
}
}
//Check to see if token in session has expired
if (!empty($this->_expires) && $this->_expires < time()) {
return false;
}
if (strlen($this->_access_token) > 0) {
return true;
}
return false;
} | php | public function isAuthorized()
{
//Check for existing access token
if (!empty($this->_request_token_url)) {
if (strlen($this->_access_token) > 0 && strlen($this->_access_token_secret) > 0) {
return true;
}
}
//Check to see if token in session has expired
if (!empty($this->_expires) && $this->_expires < time()) {
return false;
}
if (strlen($this->_access_token) > 0) {
return true;
}
return false;
} | [
"public",
"function",
"isAuthorized",
"(",
")",
"{",
"//Check for existing access token",
"if",
"(",
"!",
"empty",
"(",
"$",
"this",
"->",
"_request_token_url",
")",
")",
"{",
"if",
"(",
"strlen",
"(",
"$",
"this",
"->",
"_access_token",
")",
">",
"0",
"&&... | {@inheritdoc} | [
"{"
] | train | https://github.com/mautic/api-library/blob/54c035bb87051250c2226b46b1b07e28aece1c39/lib/Auth/OAuth.php#L181-L200 |
mautic/api-library | lib/Auth/OAuth.php | OAuth.setAccessTokenDetails | public function setAccessTokenDetails(array $accessTokenDetails)
{
$this->_access_token = isset($accessTokenDetails['access_token']) ? $accessTokenDetails['access_token'] : null;
$this->_access_token_secret = isset($accessTokenDetails['access_token_secret']) ? $accessTokenDetails['access_token_secret'] : null;
$this->_expires = isset($accessTokenDetails['expires']) ? $accessTokenDetails['expires'] : null;
$this->_refresh_token = isset($accessTokenDetails['refresh_token']) ? $accessTokenDetails['refresh_token'] : null;
return $this;
} | php | public function setAccessTokenDetails(array $accessTokenDetails)
{
$this->_access_token = isset($accessTokenDetails['access_token']) ? $accessTokenDetails['access_token'] : null;
$this->_access_token_secret = isset($accessTokenDetails['access_token_secret']) ? $accessTokenDetails['access_token_secret'] : null;
$this->_expires = isset($accessTokenDetails['expires']) ? $accessTokenDetails['expires'] : null;
$this->_refresh_token = isset($accessTokenDetails['refresh_token']) ? $accessTokenDetails['refresh_token'] : null;
return $this;
} | [
"public",
"function",
"setAccessTokenDetails",
"(",
"array",
"$",
"accessTokenDetails",
")",
"{",
"$",
"this",
"->",
"_access_token",
"=",
"isset",
"(",
"$",
"accessTokenDetails",
"[",
"'access_token'",
"]",
")",
"?",
"$",
"accessTokenDetails",
"[",
"'access_token... | Set an existing/already retrieved access token
@param array $accessTokenDetails
@return $this | [
"Set",
"an",
"existing",
"/",
"already",
"retrieved",
"access",
"token"
] | train | https://github.com/mautic/api-library/blob/54c035bb87051250c2226b46b1b07e28aece1c39/lib/Auth/OAuth.php#L209-L217 |
mautic/api-library | lib/Auth/OAuth.php | OAuth.setScope | public function setScope($scope)
{
if (!is_array($scope)) {
$this->_scope = explode(',', $scope);
} else {
$this->_scope = $scope;
}
return $this;
} | php | public function setScope($scope)
{
if (!is_array($scope)) {
$this->_scope = explode(',', $scope);
} else {
$this->_scope = $scope;
}
return $this;
} | [
"public",
"function",
"setScope",
"(",
"$",
"scope",
")",
"{",
"if",
"(",
"!",
"is_array",
"(",
"$",
"scope",
")",
")",
"{",
"$",
"this",
"->",
"_scope",
"=",
"explode",
"(",
"','",
",",
"$",
"scope",
")",
";",
"}",
"else",
"{",
"$",
"this",
"-... | Set OAuth2 scope
@param array|string $scope
@return $this | [
"Set",
"OAuth2",
"scope"
] | train | https://github.com/mautic/api-library/blob/54c035bb87051250c2226b46b1b07e28aece1c39/lib/Auth/OAuth.php#L282-L291 |
mautic/api-library | lib/Auth/OAuth.php | OAuth.validateAccessToken | public function validateAccessToken($redirect = true)
{
$this->_do_not_redirect = !$redirect;
$this->log('validateAccessToken()');
//Check to see if token in session has expired
if (!empty($this->_expires) && $this->_expires < time()) {
$this->log('access token expired so reauthorize');
if (strlen($this->_refresh_token) > 0) {
//use a refresh token to get a new token
return $this->requestAccessToken();
}
//Reauthorize
$this->authorize($this->_scope);
return false;
}
//Check for existing access token
if (strlen($this->_access_token) > 0) {
$this->log('has access token');
return true;
}
//Reauthorize if no token was found
if (strlen($this->_access_token) == 0) {
$this->log('access token empty so authorize');
//OAuth flows
if ($this->isOauth1()) {
//OAuth 1.0
$this->log('authorizing with OAuth1.0a spec');
//Request token and authorize app
if (!isset($_GET['oauth_token']) && !isset($_GET['oauth_verifier'])) {
$this->log('initializing authorization');
//Request token
$this->requestToken();
//Authorize token
$this->authorize();
return false;
}
//Request access token
if ($_GET['oauth_token'] != $_SESSION['oauth']['token']) {
unset($_SESSION['oauth']['token'], $_SESSION['oauth']['token_secret']);
return false;
}
$this->requestAccessToken();
unset($_SESSION['oauth']['token'], $_SESSION['oauth']['token_secret']);
return true;
}
//OAuth 2.0
$this->log('authorizing with OAuth2 spec');
//Authorize app
if (!isset($_GET['state']) && !isset($_GET['code'])) {
$this->authorize($this->_scope);
return false;
}
if ($this->_debug) {
$_SESSION['oauth']['debug']['received_state'] = $_GET['state'];
}
//Request an access token
if ($_GET['state'] != $_SESSION['oauth']['state']) {
unset($_SESSION['oauth']['state']);
return false;
}
unset($_SESSION['oauth']['state']);
$this->requestAccessToken('POST', array(), 'json');
return true;
}
return false;
} | php | public function validateAccessToken($redirect = true)
{
$this->_do_not_redirect = !$redirect;
$this->log('validateAccessToken()');
//Check to see if token in session has expired
if (!empty($this->_expires) && $this->_expires < time()) {
$this->log('access token expired so reauthorize');
if (strlen($this->_refresh_token) > 0) {
//use a refresh token to get a new token
return $this->requestAccessToken();
}
//Reauthorize
$this->authorize($this->_scope);
return false;
}
//Check for existing access token
if (strlen($this->_access_token) > 0) {
$this->log('has access token');
return true;
}
//Reauthorize if no token was found
if (strlen($this->_access_token) == 0) {
$this->log('access token empty so authorize');
//OAuth flows
if ($this->isOauth1()) {
//OAuth 1.0
$this->log('authorizing with OAuth1.0a spec');
//Request token and authorize app
if (!isset($_GET['oauth_token']) && !isset($_GET['oauth_verifier'])) {
$this->log('initializing authorization');
//Request token
$this->requestToken();
//Authorize token
$this->authorize();
return false;
}
//Request access token
if ($_GET['oauth_token'] != $_SESSION['oauth']['token']) {
unset($_SESSION['oauth']['token'], $_SESSION['oauth']['token_secret']);
return false;
}
$this->requestAccessToken();
unset($_SESSION['oauth']['token'], $_SESSION['oauth']['token_secret']);
return true;
}
//OAuth 2.0
$this->log('authorizing with OAuth2 spec');
//Authorize app
if (!isset($_GET['state']) && !isset($_GET['code'])) {
$this->authorize($this->_scope);
return false;
}
if ($this->_debug) {
$_SESSION['oauth']['debug']['received_state'] = $_GET['state'];
}
//Request an access token
if ($_GET['state'] != $_SESSION['oauth']['state']) {
unset($_SESSION['oauth']['state']);
return false;
}
unset($_SESSION['oauth']['state']);
$this->requestAccessToken('POST', array(), 'json');
return true;
}
return false;
} | [
"public",
"function",
"validateAccessToken",
"(",
"$",
"redirect",
"=",
"true",
")",
"{",
"$",
"this",
"->",
"_do_not_redirect",
"=",
"!",
"$",
"redirect",
";",
"$",
"this",
"->",
"log",
"(",
"'validateAccessToken()'",
")",
";",
"//Check to see if token in sessi... | Validate existing access token
@param bool $redirect
@return bool
@throws IncorrectParametersReturnedException | [
"Validate",
"existing",
"access",
"token"
] | train | https://github.com/mautic/api-library/blob/54c035bb87051250c2226b46b1b07e28aece1c39/lib/Auth/OAuth.php#L367-L456 |
mautic/api-library | lib/Auth/OAuth.php | OAuth.authorize | protected function authorize(array $scope = array(), $scope_separator = ',', $attach = null)
{
$authUrl = $this->_authorize_url;
//Build authorization URL
if ($this->isOauth1()) {
//OAuth 1.0
$authUrl .= '?oauth_token='.$_SESSION['oauth']['token'];
if (!empty($this->_callback)) {
$authUrl .= '&oauth_callback='.urlencode($this->_callback);
}
} else {
//OAuth 2.0
$authUrl .= '?client_id='.$this->_client_id.'&redirect_uri='.urlencode($this->_callback);
$state = md5(time().mt_rand());
$_SESSION['oauth']['state'] = $state;
if ($this->_debug) {
$_SESSION['oauth']['debug']['generated_state'] = $state;
}
$authUrl .= '&state='.$state.'&scope='.implode($scope_separator, $scope).$attach;
$authUrl .= '&response_type='.$this->_redirect_type;
}
$this->log('redirecting to auth url '.$authUrl);
//Redirect to authorization URL
if (!$this->_do_not_redirect) {
header('Location: '.$authUrl);
exit;
} else {
throw new AuthorizationRequiredException($authUrl);
}
} | php | protected function authorize(array $scope = array(), $scope_separator = ',', $attach = null)
{
$authUrl = $this->_authorize_url;
//Build authorization URL
if ($this->isOauth1()) {
//OAuth 1.0
$authUrl .= '?oauth_token='.$_SESSION['oauth']['token'];
if (!empty($this->_callback)) {
$authUrl .= '&oauth_callback='.urlencode($this->_callback);
}
} else {
//OAuth 2.0
$authUrl .= '?client_id='.$this->_client_id.'&redirect_uri='.urlencode($this->_callback);
$state = md5(time().mt_rand());
$_SESSION['oauth']['state'] = $state;
if ($this->_debug) {
$_SESSION['oauth']['debug']['generated_state'] = $state;
}
$authUrl .= '&state='.$state.'&scope='.implode($scope_separator, $scope).$attach;
$authUrl .= '&response_type='.$this->_redirect_type;
}
$this->log('redirecting to auth url '.$authUrl);
//Redirect to authorization URL
if (!$this->_do_not_redirect) {
header('Location: '.$authUrl);
exit;
} else {
throw new AuthorizationRequiredException($authUrl);
}
} | [
"protected",
"function",
"authorize",
"(",
"array",
"$",
"scope",
"=",
"array",
"(",
")",
",",
"$",
"scope_separator",
"=",
"','",
",",
"$",
"attach",
"=",
"null",
")",
"{",
"$",
"authUrl",
"=",
"$",
"this",
"->",
"_authorize_url",
";",
"//Build authoriz... | Authorize app
@param array $scope
@param string $scope_separator
@param null $attach
@throws AuthorizationRequiredException | [
"Authorize",
"app"
] | train | https://github.com/mautic/api-library/blob/54c035bb87051250c2226b46b1b07e28aece1c39/lib/Auth/OAuth.php#L467-L502 |
mautic/api-library | lib/Auth/OAuth.php | OAuth.getQueryParameters | protected function getQueryParameters($isPost, $parameters)
{
$query = parent::getQueryParameters($isPost, $parameters);
if (isset($parameters['file'])) {
// Mautic's OAuth2 server does not recognize multipart forms so we have to append the access token as part of the URL
$query['access_token'] = $parameters['access_token'];
}
return $query;
} | php | protected function getQueryParameters($isPost, $parameters)
{
$query = parent::getQueryParameters($isPost, $parameters);
if (isset($parameters['file'])) {
// Mautic's OAuth2 server does not recognize multipart forms so we have to append the access token as part of the URL
$query['access_token'] = $parameters['access_token'];
}
return $query;
} | [
"protected",
"function",
"getQueryParameters",
"(",
"$",
"isPost",
",",
"$",
"parameters",
")",
"{",
"$",
"query",
"=",
"parent",
"::",
"getQueryParameters",
"(",
"$",
"isPost",
",",
"$",
"parameters",
")",
";",
"if",
"(",
"isset",
"(",
"$",
"parameters",
... | @param $isPost
@param $parameters
@return array | [
"@param",
"$isPost",
"@param",
"$parameters"
] | train | https://github.com/mautic/api-library/blob/54c035bb87051250c2226b46b1b07e28aece1c39/lib/Auth/OAuth.php#L510-L520 |
mautic/api-library | lib/Auth/OAuth.php | OAuth.prepareRequest | protected function prepareRequest($url, array $headers, array $parameters, $method, array $settings)
{
$includeCallback = (isset($settings['includeCallback'])) ? $settings['includeCallback'] : false;
$includeVerifier = (isset($settings['includeVerifier'])) ? $settings['includeVerifier'] : false;
//Set OAuth parameters/headers
if ($this->isOauth1()) {
//OAuth 1.0
$this->log('making request using OAuth1.0a spec');
//Get standard OAuth headers
$oAuthHeaders = $this->getOauthHeaders($includeCallback);
if ($includeVerifier && isset($_GET['oauth_verifier'])) {
$oAuthHeaders['oauth_verifier'] = $_GET['oauth_verifier'];
if ($this->_debug) {
$_SESSION['oauth']['debug']['oauth_verifier'] = $_GET['oauth_verifier'];
}
}
//Add the parameters
$oAuthHeaders = array_merge($oAuthHeaders, $parameters);
$base_info = $this->buildBaseString($url, $method, $oAuthHeaders);
$composite_key = $this->getCompositeKey();
$oAuthHeaders['oauth_signature'] = base64_encode(hash_hmac('sha1', $base_info, $composite_key, true));
$headers[] = $this->buildAuthorizationHeader($oAuthHeaders);
$headers[] = 'Expect:';
if ($this->_debug) {
$_SESSION['oauth']['debug']['basestring'] = $base_info;
$_SESSION['oauth']['debug']['headers'] = $headers;
}
} else {
//OAuth 2.0
$this->log('making request using OAuth2 spec');
$parameters['access_token'] = $this->_access_token;
}
return array($headers, $parameters);
} | php | protected function prepareRequest($url, array $headers, array $parameters, $method, array $settings)
{
$includeCallback = (isset($settings['includeCallback'])) ? $settings['includeCallback'] : false;
$includeVerifier = (isset($settings['includeVerifier'])) ? $settings['includeVerifier'] : false;
//Set OAuth parameters/headers
if ($this->isOauth1()) {
//OAuth 1.0
$this->log('making request using OAuth1.0a spec');
//Get standard OAuth headers
$oAuthHeaders = $this->getOauthHeaders($includeCallback);
if ($includeVerifier && isset($_GET['oauth_verifier'])) {
$oAuthHeaders['oauth_verifier'] = $_GET['oauth_verifier'];
if ($this->_debug) {
$_SESSION['oauth']['debug']['oauth_verifier'] = $_GET['oauth_verifier'];
}
}
//Add the parameters
$oAuthHeaders = array_merge($oAuthHeaders, $parameters);
$base_info = $this->buildBaseString($url, $method, $oAuthHeaders);
$composite_key = $this->getCompositeKey();
$oAuthHeaders['oauth_signature'] = base64_encode(hash_hmac('sha1', $base_info, $composite_key, true));
$headers[] = $this->buildAuthorizationHeader($oAuthHeaders);
$headers[] = 'Expect:';
if ($this->_debug) {
$_SESSION['oauth']['debug']['basestring'] = $base_info;
$_SESSION['oauth']['debug']['headers'] = $headers;
}
} else {
//OAuth 2.0
$this->log('making request using OAuth2 spec');
$parameters['access_token'] = $this->_access_token;
}
return array($headers, $parameters);
} | [
"protected",
"function",
"prepareRequest",
"(",
"$",
"url",
",",
"array",
"$",
"headers",
",",
"array",
"$",
"parameters",
",",
"$",
"method",
",",
"array",
"$",
"settings",
")",
"{",
"$",
"includeCallback",
"=",
"(",
"isset",
"(",
"$",
"settings",
"[",
... | @param $url
@param array $headers
@param array $parameters
@param array $method
@param array $settings
@return array | [
"@param",
"$url",
"@param",
"array",
"$headers",
"@param",
"array",
"$parameters",
"@param",
"array",
"$method",
"@param",
"array",
"$settings"
] | train | https://github.com/mautic/api-library/blob/54c035bb87051250c2226b46b1b07e28aece1c39/lib/Auth/OAuth.php#L563-L604 |
mautic/api-library | lib/Auth/OAuth.php | OAuth.requestAccessToken | protected function requestAccessToken($method = 'POST', array $params = array(), $responseType = 'flat')
{
$this->log('requestAccessToken()');
//Set OAuth flow parameters
if ($this->isOauth1()) {
//OAuth 1.0
$this->log('using OAuth1.0a spec');
$parameters = array('oauth_verifier' => $_GET['oauth_verifier']);
$parameters = array_merge($parameters, $params);
} else {
//OAuth 2.0
$this->log('using OAuth2 spec');
$parameters = array(
'client_id' => $this->_client_id,
'redirect_uri' => $this->_callback,
'client_secret' => $this->_client_secret,
'grant_type' => 'authorization_code'
);
if (isset($_GET['code'])) {
$parameters['code'] = $_GET['code'];
}
if (strlen($this->_refresh_token) > 0) {
$this->log('Using refresh token');
$parameters['grant_type'] = 'refresh_token';
$parameters['refresh_token'] = $this->_refresh_token;
}
$parameters = array_merge($parameters, $params);
}
//Make the request
$settings = array(
'responseType' => $responseType,
'includeCallback' => true,
'includeVerifier' => true
);
$params = $this->makeRequest($this->_access_token_url, $parameters, $method, $settings);
//Add the token and secret to session
if (is_array($params)) {
if ($this->isOauth1()) {
//OAuth 1.0a
if (isset($params['oauth_token']) && isset($params['oauth_token_secret'])) {
$this->log('access token set as '.$params['oauth_token']);
$this->_access_token = $params['oauth_token'];
$this->_access_token_secret = $params['oauth_token_secret'];
$this->_access_token_updated = true;
if ($this->_debug) {
$_SESSION['oauth']['debug']['tokens']['access_token'] = $params['oauth_token'];
$_SESSION['oauth']['debug']['tokens']['access_token_secret'] = $params['oauth_token_secret'];
}
return true;
}
} else {
//OAuth 2.0
if (isset($params['access_token']) && isset($params['expires_in'])) {
$this->log('access token set as '.$params['access_token']);
$this->_access_token = $params['access_token'];
$this->_expires = time() + $params['expires_in'];
$this->_token_type = (isset($params['token_type'])) ? $params['token_type'] : null;
$this->_refresh_token = (isset($params['refresh_token'])) ? $params['refresh_token'] : null;
$this->_access_token_updated = true;
if ($this->_debug) {
$_SESSION['oauth']['debug']['tokens']['access_token'] = $params['access_token'];
$_SESSION['oauth']['debug']['tokens']['expires_in'] = $params['expires_in'];
$_SESSION['oauth']['debug']['tokens']['token_type'] = $params['token_type'];
$_SESSION['oauth']['debug']['tokens']['refresh_token'] = $params['refresh_token'];
}
return true;
}
}
}
$this->log('response did not have an access token');
if ($this->_debug) {
$_SESSION['oauth']['debug']['response'] = $params;
}
if (is_array($params)) {
if (isset($params['errors'])) {
$errors = array();
foreach ($params['errors'] as $error) {
$errors[] = $error['message'];
}
$response = implode("; ", $errors);
} elseif (isset($params['error'])) {
// @deprecated support for pre Mautic 2.6.0
if (is_array($params['error'])) {
if (isset($params['error']['message'])) {
$response = $params['error']['message'];
} else {
$response = print_r($params['error'], true);
}
} elseif (isset($params['error_description'])) {
$response = $params['error_description'];
} else {
$response = $params['error'];
}
} else {
$response = print_r($params, true);
}
} else {
$response = $params;
}
throw new IncorrectParametersReturnedException('Incorrect access token parameters returned: '.$response);
} | php | protected function requestAccessToken($method = 'POST', array $params = array(), $responseType = 'flat')
{
$this->log('requestAccessToken()');
//Set OAuth flow parameters
if ($this->isOauth1()) {
//OAuth 1.0
$this->log('using OAuth1.0a spec');
$parameters = array('oauth_verifier' => $_GET['oauth_verifier']);
$parameters = array_merge($parameters, $params);
} else {
//OAuth 2.0
$this->log('using OAuth2 spec');
$parameters = array(
'client_id' => $this->_client_id,
'redirect_uri' => $this->_callback,
'client_secret' => $this->_client_secret,
'grant_type' => 'authorization_code'
);
if (isset($_GET['code'])) {
$parameters['code'] = $_GET['code'];
}
if (strlen($this->_refresh_token) > 0) {
$this->log('Using refresh token');
$parameters['grant_type'] = 'refresh_token';
$parameters['refresh_token'] = $this->_refresh_token;
}
$parameters = array_merge($parameters, $params);
}
//Make the request
$settings = array(
'responseType' => $responseType,
'includeCallback' => true,
'includeVerifier' => true
);
$params = $this->makeRequest($this->_access_token_url, $parameters, $method, $settings);
//Add the token and secret to session
if (is_array($params)) {
if ($this->isOauth1()) {
//OAuth 1.0a
if (isset($params['oauth_token']) && isset($params['oauth_token_secret'])) {
$this->log('access token set as '.$params['oauth_token']);
$this->_access_token = $params['oauth_token'];
$this->_access_token_secret = $params['oauth_token_secret'];
$this->_access_token_updated = true;
if ($this->_debug) {
$_SESSION['oauth']['debug']['tokens']['access_token'] = $params['oauth_token'];
$_SESSION['oauth']['debug']['tokens']['access_token_secret'] = $params['oauth_token_secret'];
}
return true;
}
} else {
//OAuth 2.0
if (isset($params['access_token']) && isset($params['expires_in'])) {
$this->log('access token set as '.$params['access_token']);
$this->_access_token = $params['access_token'];
$this->_expires = time() + $params['expires_in'];
$this->_token_type = (isset($params['token_type'])) ? $params['token_type'] : null;
$this->_refresh_token = (isset($params['refresh_token'])) ? $params['refresh_token'] : null;
$this->_access_token_updated = true;
if ($this->_debug) {
$_SESSION['oauth']['debug']['tokens']['access_token'] = $params['access_token'];
$_SESSION['oauth']['debug']['tokens']['expires_in'] = $params['expires_in'];
$_SESSION['oauth']['debug']['tokens']['token_type'] = $params['token_type'];
$_SESSION['oauth']['debug']['tokens']['refresh_token'] = $params['refresh_token'];
}
return true;
}
}
}
$this->log('response did not have an access token');
if ($this->_debug) {
$_SESSION['oauth']['debug']['response'] = $params;
}
if (is_array($params)) {
if (isset($params['errors'])) {
$errors = array();
foreach ($params['errors'] as $error) {
$errors[] = $error['message'];
}
$response = implode("; ", $errors);
} elseif (isset($params['error'])) {
// @deprecated support for pre Mautic 2.6.0
if (is_array($params['error'])) {
if (isset($params['error']['message'])) {
$response = $params['error']['message'];
} else {
$response = print_r($params['error'], true);
}
} elseif (isset($params['error_description'])) {
$response = $params['error_description'];
} else {
$response = $params['error'];
}
} else {
$response = print_r($params, true);
}
} else {
$response = $params;
}
throw new IncorrectParametersReturnedException('Incorrect access token parameters returned: '.$response);
} | [
"protected",
"function",
"requestAccessToken",
"(",
"$",
"method",
"=",
"'POST'",
",",
"array",
"$",
"params",
"=",
"array",
"(",
")",
",",
"$",
"responseType",
"=",
"'flat'",
")",
"{",
"$",
"this",
"->",
"log",
"(",
"'requestAccessToken()'",
")",
";",
"... | Request access token
@param string $method
@param array $params
@param string $responseType
@return bool
@throws IncorrectParametersReturnedException | [
"Request",
"access",
"token"
] | train | https://github.com/mautic/api-library/blob/54c035bb87051250c2226b46b1b07e28aece1c39/lib/Auth/OAuth.php#L616-L735 |
mautic/api-library | lib/Auth/OAuth.php | OAuth.requestToken | protected function requestToken($responseType = 'flat')
{
$this->log('requestToken()');
//Make the request
$settings = array(
'responseType' => $responseType,
'includeCallback' => true,
'includeVerifier' => false
);
$params = $this->makeRequest($this->_request_token_url, array(), 'POST', $settings);
//Add token and secret to the session
if (is_array($params) && isset($params['oauth_token']) && isset($params['oauth_token_secret'])) {
$this->log('token set as '.$params['oauth_token']);
$_SESSION['oauth']['token'] = $params['oauth_token'];
$_SESSION['oauth']['token_secret'] = $params['oauth_token_secret'];
if ($this->_debug) {
$_SESSION['oauth']['debug']['token'] = $params['oauth_token'];
$_SESSION['oauth']['debug']['token_secret'] = $params['oauth_token_secret'];
}
} else {
//Throw exception if the required parameters were not found
$this->log('request did not return oauth tokens');
if ($this->_debug) {
$_SESSION['oauth']['debug']['response'] = $params;
}
if (is_array($params)) {
if (isset($params['error'])) {
$response = $params['error'];
} else {
$response = '???';
}
} else {
$response = $params;
}
throw new IncorrectParametersReturnedException('Incorrect access token parameters returned: '.$response);
}
} | php | protected function requestToken($responseType = 'flat')
{
$this->log('requestToken()');
//Make the request
$settings = array(
'responseType' => $responseType,
'includeCallback' => true,
'includeVerifier' => false
);
$params = $this->makeRequest($this->_request_token_url, array(), 'POST', $settings);
//Add token and secret to the session
if (is_array($params) && isset($params['oauth_token']) && isset($params['oauth_token_secret'])) {
$this->log('token set as '.$params['oauth_token']);
$_SESSION['oauth']['token'] = $params['oauth_token'];
$_SESSION['oauth']['token_secret'] = $params['oauth_token_secret'];
if ($this->_debug) {
$_SESSION['oauth']['debug']['token'] = $params['oauth_token'];
$_SESSION['oauth']['debug']['token_secret'] = $params['oauth_token_secret'];
}
} else {
//Throw exception if the required parameters were not found
$this->log('request did not return oauth tokens');
if ($this->_debug) {
$_SESSION['oauth']['debug']['response'] = $params;
}
if (is_array($params)) {
if (isset($params['error'])) {
$response = $params['error'];
} else {
$response = '???';
}
} else {
$response = $params;
}
throw new IncorrectParametersReturnedException('Incorrect access token parameters returned: '.$response);
}
} | [
"protected",
"function",
"requestToken",
"(",
"$",
"responseType",
"=",
"'flat'",
")",
"{",
"$",
"this",
"->",
"log",
"(",
"'requestToken()'",
")",
";",
"//Make the request",
"$",
"settings",
"=",
"array",
"(",
"'responseType'",
"=>",
"$",
"responseType",
",",... | Request token for OAuth1
@param string $responseType
@throws IncorrectParametersReturnedException | [
"Request",
"token",
"for",
"OAuth1"
] | train | https://github.com/mautic/api-library/blob/54c035bb87051250c2226b46b1b07e28aece1c39/lib/Auth/OAuth.php#L744-L787 |
mautic/api-library | lib/Auth/OAuth.php | OAuth.buildAuthorizationHeader | private function buildAuthorizationHeader($oauth)
{
$r = 'Authorization: OAuth ';
$values = $this->normalizeParameters($oauth);
$r .= str_replace('&', ', ', $values);
return $r;
} | php | private function buildAuthorizationHeader($oauth)
{
$r = 'Authorization: OAuth ';
$values = $this->normalizeParameters($oauth);
$r .= str_replace('&', ', ', $values);
return $r;
} | [
"private",
"function",
"buildAuthorizationHeader",
"(",
"$",
"oauth",
")",
"{",
"$",
"r",
"=",
"'Authorization: OAuth '",
";",
"$",
"values",
"=",
"$",
"this",
"->",
"normalizeParameters",
"(",
"$",
"oauth",
")",
";",
"$",
"r",
".=",
"str_replace",
"(",
"'... | Build header for OAuth 1 authorization
@param $oauth
@return string | [
"Build",
"header",
"for",
"OAuth",
"1",
"authorization"
] | train | https://github.com/mautic/api-library/blob/54c035bb87051250c2226b46b1b07e28aece1c39/lib/Auth/OAuth.php#L822-L829 |
mautic/api-library | lib/Auth/OAuth.php | OAuth.buildBaseString | private function buildBaseString($baseURI, $method, $params)
{
$r = $this->normalizeParameters($params);
return $method.'&'.$this->encode($baseURI).'&'.$this->encode($r);
} | php | private function buildBaseString($baseURI, $method, $params)
{
$r = $this->normalizeParameters($params);
return $method.'&'.$this->encode($baseURI).'&'.$this->encode($r);
} | [
"private",
"function",
"buildBaseString",
"(",
"$",
"baseURI",
",",
"$",
"method",
",",
"$",
"params",
")",
"{",
"$",
"r",
"=",
"$",
"this",
"->",
"normalizeParameters",
"(",
"$",
"params",
")",
";",
"return",
"$",
"method",
".",
"'&'",
".",
"$",
"th... | Build base string for OAuth 1 signature signing
@param string $baseURI
@param string $method
@param array $params
@return string | [
"Build",
"base",
"string",
"for",
"OAuth",
"1",
"signature",
"signing"
] | train | https://github.com/mautic/api-library/blob/54c035bb87051250c2226b46b1b07e28aece1c39/lib/Auth/OAuth.php#L840-L845 |
mautic/api-library | lib/Auth/OAuth.php | OAuth.generateNonce | private function generateNonce($bits = 64)
{
$result = '';
$accumulatedBits = 0;
$random = mt_getrandmax();
for ($totalBits = 0; $random != 0; $random >>= 1) {
++$totalBits;
}
$usableBits = intval($totalBits / 8) * 8;
while ($accumulatedBits < $bits) {
$bitsToAdd = min($totalBits - $usableBits, $bits - $accumulatedBits);
if ($bitsToAdd % 4 != 0) {
// add bits in whole increments of 4
$bitsToAdd += 4 - $bitsToAdd % 4;
}
// isolate leftmost $bits_to_add from mt_rand() result
$moreBits = mt_rand() & ((1 << $bitsToAdd) - 1);
// format as hex (this will be safe)
$format_string = '%0'.($bitsToAdd / 4).'x';
$result .= sprintf($format_string, $moreBits);
$accumulatedBits += $bitsToAdd;
}
return $result;
} | php | private function generateNonce($bits = 64)
{
$result = '';
$accumulatedBits = 0;
$random = mt_getrandmax();
for ($totalBits = 0; $random != 0; $random >>= 1) {
++$totalBits;
}
$usableBits = intval($totalBits / 8) * 8;
while ($accumulatedBits < $bits) {
$bitsToAdd = min($totalBits - $usableBits, $bits - $accumulatedBits);
if ($bitsToAdd % 4 != 0) {
// add bits in whole increments of 4
$bitsToAdd += 4 - $bitsToAdd % 4;
}
// isolate leftmost $bits_to_add from mt_rand() result
$moreBits = mt_rand() & ((1 << $bitsToAdd) - 1);
// format as hex (this will be safe)
$format_string = '%0'.($bitsToAdd / 4).'x';
$result .= sprintf($format_string, $moreBits);
$accumulatedBits += $bitsToAdd;
}
return $result;
} | [
"private",
"function",
"generateNonce",
"(",
"$",
"bits",
"=",
"64",
")",
"{",
"$",
"result",
"=",
"''",
";",
"$",
"accumulatedBits",
"=",
"0",
";",
"$",
"random",
"=",
"mt_getrandmax",
"(",
")",
";",
"for",
"(",
"$",
"totalBits",
"=",
"0",
";",
"$... | OAuth1.0 nonce generator
@param int $bits
@return string | [
"OAuth1",
".",
"0",
"nonce",
"generator"
] | train | https://github.com/mautic/api-library/blob/54c035bb87051250c2226b46b1b07e28aece1c39/lib/Auth/OAuth.php#L866-L895 |
mautic/api-library | lib/Auth/OAuth.php | OAuth.getCompositeKey | private function getCompositeKey()
{
if (isset($this->_access_token_secret) && strlen($this->_access_token_secret) > 0) {
$composite_key = $this->encode($this->_client_secret).'&'.$this->encode($this->_access_token_secret);
} elseif (isset($_SESSION['oauth']['token_secret'])) {
$composite_key = $this->encode($this->_client_secret).'&'.$this->encode($_SESSION['oauth']['token_secret']);
} else {
$composite_key = $this->encode($this->_client_secret).'&';
}
return $composite_key;
} | php | private function getCompositeKey()
{
if (isset($this->_access_token_secret) && strlen($this->_access_token_secret) > 0) {
$composite_key = $this->encode($this->_client_secret).'&'.$this->encode($this->_access_token_secret);
} elseif (isset($_SESSION['oauth']['token_secret'])) {
$composite_key = $this->encode($this->_client_secret).'&'.$this->encode($_SESSION['oauth']['token_secret']);
} else {
$composite_key = $this->encode($this->_client_secret).'&';
}
return $composite_key;
} | [
"private",
"function",
"getCompositeKey",
"(",
")",
"{",
"if",
"(",
"isset",
"(",
"$",
"this",
"->",
"_access_token_secret",
")",
"&&",
"strlen",
"(",
"$",
"this",
"->",
"_access_token_secret",
")",
">",
"0",
")",
"{",
"$",
"composite_key",
"=",
"$",
"th... | Get composite key for OAuth 1 signature signing
@return string | [
"Get",
"composite",
"key",
"for",
"OAuth",
"1",
"signature",
"signing"
] | train | https://github.com/mautic/api-library/blob/54c035bb87051250c2226b46b1b07e28aece1c39/lib/Auth/OAuth.php#L902-L913 |
mautic/api-library | lib/Auth/OAuth.php | OAuth.getOauthHeaders | private function getOauthHeaders($includeCallback = false)
{
$oauth = array(
'oauth_consumer_key' => $this->_client_id,
'oauth_nonce' => $this->generateNonce(),
'oauth_signature_method' => 'HMAC-SHA1',
'oauth_timestamp' => time(),
'oauth_version' => '1.0'
);
if (isset($this->_access_token)) {
$oauth['oauth_token'] = $this->_access_token;
} elseif (isset($_SESSION['oauth']['token'])) {
$oauth['oauth_token'] = $_SESSION['oauth']['token'];
}
if ($includeCallback) {
$oauth['oauth_callback'] = $this->_callback;
}
return $oauth;
} | php | private function getOauthHeaders($includeCallback = false)
{
$oauth = array(
'oauth_consumer_key' => $this->_client_id,
'oauth_nonce' => $this->generateNonce(),
'oauth_signature_method' => 'HMAC-SHA1',
'oauth_timestamp' => time(),
'oauth_version' => '1.0'
);
if (isset($this->_access_token)) {
$oauth['oauth_token'] = $this->_access_token;
} elseif (isset($_SESSION['oauth']['token'])) {
$oauth['oauth_token'] = $_SESSION['oauth']['token'];
}
if ($includeCallback) {
$oauth['oauth_callback'] = $this->_callback;
}
return $oauth;
} | [
"private",
"function",
"getOauthHeaders",
"(",
"$",
"includeCallback",
"=",
"false",
")",
"{",
"$",
"oauth",
"=",
"array",
"(",
"'oauth_consumer_key'",
"=>",
"$",
"this",
"->",
"_client_id",
",",
"'oauth_nonce'",
"=>",
"$",
"this",
"->",
"generateNonce",
"(",
... | Get OAuth 1.0 Headers
@param bool $includeCallback
@return array | [
"Get",
"OAuth",
"1",
".",
"0",
"Headers"
] | train | https://github.com/mautic/api-library/blob/54c035bb87051250c2226b46b1b07e28aece1c39/lib/Auth/OAuth.php#L922-L943 |
mautic/api-library | lib/Auth/OAuth.php | OAuth.normalizeParameters | private function normalizeParameters($parameters, $parentKey = '')
{
if (empty($parameters)) {
return '';
}
$normalized = array();
foreach ($parameters as $key => $value) {
if (empty($value)) {
continue;
}
if ($parentKey !== '') {
// Multidimensional array; using foo=bar&foo=baz rather than foo[bar]=baz&foo[baz]=bar
$key = $parentKey;
}
if (is_array($value)) {
$normalized[] = $this->normalizeParameters($value, $key);
} else {
$normalized[] = $this->encode($key) . '=' . $this->encode($value);
}
}
$normalized = array_filter($normalized);
sort($normalized, SORT_STRING);
return implode('&', $normalized);
} | php | private function normalizeParameters($parameters, $parentKey = '')
{
if (empty($parameters)) {
return '';
}
$normalized = array();
foreach ($parameters as $key => $value) {
if (empty($value)) {
continue;
}
if ($parentKey !== '') {
// Multidimensional array; using foo=bar&foo=baz rather than foo[bar]=baz&foo[baz]=bar
$key = $parentKey;
}
if (is_array($value)) {
$normalized[] = $this->normalizeParameters($value, $key);
} else {
$normalized[] = $this->encode($key) . '=' . $this->encode($value);
}
}
$normalized = array_filter($normalized);
sort($normalized, SORT_STRING);
return implode('&', $normalized);
} | [
"private",
"function",
"normalizeParameters",
"(",
"$",
"parameters",
",",
"$",
"parentKey",
"=",
"''",
")",
"{",
"if",
"(",
"empty",
"(",
"$",
"parameters",
")",
")",
"{",
"return",
"''",
";",
"}",
"$",
"normalized",
"=",
"array",
"(",
")",
";",
"fo... | Normalize parameters
@param array $parameters
@param string $parentKey
@return string | [
"Normalize",
"parameters"
] | train | https://github.com/mautic/api-library/blob/54c035bb87051250c2226b46b1b07e28aece1c39/lib/Auth/OAuth.php#L953-L981 |
mautic/api-library | lib/Api/Stats.php | Stats.get | public function get($table = '', $start = 0, $limit = 0, array $order = array(), array $where = array())
{
$parameters = array(
'start' => $start,
'limit' => $limit,
'order' => $order,
'where' => $where,
);
$parameters = array_filter($parameters);
return $this->makeRequest($this->endpoint.'/'.$table, $parameters);
} | php | public function get($table = '', $start = 0, $limit = 0, array $order = array(), array $where = array())
{
$parameters = array(
'start' => $start,
'limit' => $limit,
'order' => $order,
'where' => $where,
);
$parameters = array_filter($parameters);
return $this->makeRequest($this->endpoint.'/'.$table, $parameters);
} | [
"public",
"function",
"get",
"(",
"$",
"table",
"=",
"''",
",",
"$",
"start",
"=",
"0",
",",
"$",
"limit",
"=",
"0",
",",
"array",
"$",
"order",
"=",
"array",
"(",
")",
",",
"array",
"$",
"where",
"=",
"array",
"(",
")",
")",
"{",
"$",
"param... | Get a list of stat items
@param string $table
@param int $start
@param int $limit
@param array $order
@param array $where
@return array | [
"Get",
"a",
"list",
"of",
"stat",
"items"
] | train | https://github.com/mautic/api-library/blob/54c035bb87051250c2226b46b1b07e28aece1c39/lib/Api/Stats.php#L39-L51 |
mautic/api-library | lib/Api/Stats.php | Stats.getList | public function getList($search = '', $start = 0, $limit = 0, $orderBy = '', $orderByDir = 'ASC', $publishedOnly = false, $minimal = false)
{
return $this->actionNotSupported('getList');
} | php | public function getList($search = '', $start = 0, $limit = 0, $orderBy = '', $orderByDir = 'ASC', $publishedOnly = false, $minimal = false)
{
return $this->actionNotSupported('getList');
} | [
"public",
"function",
"getList",
"(",
"$",
"search",
"=",
"''",
",",
"$",
"start",
"=",
"0",
",",
"$",
"limit",
"=",
"0",
",",
"$",
"orderBy",
"=",
"''",
",",
"$",
"orderByDir",
"=",
"'ASC'",
",",
"$",
"publishedOnly",
"=",
"false",
",",
"$",
"mi... | {@inheritdoc} | [
"{"
] | train | https://github.com/mautic/api-library/blob/54c035bb87051250c2226b46b1b07e28aece1c39/lib/Api/Stats.php#L64-L67 |
mautic/api-library | lib/Api/Contacts.php | Contacts.getIdentified | public function getIdentified($search = '', $start = 0, $limit = 0, $orderBy = '', $orderByDir = 'ASC', $publishedOnly = false, $minimal = false)
{
$search = ($search) ? "$search !is:anonymous" : '!is:anonymous';
return $this->getList($search, $start, $limit, $orderBy, $orderByDir, $publishedOnly, $minimal);
} | php | public function getIdentified($search = '', $start = 0, $limit = 0, $orderBy = '', $orderByDir = 'ASC', $publishedOnly = false, $minimal = false)
{
$search = ($search) ? "$search !is:anonymous" : '!is:anonymous';
return $this->getList($search, $start, $limit, $orderBy, $orderByDir, $publishedOnly, $minimal);
} | [
"public",
"function",
"getIdentified",
"(",
"$",
"search",
"=",
"''",
",",
"$",
"start",
"=",
"0",
",",
"$",
"limit",
"=",
"0",
",",
"$",
"orderBy",
"=",
"''",
",",
"$",
"orderByDir",
"=",
"'ASC'",
",",
"$",
"publishedOnly",
"=",
"false",
",",
"$",... | @param string $search
@param int $start
@param int $limit
@param string $orderBy
@param string $orderByDir
@param bool $publishedOnly
@param bool $minimal
@return array|mixed | [
"@param",
"string",
"$search",
"@param",
"int",
"$start",
"@param",
"int",
"$limit",
"@param",
"string",
"$orderBy",
"@param",
"string",
"$orderByDir",
"@param",
"bool",
"$publishedOnly",
"@param",
"bool",
"$minimal"
] | train | https://github.com/mautic/api-library/blob/54c035bb87051250c2226b46b1b07e28aece1c39/lib/Api/Contacts.php#L84-L89 |
mautic/api-library | lib/Api/Contacts.php | Contacts.getEvents | public function getEvents(
$id,
$search = '',
array $includeEvents = array(),
array $excludeEvents = array(),
$orderBy = '',
$orderByDir = 'ASC',
$page = 1
) {
return $this->fetchActivity('/'.$id.'/events', $search, $includeEvents, $excludeEvents, $orderBy, $orderByDir, $page);
} | php | public function getEvents(
$id,
$search = '',
array $includeEvents = array(),
array $excludeEvents = array(),
$orderBy = '',
$orderByDir = 'ASC',
$page = 1
) {
return $this->fetchActivity('/'.$id.'/events', $search, $includeEvents, $excludeEvents, $orderBy, $orderByDir, $page);
} | [
"public",
"function",
"getEvents",
"(",
"$",
"id",
",",
"$",
"search",
"=",
"''",
",",
"array",
"$",
"includeEvents",
"=",
"array",
"(",
")",
",",
"array",
"$",
"excludeEvents",
"=",
"array",
"(",
")",
",",
"$",
"orderBy",
"=",
"''",
",",
"$",
"ord... | Get a list of a contact's engagement events
@param int $id Contact ID
@param string $search
@param array $includeEvents
@param array $excludeEvents
@param string $orderBy
@param string $orderByDir
@param int $page
@return array|mixed
@deprecated 2.10.0 Use getActivityForContact instead. The response is slightly different. | [
"Get",
"a",
"list",
"of",
"a",
"contact",
"s",
"engagement",
"events"
] | train | https://github.com/mautic/api-library/blob/54c035bb87051250c2226b46b1b07e28aece1c39/lib/Api/Contacts.php#L136-L146 |
mautic/api-library | lib/Api/Contacts.php | Contacts.getActivityForContact | public function getActivityForContact(
$id,
$search = '',
array $includeEvents = array(),
array $excludeEvents = array(),
$orderBy = '',
$orderByDir = 'ASC',
$page = 1,
\DateTime $dateFrom = null,
\DateTime $dateTo = null
) {
return $this->fetchActivity('/'.$id.'/activity', $search, $includeEvents, $excludeEvents, $orderBy, $orderByDir, $page, $dateFrom, $dateTo);
} | php | public function getActivityForContact(
$id,
$search = '',
array $includeEvents = array(),
array $excludeEvents = array(),
$orderBy = '',
$orderByDir = 'ASC',
$page = 1,
\DateTime $dateFrom = null,
\DateTime $dateTo = null
) {
return $this->fetchActivity('/'.$id.'/activity', $search, $includeEvents, $excludeEvents, $orderBy, $orderByDir, $page, $dateFrom, $dateTo);
} | [
"public",
"function",
"getActivityForContact",
"(",
"$",
"id",
",",
"$",
"search",
"=",
"''",
",",
"array",
"$",
"includeEvents",
"=",
"array",
"(",
")",
",",
"array",
"$",
"excludeEvents",
"=",
"array",
"(",
")",
",",
"$",
"orderBy",
"=",
"''",
",",
... | Get a list of contact activity events for all contacts
@param int $id Contact ID
@param string $search
@param array $includeEvents
@param array $excludeEvents
@param string $orderBy
@param string $orderByDir
@param int $page
@param \DateTime $dateFrom
@param \DateTime $dateTo
@return array|mixed | [
"Get",
"a",
"list",
"of",
"contact",
"activity",
"events",
"for",
"all",
"contacts"
] | train | https://github.com/mautic/api-library/blob/54c035bb87051250c2226b46b1b07e28aece1c39/lib/Api/Contacts.php#L163-L175 |
mautic/api-library | lib/Api/Contacts.php | Contacts.fetchActivity | protected function fetchActivity(
$path,
$search = '',
array $includeEvents = array(),
array $excludeEvents = array(),
$orderBy = '',
$orderByDir = 'ASC',
$page = 1,
\DateTime $dateFrom = null,
\DateTime $dateTo = null
) {
$parameters = array(
'filters' => array(
'search' => $search,
'includeEvents' => $includeEvents,
'excludeEvents' => $excludeEvents,
),
'order' => array(
$orderBy,
$orderByDir,
),
'page' => $page
);
if ($dateFrom) {
$parameters['filters']['dateFrom'] = $dateFrom->format('Y-m-d H:i:s');
}
if ($dateTo) {
$parameters['filters']['dateTo'] = $dateTo->format('Y-m-d H:i:s');
}
return $this->makeRequest($this->endpoint.$path, $parameters);
} | php | protected function fetchActivity(
$path,
$search = '',
array $includeEvents = array(),
array $excludeEvents = array(),
$orderBy = '',
$orderByDir = 'ASC',
$page = 1,
\DateTime $dateFrom = null,
\DateTime $dateTo = null
) {
$parameters = array(
'filters' => array(
'search' => $search,
'includeEvents' => $includeEvents,
'excludeEvents' => $excludeEvents,
),
'order' => array(
$orderBy,
$orderByDir,
),
'page' => $page
);
if ($dateFrom) {
$parameters['filters']['dateFrom'] = $dateFrom->format('Y-m-d H:i:s');
}
if ($dateTo) {
$parameters['filters']['dateTo'] = $dateTo->format('Y-m-d H:i:s');
}
return $this->makeRequest($this->endpoint.$path, $parameters);
} | [
"protected",
"function",
"fetchActivity",
"(",
"$",
"path",
",",
"$",
"search",
"=",
"''",
",",
"array",
"$",
"includeEvents",
"=",
"array",
"(",
")",
",",
"array",
"$",
"excludeEvents",
"=",
"array",
"(",
")",
",",
"$",
"orderBy",
"=",
"''",
",",
"$... | Get a list of contact activity events for all contacts
@param string $path of the URL after the endpoint
@param string $search
@param array $includeEvents
@param array $excludeEvents
@param string $orderBy
@param string $orderByDir
@param int $page
@param \DateTime $dateFrom
@param \DateTime $dateTo
@return array|mixed | [
"Get",
"a",
"list",
"of",
"contact",
"activity",
"events",
"for",
"all",
"contacts"
] | train | https://github.com/mautic/api-library/blob/54c035bb87051250c2226b46b1b07e28aece1c39/lib/Api/Contacts.php#L220-L253 |
mautic/api-library | lib/Api/Contacts.php | Contacts.getContactNotes | public function getContactNotes($id, $search = '', $start = 0, $limit = 0, $orderBy = '', $orderByDir = 'ASC')
{
$parameters = array(
'search' => $search,
'start' => $start,
'limit' => $limit,
'orderBy' => $orderBy,
'orderByDir' => $orderByDir,
);
$parameters = array_filter($parameters);
return $this->makeRequest($this->endpoint.'/'.$id.'/notes', $parameters);
} | php | public function getContactNotes($id, $search = '', $start = 0, $limit = 0, $orderBy = '', $orderByDir = 'ASC')
{
$parameters = array(
'search' => $search,
'start' => $start,
'limit' => $limit,
'orderBy' => $orderBy,
'orderByDir' => $orderByDir,
);
$parameters = array_filter($parameters);
return $this->makeRequest($this->endpoint.'/'.$id.'/notes', $parameters);
} | [
"public",
"function",
"getContactNotes",
"(",
"$",
"id",
",",
"$",
"search",
"=",
"''",
",",
"$",
"start",
"=",
"0",
",",
"$",
"limit",
"=",
"0",
",",
"$",
"orderBy",
"=",
"''",
",",
"$",
"orderByDir",
"=",
"'ASC'",
")",
"{",
"$",
"parameters",
"... | Get a list of a contact's notes
@param int $id Contact ID
@param string $search
@param int $start
@param int $limit
@param string $orderBy
@param string $orderByDir
@return array|mixed | [
"Get",
"a",
"list",
"of",
"a",
"contact",
"s",
"notes"
] | train | https://github.com/mautic/api-library/blob/54c035bb87051250c2226b46b1b07e28aece1c39/lib/Api/Contacts.php#L267-L280 |
mautic/api-library | lib/Api/Contacts.php | Contacts.addDnc | public function addDnc($id, $channel = 'email', $reason = Contacts::MANUAL, $channelId = null, $comments = 'via API') {
return $this->makeRequest(
'contacts/'.$id.'/dnc/'.$channel.'/add',
array(
'reason' => $reason,
'channelId' => $channelId,
'comments' => $comments,
),
'POST'
);
} | php | public function addDnc($id, $channel = 'email', $reason = Contacts::MANUAL, $channelId = null, $comments = 'via API') {
return $this->makeRequest(
'contacts/'.$id.'/dnc/'.$channel.'/add',
array(
'reason' => $reason,
'channelId' => $channelId,
'comments' => $comments,
),
'POST'
);
} | [
"public",
"function",
"addDnc",
"(",
"$",
"id",
",",
"$",
"channel",
"=",
"'email'",
",",
"$",
"reason",
"=",
"Contacts",
"::",
"MANUAL",
",",
"$",
"channelId",
"=",
"null",
",",
"$",
"comments",
"=",
"'via API'",
")",
"{",
"return",
"$",
"this",
"->... | Adds Do Not Contact
@param int $id
@param string $channel
@param int $reason
@param null $channelId
@param string $comments
@return array|mixed | [
"Adds",
"Do",
"Not",
"Contact"
] | train | https://github.com/mautic/api-library/blob/54c035bb87051250c2226b46b1b07e28aece1c39/lib/Api/Contacts.php#L384-L395 |
mautic/api-library | lib/Api/Forms.php | Forms.getSubmissionsForContact | public function getSubmissionsForContact($formId, $contactId, $search = '', $start = 0, $limit = 0, $orderBy = '', $orderByDir = 'ASC', $publishedOnly = false, $minimal = false)
{
$parameters = array(
'search' => $search,
'start' => $start,
'limit' => $limit,
'orderBy' => $orderBy,
'orderByDir' => $orderByDir,
'publishedOnly' => $publishedOnly,
'minimal' => $minimal
);
$parameters = array_filter($parameters);
return $this->makeRequest("{$this->endpoint}/$formId/submissions/contact/$contactId", $parameters);
} | php | public function getSubmissionsForContact($formId, $contactId, $search = '', $start = 0, $limit = 0, $orderBy = '', $orderByDir = 'ASC', $publishedOnly = false, $minimal = false)
{
$parameters = array(
'search' => $search,
'start' => $start,
'limit' => $limit,
'orderBy' => $orderBy,
'orderByDir' => $orderByDir,
'publishedOnly' => $publishedOnly,
'minimal' => $minimal
);
$parameters = array_filter($parameters);
return $this->makeRequest("{$this->endpoint}/$formId/submissions/contact/$contactId", $parameters);
} | [
"public",
"function",
"getSubmissionsForContact",
"(",
"$",
"formId",
",",
"$",
"contactId",
",",
"$",
"search",
"=",
"''",
",",
"$",
"start",
"=",
"0",
",",
"$",
"limit",
"=",
"0",
",",
"$",
"orderBy",
"=",
"''",
",",
"$",
"orderByDir",
"=",
"'ASC'"... | Get a list of form submissions for specific form and contact
@param int $formId
@param int $contactId
@param string $search
@param int $start
@param int $limit
@param string $orderBy
@param string $orderByDir
@param bool $publishedOnly
@param bool $minimal
@return array|mixed | [
"Get",
"a",
"list",
"of",
"form",
"submissions",
"for",
"specific",
"form",
"and",
"contact"
] | train | https://github.com/mautic/api-library/blob/54c035bb87051250c2226b46b1b07e28aece1c39/lib/Api/Forms.php#L132-L147 |
mautic/api-library | lib/Api/Leads.php | Leads.getLeadNotes | public function getLeadNotes($id, $search = '', $start = 0, $limit = 0, $orderBy = '', $orderByDir = 'ASC')
{
$parameters = array(
'search' => $search,
'start' => $start,
'limit' => $limit,
'orderBy' => $orderBy,
'orderByDir' => $orderByDir,
);
$parameters = array_filter($parameters);
return $this->makeRequest('contacts/'.$id.'/notes', $parameters);
} | php | public function getLeadNotes($id, $search = '', $start = 0, $limit = 0, $orderBy = '', $orderByDir = 'ASC')
{
$parameters = array(
'search' => $search,
'start' => $start,
'limit' => $limit,
'orderBy' => $orderBy,
'orderByDir' => $orderByDir,
);
$parameters = array_filter($parameters);
return $this->makeRequest('contacts/'.$id.'/notes', $parameters);
} | [
"public",
"function",
"getLeadNotes",
"(",
"$",
"id",
",",
"$",
"search",
"=",
"''",
",",
"$",
"start",
"=",
"0",
",",
"$",
"limit",
"=",
"0",
",",
"$",
"orderBy",
"=",
"''",
",",
"$",
"orderByDir",
"=",
"'ASC'",
")",
"{",
"$",
"parameters",
"=",... | @param $id
@param string $search
@param int $start
@param int $limit
@param string $orderBy
@param string $orderByDir
@return array|mixed | [
"@param",
"$id",
"@param",
"string",
"$search",
"@param",
"int",
"$start",
"@param",
"int",
"$limit",
"@param",
"string",
"$orderBy",
"@param",
"string",
"$orderByDir"
] | train | https://github.com/mautic/api-library/blob/54c035bb87051250c2226b46b1b07e28aece1c39/lib/Api/Leads.php#L41-L54 |
mautic/api-library | lib/MauticApi.php | MauticApi.getContext | public static function getContext($apiContext, AuthInterface $auth, $baseUrl = '')
{
static $contexts = array();
$apiContext = ucfirst($apiContext);
if (!isset($context[$apiContext])) {
$class = 'Mautic\\Api\\'.$apiContext;
if (!class_exists($class)) {
throw new ContextNotFoundException("A context of '$apiContext' was not found.");
}
$contexts[$apiContext] = new $class($auth, $baseUrl);
}
return $contexts[$apiContext];
} | php | public static function getContext($apiContext, AuthInterface $auth, $baseUrl = '')
{
static $contexts = array();
$apiContext = ucfirst($apiContext);
if (!isset($context[$apiContext])) {
$class = 'Mautic\\Api\\'.$apiContext;
if (!class_exists($class)) {
throw new ContextNotFoundException("A context of '$apiContext' was not found.");
}
$contexts[$apiContext] = new $class($auth, $baseUrl);
}
return $contexts[$apiContext];
} | [
"public",
"static",
"function",
"getContext",
"(",
"$",
"apiContext",
",",
"AuthInterface",
"$",
"auth",
",",
"$",
"baseUrl",
"=",
"''",
")",
"{",
"static",
"$",
"contexts",
"=",
"array",
"(",
")",
";",
"$",
"apiContext",
"=",
"ucfirst",
"(",
"$",
"api... | Get an API context object
@param string $apiContext API context (leads, forms, etc)
@param AuthInterface $auth API Auth object
@param string $baseUrl Base URL for API endpoints
@return Api\Api
@throws ContextNotFoundException
@deprecated | [
"Get",
"an",
"API",
"context",
"object"
] | train | https://github.com/mautic/api-library/blob/54c035bb87051250c2226b46b1b07e28aece1c39/lib/MauticApi.php#L32-L49 |
mautic/api-library | lib/MauticApi.php | MauticApi.newApi | public function newApi($apiContext, AuthInterface $auth, $baseUrl = '')
{
$apiContext = ucfirst($apiContext);
$class = 'Mautic\\Api\\'.$apiContext;
if (!class_exists($class)) {
throw new ContextNotFoundException("A context of '$apiContext' was not found.");
}
return new $class($auth, $baseUrl);
} | php | public function newApi($apiContext, AuthInterface $auth, $baseUrl = '')
{
$apiContext = ucfirst($apiContext);
$class = 'Mautic\\Api\\'.$apiContext;
if (!class_exists($class)) {
throw new ContextNotFoundException("A context of '$apiContext' was not found.");
}
return new $class($auth, $baseUrl);
} | [
"public",
"function",
"newApi",
"(",
"$",
"apiContext",
",",
"AuthInterface",
"$",
"auth",
",",
"$",
"baseUrl",
"=",
"''",
")",
"{",
"$",
"apiContext",
"=",
"ucfirst",
"(",
"$",
"apiContext",
")",
";",
"$",
"class",
"=",
"'Mautic\\\\Api\\\\'",
".",
"$",
... | Get an API context object
@param string $apiContext API context (leads, forms, etc)
@param AuthInterface $auth API Auth object
@param string $baseUrl Base URL for API endpoints
@return Api\Api
@throws ContextNotFoundException | [
"Get",
"an",
"API",
"context",
"object"
] | train | https://github.com/mautic/api-library/blob/54c035bb87051250c2226b46b1b07e28aece1c39/lib/MauticApi.php#L61-L72 |
mautic/api-library | lib/Api/Campaigns.php | Campaigns.getContacts | public function getContacts($id, $start = 0, $limit = 0, array $order = array(), array $where = array())
{
$parameters = array();
$args = array('start', 'limit', 'order', 'where');
foreach ($args as $arg) {
if (!empty($$arg)) {
$parameters[$arg] = $$arg;
}
}
return $this->makeRequest($this->endpoint.'/'.$id.'/contacts', $parameters);
} | php | public function getContacts($id, $start = 0, $limit = 0, array $order = array(), array $where = array())
{
$parameters = array();
$args = array('start', 'limit', 'order', 'where');
foreach ($args as $arg) {
if (!empty($$arg)) {
$parameters[$arg] = $$arg;
}
}
return $this->makeRequest($this->endpoint.'/'.$id.'/contacts', $parameters);
} | [
"public",
"function",
"getContacts",
"(",
"$",
"id",
",",
"$",
"start",
"=",
"0",
",",
"$",
"limit",
"=",
"0",
",",
"array",
"$",
"order",
"=",
"array",
"(",
")",
",",
"array",
"$",
"where",
"=",
"array",
"(",
")",
")",
"{",
"$",
"parameters",
... | Get a list of stat items
@param int $id Campaign ID
@param int $start
@param int $limit
@param array $order
@param array $where
@return array|mixed | [
"Get",
"a",
"list",
"of",
"stat",
"items"
] | train | https://github.com/mautic/api-library/blob/54c035bb87051250c2226b46b1b07e28aece1c39/lib/Api/Campaigns.php#L120-L132 |
mautic/api-library | lib/Api/Reports.php | Reports.get | public function get($id, $limit = null, $page = null, \DateTime $dateFrom = null, \DateTime $dateTo = null)
{
$options = array();
if ($limit) {
$options['limit'] = (int) $limit;
}
if ($page) {
$options['page'] = (int) $page;
}
if ($dateFrom) {
$options['dateFrom'] = $dateFrom->format('c');
}
if ($dateTo) {
$options['dateTo'] = $dateTo->format('c');
}
return $this->makeRequest("{$this->endpoint}/$id", $options);
} | php | public function get($id, $limit = null, $page = null, \DateTime $dateFrom = null, \DateTime $dateTo = null)
{
$options = array();
if ($limit) {
$options['limit'] = (int) $limit;
}
if ($page) {
$options['page'] = (int) $page;
}
if ($dateFrom) {
$options['dateFrom'] = $dateFrom->format('c');
}
if ($dateTo) {
$options['dateTo'] = $dateTo->format('c');
}
return $this->makeRequest("{$this->endpoint}/$id", $options);
} | [
"public",
"function",
"get",
"(",
"$",
"id",
",",
"$",
"limit",
"=",
"null",
",",
"$",
"page",
"=",
"null",
",",
"\\",
"DateTime",
"$",
"dateFrom",
"=",
"null",
",",
"\\",
"DateTime",
"$",
"dateTo",
"=",
"null",
")",
"{",
"$",
"options",
"=",
"ar... | Get a single report data
@param int $id
@param int|null $limit
@param int|null $page
@param \DateTime|null $dateFrom
@param \DateTime|null $dateTo
@return array|mixed | [
"Get",
"a",
"single",
"report",
"data"
] | train | https://github.com/mautic/api-library/blob/54c035bb87051250c2226b46b1b07e28aece1c39/lib/Api/Reports.php#L62-L83 |
mautic/api-library | lib/QueryBuilder/WhereBuilder.php | WhereBuilder.between | public function between($col, $val1, $val2)
{
$this->addClause($col, __FUNCTION__, array($val1, $val2));
return $this;
} | php | public function between($col, $val1, $val2)
{
$this->addClause($col, __FUNCTION__, array($val1, $val2));
return $this;
} | [
"public",
"function",
"between",
"(",
"$",
"col",
",",
"$",
"val1",
",",
"$",
"val2",
")",
"{",
"$",
"this",
"->",
"addClause",
"(",
"$",
"col",
",",
"__FUNCTION__",
",",
"array",
"(",
"$",
"val1",
",",
"$",
"val2",
")",
")",
";",
"return",
"$",
... | @param $col
@param $val1
@param $val2
@return $this | [
"@param",
"$col",
"@param",
"$val1",
"@param",
"$val2"
] | train | https://github.com/mautic/api-library/blob/54c035bb87051250c2226b46b1b07e28aece1c39/lib/QueryBuilder/WhereBuilder.php#L184-L189 |
mautic/api-library | lib/QueryBuilder/WhereBuilder.php | WhereBuilder.notBetween | public function notBetween($col, $val1, $val2)
{
$this->addClause($col, __FUNCTION__, array($val1, $val2));
return $this;
} | php | public function notBetween($col, $val1, $val2)
{
$this->addClause($col, __FUNCTION__, array($val1, $val2));
return $this;
} | [
"public",
"function",
"notBetween",
"(",
"$",
"col",
",",
"$",
"val1",
",",
"$",
"val2",
")",
"{",
"$",
"this",
"->",
"addClause",
"(",
"$",
"col",
",",
"__FUNCTION__",
",",
"array",
"(",
"$",
"val1",
",",
"$",
"val2",
")",
")",
";",
"return",
"$... | @param $col
@param $val1
@param $val2
@return $this | [
"@param",
"$col",
"@param",
"$val1",
"@param",
"$val2"
] | train | https://github.com/mautic/api-library/blob/54c035bb87051250c2226b46b1b07e28aece1c39/lib/QueryBuilder/WhereBuilder.php#L198-L203 |
mautic/api-library | lib/QueryBuilder/WhereBuilder.php | WhereBuilder.x | private function x($composite, $clauses)
{
$builder = new self($composite);
if ($clauses) {
foreach ($clauses as $x) {
$builder->add($x);
}
$this->add($builder);
return $this;
}
return $builder;
} | php | private function x($composite, $clauses)
{
$builder = new self($composite);
if ($clauses) {
foreach ($clauses as $x) {
$builder->add($x);
}
$this->add($builder);
return $this;
}
return $builder;
} | [
"private",
"function",
"x",
"(",
"$",
"composite",
",",
"$",
"clauses",
")",
"{",
"$",
"builder",
"=",
"new",
"self",
"(",
"$",
"composite",
")",
";",
"if",
"(",
"$",
"clauses",
")",
"{",
"foreach",
"(",
"$",
"clauses",
"as",
"$",
"x",
")",
"{",
... | @param $composite
@param $clauses
@return $this|WhereBuilder | [
"@param",
"$composite",
"@param",
"$clauses"
] | train | https://github.com/mautic/api-library/blob/54c035bb87051250c2226b46b1b07e28aece1c39/lib/QueryBuilder/WhereBuilder.php#L322-L337 |
mautic/api-library | lib/Api/CampaignEvents.php | CampaignEvents.getContactEvents | public function getContactEvents($contactId, $search = '', $start = 0, $limit = 0, $orderBy = '', $orderByDir = 'ASC')
{
$parameters = array(
'search' => $search,
'start' => $start,
'limit' => $limit,
'orderBy' => $orderBy,
'orderByDir' => $orderByDir,
);
$parameters = array_filter($parameters);
return $this->makeRequest($this->endpoint.'/contact/'.$contactId, $parameters);
} | php | public function getContactEvents($contactId, $search = '', $start = 0, $limit = 0, $orderBy = '', $orderByDir = 'ASC')
{
$parameters = array(
'search' => $search,
'start' => $start,
'limit' => $limit,
'orderBy' => $orderBy,
'orderByDir' => $orderByDir,
);
$parameters = array_filter($parameters);
return $this->makeRequest($this->endpoint.'/contact/'.$contactId, $parameters);
} | [
"public",
"function",
"getContactEvents",
"(",
"$",
"contactId",
",",
"$",
"search",
"=",
"''",
",",
"$",
"start",
"=",
"0",
",",
"$",
"limit",
"=",
"0",
",",
"$",
"orderBy",
"=",
"''",
",",
"$",
"orderByDir",
"=",
"'ASC'",
")",
"{",
"$",
"paramete... | Get contact events across all campaigns
@param $contactId
@param string $search
@param int $start
@param int $limit
@param string $orderBy
@param string $orderByDir
@return array|mixed | [
"Get",
"contact",
"events",
"across",
"all",
"campaigns"
] | train | https://github.com/mautic/api-library/blob/54c035bb87051250c2226b46b1b07e28aece1c39/lib/Api/CampaignEvents.php#L53-L66 |
mautic/api-library | lib/Api/CampaignEvents.php | CampaignEvents.getContactCampaignEvents | public function getContactCampaignEvents($campaignId, $contactId, $search = '', $start = 0, $limit = 0, $orderBy = '', $orderByDir = 'ASC')
{
$parameters = array(
'search' => $search,
'start' => $start,
'limit' => $limit,
'orderBy' => $orderBy,
'orderByDir' => $orderByDir,
);
$parameters = array_filter($parameters);
return $this->makeRequest('campaigns/'.$campaignId.'/events/contact/'.$contactId, $parameters);
} | php | public function getContactCampaignEvents($campaignId, $contactId, $search = '', $start = 0, $limit = 0, $orderBy = '', $orderByDir = 'ASC')
{
$parameters = array(
'search' => $search,
'start' => $start,
'limit' => $limit,
'orderBy' => $orderBy,
'orderByDir' => $orderByDir,
);
$parameters = array_filter($parameters);
return $this->makeRequest('campaigns/'.$campaignId.'/events/contact/'.$contactId, $parameters);
} | [
"public",
"function",
"getContactCampaignEvents",
"(",
"$",
"campaignId",
",",
"$",
"contactId",
",",
"$",
"search",
"=",
"''",
",",
"$",
"start",
"=",
"0",
",",
"$",
"limit",
"=",
"0",
",",
"$",
"orderBy",
"=",
"''",
",",
"$",
"orderByDir",
"=",
"'A... | Get contact events for a single campaign
@param $campaignId
@param $contactId
@param string $search
@param int $start
@param int $limit
@param string $orderBy
@param string $orderByDir
@return array|mixed | [
"Get",
"contact",
"events",
"for",
"a",
"single",
"campaign"
] | train | https://github.com/mautic/api-library/blob/54c035bb87051250c2226b46b1b07e28aece1c39/lib/Api/CampaignEvents.php#L81-L94 |
mautic/api-library | lib/Api/CampaignEvents.php | CampaignEvents.editContactEvent | public function editContactEvent($contactId, $eventId, array $parameters)
{
return $this->makeRequest($this->endpoint.'/'.$eventId.'/contact/'.$contactId.'/edit', $parameters, 'PUT');
} | php | public function editContactEvent($contactId, $eventId, array $parameters)
{
return $this->makeRequest($this->endpoint.'/'.$eventId.'/contact/'.$contactId.'/edit', $parameters, 'PUT');
} | [
"public",
"function",
"editContactEvent",
"(",
"$",
"contactId",
",",
"$",
"eventId",
",",
"array",
"$",
"parameters",
")",
"{",
"return",
"$",
"this",
"->",
"makeRequest",
"(",
"$",
"this",
"->",
"endpoint",
".",
"'/'",
".",
"$",
"eventId",
".",
"'/cont... | Edit or schedule a campaign event for a specific contact.
@param $contactId
@param $eventId
@param $parameters
@return array|mixed | [
"Edit",
"or",
"schedule",
"a",
"campaign",
"event",
"for",
"a",
"specific",
"contact",
"."
] | train | https://github.com/mautic/api-library/blob/54c035bb87051250c2226b46b1b07e28aece1c39/lib/Api/CampaignEvents.php#L105-L108 |
mautic/api-library | lib/QueryBuilder/QueryBuilder.php | QueryBuilder.getWhereBuilder | public function getWhereBuilder($new = false)
{
if ($new) {
return new WhereBuilder();
}
if (null == self::$whereBuilder) {
$this->resetWhereBuilder();
}
return self::$whereBuilder;
} | php | public function getWhereBuilder($new = false)
{
if ($new) {
return new WhereBuilder();
}
if (null == self::$whereBuilder) {
$this->resetWhereBuilder();
}
return self::$whereBuilder;
} | [
"public",
"function",
"getWhereBuilder",
"(",
"$",
"new",
"=",
"false",
")",
"{",
"if",
"(",
"$",
"new",
")",
"{",
"return",
"new",
"WhereBuilder",
"(",
")",
";",
"}",
"if",
"(",
"null",
"==",
"self",
"::",
"$",
"whereBuilder",
")",
"{",
"$",
"this... | @param bool $new
@return WhereBuilder | [
"@param",
"bool",
"$new"
] | train | https://github.com/mautic/api-library/blob/54c035bb87051250c2226b46b1b07e28aece1c39/lib/QueryBuilder/QueryBuilder.php#L79-L90 |
jublo/codebird-php | src/codebird.php | Codebird.logout | public function logout()
{
$this->oauth_invalidateToken([
'access_token' => $this->_oauth_token,
'access_token_secret' => $this->_oauth_token_secret
]);
$this->_oauth_token =
$this->_oauth_token_secret = null;
return true;
} | php | public function logout()
{
$this->oauth_invalidateToken([
'access_token' => $this->_oauth_token,
'access_token_secret' => $this->_oauth_token_secret
]);
$this->_oauth_token =
$this->_oauth_token_secret = null;
return true;
} | [
"public",
"function",
"logout",
"(",
")",
"{",
"$",
"this",
"->",
"oauth_invalidateToken",
"(",
"[",
"'access_token'",
"=>",
"$",
"this",
"->",
"_oauth_token",
",",
"'access_token_secret'",
"=>",
"$",
"this",
"->",
"_oauth_token_secret",
"]",
")",
";",
"$",
... | Forgets the OAuth request or access token and secret (User key)
@return bool | [
"Forgets",
"the",
"OAuth",
"request",
"or",
"access",
"token",
"and",
"secret",
"(",
"User",
"key",
")"
] | train | https://github.com/jublo/codebird-php/blob/0c20a63e95640f56102e76d3ca14462b3908acc1/src/codebird.php#L672-L683 |
jublo/codebird-php | src/codebird.php | Codebird.setProxy | public function setProxy($host, $port, $type = CURLPROXY_HTTP)
{
static $types_str = [
'HTTP', 'SOCKS4', 'SOCKS5', 'SOCKS4A', 'SOCKS5_HOSTNAME'
];
$types = [];
foreach ($types_str as $type_str) {
if (defined('CURLPROXY_' . $type_str)) {
$types[] = constant('CURLPROXY_' . $type_str);
}
}
if (! in_array($type, $types)) {
throw new \Exception('Invalid proxy type specified.');
}
$this->_proxy['host'] = $host;
$this->_proxy['port'] = (int) $port;
$this->_proxy['type'] = $type;
} | php | public function setProxy($host, $port, $type = CURLPROXY_HTTP)
{
static $types_str = [
'HTTP', 'SOCKS4', 'SOCKS5', 'SOCKS4A', 'SOCKS5_HOSTNAME'
];
$types = [];
foreach ($types_str as $type_str) {
if (defined('CURLPROXY_' . $type_str)) {
$types[] = constant('CURLPROXY_' . $type_str);
}
}
if (! in_array($type, $types)) {
throw new \Exception('Invalid proxy type specified.');
}
$this->_proxy['host'] = $host;
$this->_proxy['port'] = (int) $port;
$this->_proxy['type'] = $type;
} | [
"public",
"function",
"setProxy",
"(",
"$",
"host",
",",
"$",
"port",
",",
"$",
"type",
"=",
"CURLPROXY_HTTP",
")",
"{",
"static",
"$",
"types_str",
"=",
"[",
"'HTTP'",
",",
"'SOCKS4'",
",",
"'SOCKS5'",
",",
"'SOCKS4A'",
",",
"'SOCKS5_HOSTNAME'",
"]",
";... | Sets the proxy
@param string $host Proxy host
@param int $port Proxy port
@param int optional $type Proxy type, defaults to HTTP
@return void
@throws \Exception | [
"Sets",
"the",
"proxy"
] | train | https://github.com/jublo/codebird-php/blob/0c20a63e95640f56102e76d3ca14462b3908acc1/src/codebird.php#L772-L790 |
jublo/codebird-php | src/codebird.php | Codebird._parseApiParams | protected function _parseApiParams($params)
{
$apiparams = [];
if (count($params) === 0) {
return $apiparams;
}
if (is_array($params[0])) {
// given parameters are array
$apiparams = $params[0];
return $apiparams;
}
// user gave us query-style params
parse_str($params[0], $apiparams);
if (! is_array($apiparams)) {
$apiparams = [];
}
return $apiparams;
} | php | protected function _parseApiParams($params)
{
$apiparams = [];
if (count($params) === 0) {
return $apiparams;
}
if (is_array($params[0])) {
// given parameters are array
$apiparams = $params[0];
return $apiparams;
}
// user gave us query-style params
parse_str($params[0], $apiparams);
if (! is_array($apiparams)) {
$apiparams = [];
}
return $apiparams;
} | [
"protected",
"function",
"_parseApiParams",
"(",
"$",
"params",
")",
"{",
"$",
"apiparams",
"=",
"[",
"]",
";",
"if",
"(",
"count",
"(",
"$",
"params",
")",
"===",
"0",
")",
"{",
"return",
"$",
"apiparams",
";",
"}",
"if",
"(",
"is_array",
"(",
"$"... | Parse given params, detect query-style params
@param array|string $params Parameters to parse
@return array $apiparams | [
"Parse",
"given",
"params",
"detect",
"query",
"-",
"style",
"params"
] | train | https://github.com/jublo/codebird-php/blob/0c20a63e95640f56102e76d3ca14462b3908acc1/src/codebird.php#L896-L916 |
jublo/codebird-php | src/codebird.php | Codebird._stringifyNullBoolParams | protected function _stringifyNullBoolParams($apiparams)
{
foreach ($apiparams as $key => $value) {
if (! is_scalar($value)) {
// no need to try replacing arrays
continue;
}
if (is_null($value)) {
$apiparams[$key] = 'null';
} elseif (is_bool($value)) {
$apiparams[$key] = $value ? 'true' : 'false';
}
}
return $apiparams;
} | php | protected function _stringifyNullBoolParams($apiparams)
{
foreach ($apiparams as $key => $value) {
if (! is_scalar($value)) {
// no need to try replacing arrays
continue;
}
if (is_null($value)) {
$apiparams[$key] = 'null';
} elseif (is_bool($value)) {
$apiparams[$key] = $value ? 'true' : 'false';
}
}
return $apiparams;
} | [
"protected",
"function",
"_stringifyNullBoolParams",
"(",
"$",
"apiparams",
")",
"{",
"foreach",
"(",
"$",
"apiparams",
"as",
"$",
"key",
"=>",
"$",
"value",
")",
"{",
"if",
"(",
"!",
"is_scalar",
"(",
"$",
"value",
")",
")",
"{",
"// no need to try replac... | Replace null and boolean parameters with their string representations
@param array $apiparams Parameter array to replace in
@return array $apiparams | [
"Replace",
"null",
"and",
"boolean",
"parameters",
"with",
"their",
"string",
"representations"
] | train | https://github.com/jublo/codebird-php/blob/0c20a63e95640f56102e76d3ca14462b3908acc1/src/codebird.php#L925-L940 |
jublo/codebird-php | src/codebird.php | Codebird._mapFnToApiMethod | protected function _mapFnToApiMethod($function, &$apiparams)
{
// replace _ by /
$method = $this->_mapFnInsertSlashes($function);
// undo replacement for URL parameters
$method = $this->_mapFnRestoreParamUnderscores($method);
// replace AA by URL parameters
list ($method, $method_template) = $this->_mapFnInlineParams($method, $apiparams);
if (substr($method, 0, 4) !== 'ton/') {
// replace A-Z by _a-z
for ($i = 0; $i < 26; $i++) {
$method = str_replace(chr(65 + $i), '_' . chr(97 + $i), $method);
$method_template = str_replace(chr(65 + $i), '_' . chr(97 + $i), $method_template);
}
}
return [$method, $method_template];
} | php | protected function _mapFnToApiMethod($function, &$apiparams)
{
// replace _ by /
$method = $this->_mapFnInsertSlashes($function);
// undo replacement for URL parameters
$method = $this->_mapFnRestoreParamUnderscores($method);
// replace AA by URL parameters
list ($method, $method_template) = $this->_mapFnInlineParams($method, $apiparams);
if (substr($method, 0, 4) !== 'ton/') {
// replace A-Z by _a-z
for ($i = 0; $i < 26; $i++) {
$method = str_replace(chr(65 + $i), '_' . chr(97 + $i), $method);
$method_template = str_replace(chr(65 + $i), '_' . chr(97 + $i), $method_template);
}
}
return [$method, $method_template];
} | [
"protected",
"function",
"_mapFnToApiMethod",
"(",
"$",
"function",
",",
"&",
"$",
"apiparams",
")",
"{",
"// replace _ by /",
"$",
"method",
"=",
"$",
"this",
"->",
"_mapFnInsertSlashes",
"(",
"$",
"function",
")",
";",
"// undo replacement for URL parameters",
"... | Maps called PHP magic method name to Twitter API method
@param string $function Function called
@param array $apiparams byref API parameters
@return string[] (string method, string method_template) | [
"Maps",
"called",
"PHP",
"magic",
"method",
"name",
"to",
"Twitter",
"API",
"method"
] | train | https://github.com/jublo/codebird-php/blob/0c20a63e95640f56102e76d3ca14462b3908acc1/src/codebird.php#L950-L970 |
jublo/codebird-php | src/codebird.php | Codebird._mapFnRestoreParamUnderscores | protected function _mapFnRestoreParamUnderscores($method)
{
$params = [
'screen_name', 'place_id', 'env_name',
'account_id', 'campaign_id', 'card_id', 'line_item_id',
'tweet_id', 'web_event_tag_id'
];
foreach ($params as $param) {
$param = strtoupper($param);
$replacement_was = str_replace('_', '/', $param);
$method = str_replace($replacement_was, $param, $method);
}
return $method;
} | php | protected function _mapFnRestoreParamUnderscores($method)
{
$params = [
'screen_name', 'place_id', 'env_name',
'account_id', 'campaign_id', 'card_id', 'line_item_id',
'tweet_id', 'web_event_tag_id'
];
foreach ($params as $param) {
$param = strtoupper($param);
$replacement_was = str_replace('_', '/', $param);
$method = str_replace($replacement_was, $param, $method);
}
return $method;
} | [
"protected",
"function",
"_mapFnRestoreParamUnderscores",
"(",
"$",
"method",
")",
"{",
"$",
"params",
"=",
"[",
"'screen_name'",
",",
"'place_id'",
",",
"'env_name'",
",",
"'account_id'",
",",
"'campaign_id'",
",",
"'card_id'",
",",
"'line_item_id'",
",",
"'tweet... | API method mapping: Restore _ character in named parameters
@param string $method API method to call
@return string API method with restored underscores | [
"API",
"method",
"mapping",
":",
"Restore",
"_",
"character",
"in",
"named",
"parameters"
] | train | https://github.com/jublo/codebird-php/blob/0c20a63e95640f56102e76d3ca14462b3908acc1/src/codebird.php#L991-L1005 |
jublo/codebird-php | src/codebird.php | Codebird._mapFnInlineParams | protected function _mapFnInlineParams($method, &$apiparams)
{
$method_template = $method;
$match = [];
if (preg_match_all('/[A-Z_]{2,}/', $method, $match)) {
foreach ($match[0] as $param) {
$param_l = strtolower($param);
if ($param_l === 'resumeid') {
$param_l = 'resumeId';
}
$method_template = str_replace($param, ':' . $param_l, $method_template);
if (! isset($apiparams[$param_l])) {
for ($i = 0; $i < 26; $i++) {
$method_template = str_replace(chr(65 + $i), '_' . chr(97 + $i), $method_template);
}
throw new \Exception(
'To call the templated method "' . $method_template
. '", specify the parameter value for "' . $param_l . '".'
);
}
$method = str_replace($param, $apiparams[$param_l], $method);
unset($apiparams[$param_l]);
}
}
return [$method, $method_template];
} | php | protected function _mapFnInlineParams($method, &$apiparams)
{
$method_template = $method;
$match = [];
if (preg_match_all('/[A-Z_]{2,}/', $method, $match)) {
foreach ($match[0] as $param) {
$param_l = strtolower($param);
if ($param_l === 'resumeid') {
$param_l = 'resumeId';
}
$method_template = str_replace($param, ':' . $param_l, $method_template);
if (! isset($apiparams[$param_l])) {
for ($i = 0; $i < 26; $i++) {
$method_template = str_replace(chr(65 + $i), '_' . chr(97 + $i), $method_template);
}
throw new \Exception(
'To call the templated method "' . $method_template
. '", specify the parameter value for "' . $param_l . '".'
);
}
$method = str_replace($param, $apiparams[$param_l], $method);
unset($apiparams[$param_l]);
}
}
return [$method, $method_template];
} | [
"protected",
"function",
"_mapFnInlineParams",
"(",
"$",
"method",
",",
"&",
"$",
"apiparams",
")",
"{",
"$",
"method_template",
"=",
"$",
"method",
";",
"$",
"match",
"=",
"[",
"]",
";",
"if",
"(",
"preg_match_all",
"(",
"'/[A-Z_]{2,}/'",
",",
"$",
"met... | Inserts inline parameters into the method name
@param string $method The method to call
@param array byref $apiparams The parameters to send along
@return string[] (string method, string method_template)
@throws \Exception | [
"Inserts",
"inline",
"parameters",
"into",
"the",
"method",
"name"
] | train | https://github.com/jublo/codebird-php/blob/0c20a63e95640f56102e76d3ca14462b3908acc1/src/codebird.php#L1016-L1042 |
jublo/codebird-php | src/codebird.php | Codebird._json_decode | protected function _json_decode($data, $need_array = false)
{
if (!(defined('JSON_C_VERSION') && PHP_INT_SIZE > 4)) {
return json_decode($data, $need_array, 512, JSON_BIGINT_AS_STRING);
}
return json_decode($data, $need_array);
} | php | protected function _json_decode($data, $need_array = false)
{
if (!(defined('JSON_C_VERSION') && PHP_INT_SIZE > 4)) {
return json_decode($data, $need_array, 512, JSON_BIGINT_AS_STRING);
}
return json_decode($data, $need_array);
} | [
"protected",
"function",
"_json_decode",
"(",
"$",
"data",
",",
"$",
"need_array",
"=",
"false",
")",
"{",
"if",
"(",
"!",
"(",
"defined",
"(",
"'JSON_C_VERSION'",
")",
"&&",
"PHP_INT_SIZE",
">",
"4",
")",
")",
"{",
"return",
"json_decode",
"(",
"$",
"... | Avoids any JSON_BIGINT_AS_STRING errors
@param string $data JSON data to decode
@param int optional $need_array Decode as array, otherwise as object
@return array|object The decoded object | [
"Avoids",
"any",
"JSON_BIGINT_AS_STRING",
"errors"
] | train | https://github.com/jublo/codebird-php/blob/0c20a63e95640f56102e76d3ca14462b3908acc1/src/codebird.php#L1052-L1058 |
jublo/codebird-php | src/codebird.php | Codebird.oauth_authenticate | public function oauth_authenticate($force_login = NULL, $screen_name = NULL, $type = 'authenticate')
{
if (! in_array($type, ['authenticate', 'authorize'])) {
throw new \Exception('To get the ' . $type . ' URL, use the correct third parameter, or omit it.');
}
if ($this->_oauth_token === null) {
throw new CodebirdCredentialsException('To get the ' . $type . ' URL, the OAuth token must be set.');
}
$url = self::$_endpoints['oauth'] . 'oauth/' . $type . '?oauth_token=' . $this->_url($this->_oauth_token);
if ($force_login) {
$url .= "&force_login=1";
}
if ($screen_name) {
$url .= "&screen_name=" . $screen_name;
}
return $url;
} | php | public function oauth_authenticate($force_login = NULL, $screen_name = NULL, $type = 'authenticate')
{
if (! in_array($type, ['authenticate', 'authorize'])) {
throw new \Exception('To get the ' . $type . ' URL, use the correct third parameter, or omit it.');
}
if ($this->_oauth_token === null) {
throw new CodebirdCredentialsException('To get the ' . $type . ' URL, the OAuth token must be set.');
}
$url = self::$_endpoints['oauth'] . 'oauth/' . $type . '?oauth_token=' . $this->_url($this->_oauth_token);
if ($force_login) {
$url .= "&force_login=1";
}
if ($screen_name) {
$url .= "&screen_name=" . $screen_name;
}
return $url;
} | [
"public",
"function",
"oauth_authenticate",
"(",
"$",
"force_login",
"=",
"NULL",
",",
"$",
"screen_name",
"=",
"NULL",
",",
"$",
"type",
"=",
"'authenticate'",
")",
"{",
"if",
"(",
"!",
"in_array",
"(",
"$",
"type",
",",
"[",
"'authenticate'",
",",
"'au... | Gets the OAuth authenticate URL for the current request token
@param optional bool $force_login Whether to force the user to enter their login data
@param optional string $screen_name Screen name to repopulate the user name with
@param optional string $type 'authenticate' or 'authorize', to avoid duplicate code
@return string The OAuth authenticate/authorize URL
@throws \Exception | [
"Gets",
"the",
"OAuth",
"authenticate",
"URL",
"for",
"the",
"current",
"request",
"token"
] | train | https://github.com/jublo/codebird-php/blob/0c20a63e95640f56102e76d3ca14462b3908acc1/src/codebird.php#L1074-L1090 |
jublo/codebird-php | src/codebird.php | Codebird._getCurlInitialization | protected function _getCurlInitialization($url)
{
$connection = $this->_curl_init($url);
$this->_curl_setopt($connection, CURLOPT_RETURNTRANSFER, 1);
$this->_curl_setopt($connection, CURLOPT_FOLLOWLOCATION, 0);
$this->_curl_setopt($connection, CURLOPT_HEADER, 1);
$this->_curl_setopt($connection, CURLOPT_SSL_VERIFYPEER, 1);
$this->_curl_setopt($connection, CURLOPT_SSL_VERIFYHOST, 2);
$this->_curl_setopt($connection, CURLOPT_CAINFO, __DIR__ . '/cacert.pem');
$this->_curl_setopt(
$connection, CURLOPT_USERAGENT,
'codebird-php/' . $this->getVersion() . ' +https://github.com/jublonet/codebird-php'
);
if ($this->_hasProxy()) {
$this->_curl_setopt($connection, CURLOPT_PROXYTYPE, $this->_getProxyType());
$this->_curl_setopt($connection, CURLOPT_PROXY, $this->_getProxyHost());
$this->_curl_setopt($connection, CURLOPT_PROXYPORT, $this->_getProxyPort());
if ($this->_getProxyAuthentication()) {
$this->_curl_setopt($connection, CURLOPT_PROXYAUTH, CURLAUTH_BASIC);
$this->_curl_setopt($connection, CURLOPT_PROXYUSERPWD, $this->_getProxyAuthentication());
}
}
return $connection;
} | php | protected function _getCurlInitialization($url)
{
$connection = $this->_curl_init($url);
$this->_curl_setopt($connection, CURLOPT_RETURNTRANSFER, 1);
$this->_curl_setopt($connection, CURLOPT_FOLLOWLOCATION, 0);
$this->_curl_setopt($connection, CURLOPT_HEADER, 1);
$this->_curl_setopt($connection, CURLOPT_SSL_VERIFYPEER, 1);
$this->_curl_setopt($connection, CURLOPT_SSL_VERIFYHOST, 2);
$this->_curl_setopt($connection, CURLOPT_CAINFO, __DIR__ . '/cacert.pem');
$this->_curl_setopt(
$connection, CURLOPT_USERAGENT,
'codebird-php/' . $this->getVersion() . ' +https://github.com/jublonet/codebird-php'
);
if ($this->_hasProxy()) {
$this->_curl_setopt($connection, CURLOPT_PROXYTYPE, $this->_getProxyType());
$this->_curl_setopt($connection, CURLOPT_PROXY, $this->_getProxyHost());
$this->_curl_setopt($connection, CURLOPT_PROXYPORT, $this->_getProxyPort());
if ($this->_getProxyAuthentication()) {
$this->_curl_setopt($connection, CURLOPT_PROXYAUTH, CURLAUTH_BASIC);
$this->_curl_setopt($connection, CURLOPT_PROXYUSERPWD, $this->_getProxyAuthentication());
}
}
return $connection;
} | [
"protected",
"function",
"_getCurlInitialization",
"(",
"$",
"url",
")",
"{",
"$",
"connection",
"=",
"$",
"this",
"->",
"_curl_init",
"(",
"$",
"url",
")",
";",
"$",
"this",
"->",
"_curl_setopt",
"(",
"$",
"connection",
",",
"CURLOPT_RETURNTRANSFER",
",",
... | Gets a cURL handle
@param string $url the URL for the curl initialization
@return resource handle | [
"Gets",
"a",
"cURL",
"handle"
] | train | https://github.com/jublo/codebird-php/blob/0c20a63e95640f56102e76d3ca14462b3908acc1/src/codebird.php#L1123-L1150 |
jublo/codebird-php | src/codebird.php | Codebird._getNoCurlInitialization | protected function _getNoCurlInitialization($url, $contextOptions, $hostname = '')
{
$httpOptions = [];
$httpOptions['header'] = [
'User-Agent: codebird-php/' . $this->getVersion() . ' +https://github.com/jublonet/codebird-php'
];
$httpOptions['ssl'] = [
'verify_peer' => true,
'cafile' => __DIR__ . '/cacert.pem',
'verify_depth' => 5,
'peer_name' => $hostname
];
if ($this->_hasProxy()) {
$httpOptions['request_fulluri'] = true;
$httpOptions['proxy'] = $this->_getProxyHost() . ':' . $this->_getProxyPort();
if ($this->_getProxyAuthentication()) {
$httpOptions['header'][] =
'Proxy-Authorization: Basic ' . base64_encode($this->_getProxyAuthentication());
}
}
// merge the http options with the context options
$options = array_merge_recursive(
$contextOptions,
['http' => $httpOptions]
);
// concatenate $options['http']['header']
$options['http']['header'] = implode("\r\n", $options['http']['header']);
// silent the file_get_contents function
$content = @file_get_contents($url, false, stream_context_create($options));
$headers = [];
// API is responding
if (isset($http_response_header)) {
$headers = $http_response_header;
}
return [
$content,
$headers
];
} | php | protected function _getNoCurlInitialization($url, $contextOptions, $hostname = '')
{
$httpOptions = [];
$httpOptions['header'] = [
'User-Agent: codebird-php/' . $this->getVersion() . ' +https://github.com/jublonet/codebird-php'
];
$httpOptions['ssl'] = [
'verify_peer' => true,
'cafile' => __DIR__ . '/cacert.pem',
'verify_depth' => 5,
'peer_name' => $hostname
];
if ($this->_hasProxy()) {
$httpOptions['request_fulluri'] = true;
$httpOptions['proxy'] = $this->_getProxyHost() . ':' . $this->_getProxyPort();
if ($this->_getProxyAuthentication()) {
$httpOptions['header'][] =
'Proxy-Authorization: Basic ' . base64_encode($this->_getProxyAuthentication());
}
}
// merge the http options with the context options
$options = array_merge_recursive(
$contextOptions,
['http' => $httpOptions]
);
// concatenate $options['http']['header']
$options['http']['header'] = implode("\r\n", $options['http']['header']);
// silent the file_get_contents function
$content = @file_get_contents($url, false, stream_context_create($options));
$headers = [];
// API is responding
if (isset($http_response_header)) {
$headers = $http_response_header;
}
return [
$content,
$headers
];
} | [
"protected",
"function",
"_getNoCurlInitialization",
"(",
"$",
"url",
",",
"$",
"contextOptions",
",",
"$",
"hostname",
"=",
"''",
")",
"{",
"$",
"httpOptions",
"=",
"[",
"]",
";",
"$",
"httpOptions",
"[",
"'header'",
"]",
"=",
"[",
"'User-Agent: codebird-ph... | Gets a non cURL initialization
@param string $url the URL for the curl initialization
@param array $contextOptions the options for the stream context
@param string $hostname the hostname to verify the SSL FQDN for
@return array the read data | [
"Gets",
"a",
"non",
"cURL",
"initialization"
] | train | https://github.com/jublo/codebird-php/blob/0c20a63e95640f56102e76d3ca14462b3908acc1/src/codebird.php#L1161-L1208 |
jublo/codebird-php | src/codebird.php | Codebird._getProxyData | private function _getProxyData($name)
{
return empty($this->_proxy[$name]) ? null : $this->_proxy[$name];
} | php | private function _getProxyData($name)
{
return empty($this->_proxy[$name]) ? null : $this->_proxy[$name];
} | [
"private",
"function",
"_getProxyData",
"(",
"$",
"name",
")",
"{",
"return",
"empty",
"(",
"$",
"this",
"->",
"_proxy",
"[",
"$",
"name",
"]",
")",
"?",
"null",
":",
"$",
"this",
"->",
"_proxy",
"[",
"$",
"name",
"]",
";",
"}"
] | Gets data from the proxy configuration
@param string $name | [
"Gets",
"data",
"from",
"the",
"proxy",
"configuration"
] | train | https://github.com/jublo/codebird-php/blob/0c20a63e95640f56102e76d3ca14462b3908acc1/src/codebird.php#L1260-L1263 |
jublo/codebird-php | src/codebird.php | Codebird._oauth2TokenCurl | protected function _oauth2TokenCurl()
{
if (self::$_consumer_key === null) {
throw new CodebirdCredentialsException('To obtain a bearer token, the consumer key must be set.');
}
$post_fields = [
'grant_type' => 'client_credentials'
];
$url = self::$_endpoints['oauth'] . 'oauth2/token';
$connection = $this->_getCurlInitialization($url);
$this->_curl_setopt($connection, CURLOPT_POST, 1);
$this->_curl_setopt($connection, CURLOPT_POSTFIELDS, $post_fields);
$this->_curl_setopt($connection, CURLOPT_USERPWD, self::$_consumer_key . ':' . self::$_consumer_secret);
$this->_curl_setopt($connection, CURLOPT_HTTPHEADER, [
'Expect:'
]);
$result = $this->_curl_exec($connection);
// catch request errors
if ($result === false) {
throw new CodebirdAuthException('Request error for bearer token: ' . $this->_curl_error($connection));
}
// certificate validation results
$validation_result = $this->_curl_errno($connection);
$this->_validateSslCertificate($validation_result);
$httpstatus = $this->_curl_getinfo($connection, CURLINFO_HTTP_CODE);
$reply = $this->_parseBearerReply($result, $httpstatus);
return $reply;
} | php | protected function _oauth2TokenCurl()
{
if (self::$_consumer_key === null) {
throw new CodebirdCredentialsException('To obtain a bearer token, the consumer key must be set.');
}
$post_fields = [
'grant_type' => 'client_credentials'
];
$url = self::$_endpoints['oauth'] . 'oauth2/token';
$connection = $this->_getCurlInitialization($url);
$this->_curl_setopt($connection, CURLOPT_POST, 1);
$this->_curl_setopt($connection, CURLOPT_POSTFIELDS, $post_fields);
$this->_curl_setopt($connection, CURLOPT_USERPWD, self::$_consumer_key . ':' . self::$_consumer_secret);
$this->_curl_setopt($connection, CURLOPT_HTTPHEADER, [
'Expect:'
]);
$result = $this->_curl_exec($connection);
// catch request errors
if ($result === false) {
throw new CodebirdAuthException('Request error for bearer token: ' . $this->_curl_error($connection));
}
// certificate validation results
$validation_result = $this->_curl_errno($connection);
$this->_validateSslCertificate($validation_result);
$httpstatus = $this->_curl_getinfo($connection, CURLINFO_HTTP_CODE);
$reply = $this->_parseBearerReply($result, $httpstatus);
return $reply;
} | [
"protected",
"function",
"_oauth2TokenCurl",
"(",
")",
"{",
"if",
"(",
"self",
"::",
"$",
"_consumer_key",
"===",
"null",
")",
"{",
"throw",
"new",
"CodebirdCredentialsException",
"(",
"'To obtain a bearer token, the consumer key must be set.'",
")",
";",
"}",
"$",
... | Gets the OAuth bearer token, using cURL
@return string The OAuth bearer token
@throws \Exception | [
"Gets",
"the",
"OAuth",
"bearer",
"token",
"using",
"cURL"
] | train | https://github.com/jublo/codebird-php/blob/0c20a63e95640f56102e76d3ca14462b3908acc1/src/codebird.php#L1272-L1303 |
jublo/codebird-php | src/codebird.php | Codebird._oauth2TokenNoCurl | protected function _oauth2TokenNoCurl()
{
if (self::$_consumer_key == null) {
throw new CodebirdCredentialsException('To obtain a bearer token, the consumer key must be set.');
}
$url = self::$_endpoints['oauth'] . 'oauth2/token';
$hostname = parse_url($url, PHP_URL_HOST);
if ($hostname === false) {
throw new CodebirdEndpointException('Incorrect API endpoint host.');
}
$contextOptions = [
'http' => [
'method' => 'POST',
'protocol_version' => '1.1',
'header' => "Accept: */*\r\n"
. 'Authorization: Basic '
. base64_encode(
self::$_consumer_key
. ':'
. self::$_consumer_secret
),
'timeout' => $this->_timeouts['request'] / 1000,
'content' => 'grant_type=client_credentials',
'ignore_errors' => true
]
];
list($reply, $headers) = $this->_getNoCurlInitialization($url, $contextOptions, $hostname);
$result = '';
foreach ($headers as $header) {
$result .= $header . "\r\n";
}
$result .= "\r\n" . $reply;
// find HTTP status
$httpstatus = $this->_getHttpStatusFromHeaders($headers);
$reply = $this->_parseBearerReply($result, $httpstatus);
return $reply;
} | php | protected function _oauth2TokenNoCurl()
{
if (self::$_consumer_key == null) {
throw new CodebirdCredentialsException('To obtain a bearer token, the consumer key must be set.');
}
$url = self::$_endpoints['oauth'] . 'oauth2/token';
$hostname = parse_url($url, PHP_URL_HOST);
if ($hostname === false) {
throw new CodebirdEndpointException('Incorrect API endpoint host.');
}
$contextOptions = [
'http' => [
'method' => 'POST',
'protocol_version' => '1.1',
'header' => "Accept: */*\r\n"
. 'Authorization: Basic '
. base64_encode(
self::$_consumer_key
. ':'
. self::$_consumer_secret
),
'timeout' => $this->_timeouts['request'] / 1000,
'content' => 'grant_type=client_credentials',
'ignore_errors' => true
]
];
list($reply, $headers) = $this->_getNoCurlInitialization($url, $contextOptions, $hostname);
$result = '';
foreach ($headers as $header) {
$result .= $header . "\r\n";
}
$result .= "\r\n" . $reply;
// find HTTP status
$httpstatus = $this->_getHttpStatusFromHeaders($headers);
$reply = $this->_parseBearerReply($result, $httpstatus);
return $reply;
} | [
"protected",
"function",
"_oauth2TokenNoCurl",
"(",
")",
"{",
"if",
"(",
"self",
"::",
"$",
"_consumer_key",
"==",
"null",
")",
"{",
"throw",
"new",
"CodebirdCredentialsException",
"(",
"'To obtain a bearer token, the consumer key must be set.'",
")",
";",
"}",
"$",
... | Gets the OAuth bearer token, without cURL
@return string The OAuth bearer token
@throws \Exception | [
"Gets",
"the",
"OAuth",
"bearer",
"token",
"without",
"cURL"
] | train | https://github.com/jublo/codebird-php/blob/0c20a63e95640f56102e76d3ca14462b3908acc1/src/codebird.php#L1312-L1352 |
jublo/codebird-php | src/codebird.php | Codebird._getHttpStatusFromHeaders | protected function _getHttpStatusFromHeaders($headers)
{
$httpstatus = '500';
$match = [];
if (!empty($headers[0]) && preg_match('/HTTP\/\d\.\d (\d{3})/', $headers[0], $match)) {
$httpstatus = $match[1];
}
return $httpstatus;
} | php | protected function _getHttpStatusFromHeaders($headers)
{
$httpstatus = '500';
$match = [];
if (!empty($headers[0]) && preg_match('/HTTP\/\d\.\d (\d{3})/', $headers[0], $match)) {
$httpstatus = $match[1];
}
return $httpstatus;
} | [
"protected",
"function",
"_getHttpStatusFromHeaders",
"(",
"$",
"headers",
")",
"{",
"$",
"httpstatus",
"=",
"'500'",
";",
"$",
"match",
"=",
"[",
"]",
";",
"if",
"(",
"!",
"empty",
"(",
"$",
"headers",
"[",
"0",
"]",
")",
"&&",
"preg_match",
"(",
"'... | Extract HTTP status code from headers
@param array $headers The headers to parse
@return string The HTTP status code | [
"Extract",
"HTTP",
"status",
"code",
"from",
"headers"
] | train | https://github.com/jublo/codebird-php/blob/0c20a63e95640f56102e76d3ca14462b3908acc1/src/codebird.php#L1366-L1374 |
jublo/codebird-php | src/codebird.php | Codebird._parseBearerReply | protected function _parseBearerReply($result, $httpstatus)
{
list($headers, $reply) = $this->_parseApiHeaders($result);
$reply = $this->_parseApiReply($reply);
$rate = $this->_getRateLimitInfo($headers);
switch ($this->_return_format) {
case CODEBIRD_RETURNFORMAT_ARRAY:
$reply['httpstatus'] = $httpstatus;
$reply['rate'] = $rate;
if ($httpstatus === 200) {
self::setBearerToken($reply['access_token']);
}
break;
case CODEBIRD_RETURNFORMAT_JSON:
if ($httpstatus === 200) {
$parsed = $this->_json_decode($reply);
self::setBearerToken($parsed->access_token);
}
break;
case CODEBIRD_RETURNFORMAT_OBJECT:
$reply->httpstatus = $httpstatus;
$reply->rate = $rate;
if ($httpstatus === 200) {
self::setBearerToken($reply->access_token);
}
break;
}
return $reply;
} | php | protected function _parseBearerReply($result, $httpstatus)
{
list($headers, $reply) = $this->_parseApiHeaders($result);
$reply = $this->_parseApiReply($reply);
$rate = $this->_getRateLimitInfo($headers);
switch ($this->_return_format) {
case CODEBIRD_RETURNFORMAT_ARRAY:
$reply['httpstatus'] = $httpstatus;
$reply['rate'] = $rate;
if ($httpstatus === 200) {
self::setBearerToken($reply['access_token']);
}
break;
case CODEBIRD_RETURNFORMAT_JSON:
if ($httpstatus === 200) {
$parsed = $this->_json_decode($reply);
self::setBearerToken($parsed->access_token);
}
break;
case CODEBIRD_RETURNFORMAT_OBJECT:
$reply->httpstatus = $httpstatus;
$reply->rate = $rate;
if ($httpstatus === 200) {
self::setBearerToken($reply->access_token);
}
break;
}
return $reply;
} | [
"protected",
"function",
"_parseBearerReply",
"(",
"$",
"result",
",",
"$",
"httpstatus",
")",
"{",
"list",
"(",
"$",
"headers",
",",
"$",
"reply",
")",
"=",
"$",
"this",
"->",
"_parseApiHeaders",
"(",
"$",
"result",
")",
";",
"$",
"reply",
"=",
"$",
... | Parse oauth2_token reply and set bearer token, if found
@param string $result Raw HTTP response
@param int $httpstatus HTTP status code
@return string reply | [
"Parse",
"oauth2_token",
"reply",
"and",
"set",
"bearer",
"token",
"if",
"found"
] | train | https://github.com/jublo/codebird-php/blob/0c20a63e95640f56102e76d3ca14462b3908acc1/src/codebird.php#L1384-L1412 |
jublo/codebird-php | src/codebird.php | Codebird._getRateLimitInfo | protected function _getRateLimitInfo($headers)
{
if (! isset($headers['x-rate-limit-limit'])) {
return null;
}
$rate = [
'limit' => $headers['x-rate-limit-limit'],
'remaining' => $headers['x-rate-limit-remaining'],
'reset' => $headers['x-rate-limit-reset']
];
if ($this->_return_format === CODEBIRD_RETURNFORMAT_OBJECT) {
return (object) $rate;
}
return $rate;
} | php | protected function _getRateLimitInfo($headers)
{
if (! isset($headers['x-rate-limit-limit'])) {
return null;
}
$rate = [
'limit' => $headers['x-rate-limit-limit'],
'remaining' => $headers['x-rate-limit-remaining'],
'reset' => $headers['x-rate-limit-reset']
];
if ($this->_return_format === CODEBIRD_RETURNFORMAT_OBJECT) {
return (object) $rate;
}
return $rate;
} | [
"protected",
"function",
"_getRateLimitInfo",
"(",
"$",
"headers",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"$",
"headers",
"[",
"'x-rate-limit-limit'",
"]",
")",
")",
"{",
"return",
"null",
";",
"}",
"$",
"rate",
"=",
"[",
"'limit'",
"=>",
"$",
"header... | Extract rate-limiting data from response headers
@param array $headers The CURL response headers
@return null|array|object The rate-limiting information | [
"Extract",
"rate",
"-",
"limiting",
"data",
"from",
"response",
"headers"
] | train | https://github.com/jublo/codebird-php/blob/0c20a63e95640f56102e76d3ca14462b3908acc1/src/codebird.php#L1421-L1435 |
jublo/codebird-php | src/codebird.php | Codebird._validateSslCertificate | protected function _validateSslCertificate($validation_result)
{
if (in_array(
$validation_result,
[
CURLE_SSL_CERTPROBLEM,
CURLE_SSL_CACERT,
CURLE_SSL_CACERT_BADFILE,
CURLE_SSL_CRL_BADFILE,
CURLE_SSL_ISSUER_ERROR
]
)
) {
throw new \Exception(
'Error ' . $validation_result
. ' while validating the Twitter API certificate.'
);
}
} | php | protected function _validateSslCertificate($validation_result)
{
if (in_array(
$validation_result,
[
CURLE_SSL_CERTPROBLEM,
CURLE_SSL_CACERT,
CURLE_SSL_CACERT_BADFILE,
CURLE_SSL_CRL_BADFILE,
CURLE_SSL_ISSUER_ERROR
]
)
) {
throw new \Exception(
'Error ' . $validation_result
. ' while validating the Twitter API certificate.'
);
}
} | [
"protected",
"function",
"_validateSslCertificate",
"(",
"$",
"validation_result",
")",
"{",
"if",
"(",
"in_array",
"(",
"$",
"validation_result",
",",
"[",
"CURLE_SSL_CERTPROBLEM",
",",
"CURLE_SSL_CACERT",
",",
"CURLE_SSL_CACERT_BADFILE",
",",
"CURLE_SSL_CRL_BADFILE",
... | Check if there were any SSL certificate errors
@param int $validation_result The curl error number
@return void
@throws \Exception | [
"Check",
"if",
"there",
"were",
"any",
"SSL",
"certificate",
"errors"
] | train | https://github.com/jublo/codebird-php/blob/0c20a63e95640f56102e76d3ca14462b3908acc1/src/codebird.php#L1445-L1463 |
jublo/codebird-php | src/codebird.php | Codebird._url | protected function _url($data)
{
if (is_array($data)) {
return array_map([
$this,
'_url'
], $data);
} elseif (is_scalar($data)) {
return str_replace([
'+',
'!',
'*',
"'",
'(',
')'
], [
' ',
'%21',
'%2A',
'%27',
'%28',
'%29'
], rawurlencode($data));
}
return '';
} | php | protected function _url($data)
{
if (is_array($data)) {
return array_map([
$this,
'_url'
], $data);
} elseif (is_scalar($data)) {
return str_replace([
'+',
'!',
'*',
"'",
'(',
')'
], [
' ',
'%21',
'%2A',
'%27',
'%28',
'%29'
], rawurlencode($data));
}
return '';
} | [
"protected",
"function",
"_url",
"(",
"$",
"data",
")",
"{",
"if",
"(",
"is_array",
"(",
"$",
"data",
")",
")",
"{",
"return",
"array_map",
"(",
"[",
"$",
"this",
",",
"'_url'",
"]",
",",
"$",
"data",
")",
";",
"}",
"elseif",
"(",
"is_scalar",
"(... | URL-encodes the given data
@param mixed $data
@return mixed The encoded data | [
"URL",
"-",
"encodes",
"the",
"given",
"data"
] | train | https://github.com/jublo/codebird-php/blob/0c20a63e95640f56102e76d3ca14462b3908acc1/src/codebird.php#L1476-L1501 |
jublo/codebird-php | src/codebird.php | Codebird._sha1 | protected function _sha1($data)
{
if (self::$_consumer_secret === null) {
throw new CodebirdCredentialsException('To generate a hash, the consumer secret must be set.');
}
if (!function_exists('hash_hmac')) {
throw new \Exception('To generate a hash, the PHP hash extension must be available.');
}
return base64_encode(hash_hmac(
'sha1',
$data,
self::$_consumer_secret
. '&'
. ($this->_oauth_token_secret !== null
? $this->_oauth_token_secret
: ''
),
true
));
} | php | protected function _sha1($data)
{
if (self::$_consumer_secret === null) {
throw new CodebirdCredentialsException('To generate a hash, the consumer secret must be set.');
}
if (!function_exists('hash_hmac')) {
throw new \Exception('To generate a hash, the PHP hash extension must be available.');
}
return base64_encode(hash_hmac(
'sha1',
$data,
self::$_consumer_secret
. '&'
. ($this->_oauth_token_secret !== null
? $this->_oauth_token_secret
: ''
),
true
));
} | [
"protected",
"function",
"_sha1",
"(",
"$",
"data",
")",
"{",
"if",
"(",
"self",
"::",
"$",
"_consumer_secret",
"===",
"null",
")",
"{",
"throw",
"new",
"CodebirdCredentialsException",
"(",
"'To generate a hash, the consumer secret must be set.'",
")",
";",
"}",
"... | Gets the base64-encoded SHA1 hash for the given data
@param string $data The data to calculate the hash from
@return string The hash
@throws \Exception | [
"Gets",
"the",
"base64",
"-",
"encoded",
"SHA1",
"hash",
"for",
"the",
"given",
"data"
] | train | https://github.com/jublo/codebird-php/blob/0c20a63e95640f56102e76d3ca14462b3908acc1/src/codebird.php#L1511-L1530 |
jublo/codebird-php | src/codebird.php | Codebird._nonce | protected function _nonce($length = 8)
{
if ($length < 1) {
throw new \Exception('Invalid nonce length.');
}
return substr(md5($this->_microtime(true)), 0, $length);
} | php | protected function _nonce($length = 8)
{
if ($length < 1) {
throw new \Exception('Invalid nonce length.');
}
return substr(md5($this->_microtime(true)), 0, $length);
} | [
"protected",
"function",
"_nonce",
"(",
"$",
"length",
"=",
"8",
")",
"{",
"if",
"(",
"$",
"length",
"<",
"1",
")",
"{",
"throw",
"new",
"\\",
"Exception",
"(",
"'Invalid nonce length.'",
")",
";",
"}",
"return",
"substr",
"(",
"md5",
"(",
"$",
"this... | Generates a (hopefully) unique random string
@param int optional $length The length of the string to generate
@return string The random string
@throws \Exception | [
"Generates",
"a",
"(",
"hopefully",
")",
"unique",
"random",
"string"
] | train | https://github.com/jublo/codebird-php/blob/0c20a63e95640f56102e76d3ca14462b3908acc1/src/codebird.php#L1540-L1546 |
jublo/codebird-php | src/codebird.php | Codebird._getSignature | protected function _getSignature($httpmethod, $method, $base_params)
{
// convert params to string
$base_string = '';
foreach ($base_params as $key => $value) {
$base_string .= $key . '=' . $value . '&';
}
// trim last ampersand
$base_string = substr($base_string, 0, -1);
// hash it
return $this->_sha1(
$httpmethod . '&' .
$this->_url($method) . '&' .
$this->_url($base_string)
);
} | php | protected function _getSignature($httpmethod, $method, $base_params)
{
// convert params to string
$base_string = '';
foreach ($base_params as $key => $value) {
$base_string .= $key . '=' . $value . '&';
}
// trim last ampersand
$base_string = substr($base_string, 0, -1);
// hash it
return $this->_sha1(
$httpmethod . '&' .
$this->_url($method) . '&' .
$this->_url($base_string)
);
} | [
"protected",
"function",
"_getSignature",
"(",
"$",
"httpmethod",
",",
"$",
"method",
",",
"$",
"base_params",
")",
"{",
"// convert params to string",
"$",
"base_string",
"=",
"''",
";",
"foreach",
"(",
"$",
"base_params",
"as",
"$",
"key",
"=>",
"$",
"valu... | Signature helper
@param string $httpmethod Usually either 'GET' or 'POST' or 'DELETE'
@param string $method The API method to call
@param array $base_params The signature base parameters
@return string signature | [
"Signature",
"helper"
] | train | https://github.com/jublo/codebird-php/blob/0c20a63e95640f56102e76d3ca14462b3908acc1/src/codebird.php#L1557-L1574 |
jublo/codebird-php | src/codebird.php | Codebird._sign | protected function _sign($httpmethod, $method, $params = [])
{
if (self::$_consumer_key === null) {
throw new CodebirdCredentialsException('To generate a signature, the consumer key must be set.');
}
$sign_base_params = array_map(
[$this, '_url'],
[
'oauth_consumer_key' => self::$_consumer_key,
'oauth_version' => '1.0',
'oauth_timestamp' => $this->_time(),
'oauth_nonce' => $this->_nonce(),
'oauth_signature_method' => 'HMAC-SHA1'
]
);
if ($this->_oauth_token !== null) {
$sign_base_params['oauth_token'] = $this->_url($this->_oauth_token);
}
$oauth_params = $sign_base_params;
// merge in the non-OAuth params
$sign_base_params = array_merge(
$sign_base_params,
array_map([$this, '_url'], $params)
);
ksort($sign_base_params);
$signature = $this->_getSignature($httpmethod, $method, $sign_base_params);
$params = $oauth_params;
$params['oauth_signature'] = $signature;
ksort($params);
$authorization = 'OAuth ';
foreach ($params as $key => $value) {
$authorization .= $key . "=\"" . $this->_url($value) . "\", ";
}
return substr($authorization, 0, -2);
} | php | protected function _sign($httpmethod, $method, $params = [])
{
if (self::$_consumer_key === null) {
throw new CodebirdCredentialsException('To generate a signature, the consumer key must be set.');
}
$sign_base_params = array_map(
[$this, '_url'],
[
'oauth_consumer_key' => self::$_consumer_key,
'oauth_version' => '1.0',
'oauth_timestamp' => $this->_time(),
'oauth_nonce' => $this->_nonce(),
'oauth_signature_method' => 'HMAC-SHA1'
]
);
if ($this->_oauth_token !== null) {
$sign_base_params['oauth_token'] = $this->_url($this->_oauth_token);
}
$oauth_params = $sign_base_params;
// merge in the non-OAuth params
$sign_base_params = array_merge(
$sign_base_params,
array_map([$this, '_url'], $params)
);
ksort($sign_base_params);
$signature = $this->_getSignature($httpmethod, $method, $sign_base_params);
$params = $oauth_params;
$params['oauth_signature'] = $signature;
ksort($params);
$authorization = 'OAuth ';
foreach ($params as $key => $value) {
$authorization .= $key . "=\"" . $this->_url($value) . "\", ";
}
return substr($authorization, 0, -2);
} | [
"protected",
"function",
"_sign",
"(",
"$",
"httpmethod",
",",
"$",
"method",
",",
"$",
"params",
"=",
"[",
"]",
")",
"{",
"if",
"(",
"self",
"::",
"$",
"_consumer_key",
"===",
"null",
")",
"{",
"throw",
"new",
"CodebirdCredentialsException",
"(",
"'To g... | Generates an OAuth signature
@param string $httpmethod Usually either 'GET' or 'POST' or 'DELETE'
@param string $method The API method to call
@param array optional $params The API call parameters, associative
@return string Authorization HTTP header
@throws \Exception | [
"Generates",
"an",
"OAuth",
"signature"
] | train | https://github.com/jublo/codebird-php/blob/0c20a63e95640f56102e76d3ca14462b3908acc1/src/codebird.php#L1586-L1624 |
jublo/codebird-php | src/codebird.php | Codebird._detectMethod | protected function _detectMethod($method, &$params)
{
if (isset($params['httpmethod'])) {
$httpmethod = $params['httpmethod'];
unset($params['httpmethod']);
return $httpmethod;
}
$apimethods = $this->getApiMethods();
// multi-HTTP method API methods
// parameter-based detection
$httpmethods_by_param = [
'POST' => [
'campaign_id' => [
'ads/accounts/:account_id/line_items',
'ads/sandbox/accounts/:account_id/line_items'
],
'media_id' => [
'ads/accounts/:account_id/account_media',
'ads/sandbox/accounts/:account_id/account_media'
],
'name' => [
'ads/accounts/:account_id/app_lists',
'ads/accounts/:account_id/campaigns',
'ads/accounts/:account_id/cards/app_download',
'ads/accounts/:account_id/cards/image_app_download',
'ads/accounts/:account_id/cards/image_conversation',
'ads/accounts/:account_id/cards/lead_gen',
'ads/accounts/:account_id/cards/video_app_download',
'ads/accounts/:account_id/cards/video_conversation',
'ads/accounts/:account_id/cards/website',
'ads/accounts/:account_id/tailored_audiences',
'ads/accounts/:account_id/web_event_tags',
'ads/sandbox/accounts/:account_id/app_lists',
'ads/sandbox/accounts/:account_id/campaigns',
'ads/sandbox/accounts/:account_id/cards/app_download',
'ads/sandbox/accounts/:account_id/cards/image_app_download',
'ads/sandbox/accounts/:account_id/cards/image_conversation',
'ads/sandbox/accounts/:account_id/cards/lead_gen',
'ads/sandbox/accounts/:account_id/cards/video_app_download',
'ads/sandbox/accounts/:account_id/cards/video_conversation',
'ads/sandbox/accounts/:account_id/cards/website',
'ads/sandbox/accounts/:account_id/tailored_audiences',
'ads/sandbox/accounts/:account_id/web_event_tags'
],
'permission_level' => [
'ads/accounts/:account_id/tailored_audiences/:id/permissions',
'ads/sandbox/accounts/:account_id/tailored_audiences/:id/permissions'
],
'tailored_audience_id' => [
'ads/accounts/:account_id/tailored_audience_changes',
'ads/sandbox/accounts/:account_id/tailored_audience_changes'
],
'targeting_value' => [
'ads/accounts/:account_id/targeting_criteria',
'ads/sandbox/accounts/:account_id/targeting_criteria'
],
'tweet_ids' => [
'ads/accounts/:account_id/promoted_tweets',
'ads/sandbox/accounts/:account_id/promoted_tweets'
],
'type' => [
'ads/sandbox/accounts/:account_id/features',
'ads/sandbox/accounts/:account_id/funding_instruments'
],
'url' => [
'account_activity/webhooks'
],
'user_id' => [
'ads/accounts/:account_id/promoted_accounts',
'ads/sandbox/accounts/:account_id/promoted_accounts'
],
'video_media_id' => [
'ads/accounts/:account_id/videos',
'ads/sandbox/accounts/:account_id/videos'
]
],
'PUT' => [
'name' => [
'ads/accounts/:account_id/cards/image_conversation/:card_id',
'ads/accounts/:account_id/cards/video_conversation/:card_id',
'ads/accounts/:account_id/cards/website/:card_id',
'ads/sandbox/accounts/:account_id/cards/image_conversation/:card_id',
'ads/sandbox/accounts/:account_id/cards/video_conversation/:card_id',
'ads/sandbox/accounts/:account_id/cards/website/:card_id'
]
]
];
foreach ($httpmethods_by_param as $httpmethod => $methods_by_param) {
foreach ($methods_by_param as $param => $methods) {
if (in_array($method, $methods) && isset($params[$param])) {
return $httpmethod;
}
}
}
// async media/upload calls may request a status by GET
if ($method === 'media/upload'
&& isset($params['command'])
&& $params['command'] === 'STATUS'
) {
return 'GET';
}
// prefer POST and PUT if parameters are set
if (count($params) > 0) {
if (in_array($method, $apimethods['POST'])) {
return 'POST';
}
if (in_array($method, $apimethods['PUT'])) {
return 'PUT';
}
}
foreach ($apimethods as $httpmethod => $methods) {
if (in_array($method, $methods)) {
return $httpmethod;
}
}
throw new \Exception('Can\'t find HTTP method to use for "' . $method . '".');
} | php | protected function _detectMethod($method, &$params)
{
if (isset($params['httpmethod'])) {
$httpmethod = $params['httpmethod'];
unset($params['httpmethod']);
return $httpmethod;
}
$apimethods = $this->getApiMethods();
// multi-HTTP method API methods
// parameter-based detection
$httpmethods_by_param = [
'POST' => [
'campaign_id' => [
'ads/accounts/:account_id/line_items',
'ads/sandbox/accounts/:account_id/line_items'
],
'media_id' => [
'ads/accounts/:account_id/account_media',
'ads/sandbox/accounts/:account_id/account_media'
],
'name' => [
'ads/accounts/:account_id/app_lists',
'ads/accounts/:account_id/campaigns',
'ads/accounts/:account_id/cards/app_download',
'ads/accounts/:account_id/cards/image_app_download',
'ads/accounts/:account_id/cards/image_conversation',
'ads/accounts/:account_id/cards/lead_gen',
'ads/accounts/:account_id/cards/video_app_download',
'ads/accounts/:account_id/cards/video_conversation',
'ads/accounts/:account_id/cards/website',
'ads/accounts/:account_id/tailored_audiences',
'ads/accounts/:account_id/web_event_tags',
'ads/sandbox/accounts/:account_id/app_lists',
'ads/sandbox/accounts/:account_id/campaigns',
'ads/sandbox/accounts/:account_id/cards/app_download',
'ads/sandbox/accounts/:account_id/cards/image_app_download',
'ads/sandbox/accounts/:account_id/cards/image_conversation',
'ads/sandbox/accounts/:account_id/cards/lead_gen',
'ads/sandbox/accounts/:account_id/cards/video_app_download',
'ads/sandbox/accounts/:account_id/cards/video_conversation',
'ads/sandbox/accounts/:account_id/cards/website',
'ads/sandbox/accounts/:account_id/tailored_audiences',
'ads/sandbox/accounts/:account_id/web_event_tags'
],
'permission_level' => [
'ads/accounts/:account_id/tailored_audiences/:id/permissions',
'ads/sandbox/accounts/:account_id/tailored_audiences/:id/permissions'
],
'tailored_audience_id' => [
'ads/accounts/:account_id/tailored_audience_changes',
'ads/sandbox/accounts/:account_id/tailored_audience_changes'
],
'targeting_value' => [
'ads/accounts/:account_id/targeting_criteria',
'ads/sandbox/accounts/:account_id/targeting_criteria'
],
'tweet_ids' => [
'ads/accounts/:account_id/promoted_tweets',
'ads/sandbox/accounts/:account_id/promoted_tweets'
],
'type' => [
'ads/sandbox/accounts/:account_id/features',
'ads/sandbox/accounts/:account_id/funding_instruments'
],
'url' => [
'account_activity/webhooks'
],
'user_id' => [
'ads/accounts/:account_id/promoted_accounts',
'ads/sandbox/accounts/:account_id/promoted_accounts'
],
'video_media_id' => [
'ads/accounts/:account_id/videos',
'ads/sandbox/accounts/:account_id/videos'
]
],
'PUT' => [
'name' => [
'ads/accounts/:account_id/cards/image_conversation/:card_id',
'ads/accounts/:account_id/cards/video_conversation/:card_id',
'ads/accounts/:account_id/cards/website/:card_id',
'ads/sandbox/accounts/:account_id/cards/image_conversation/:card_id',
'ads/sandbox/accounts/:account_id/cards/video_conversation/:card_id',
'ads/sandbox/accounts/:account_id/cards/website/:card_id'
]
]
];
foreach ($httpmethods_by_param as $httpmethod => $methods_by_param) {
foreach ($methods_by_param as $param => $methods) {
if (in_array($method, $methods) && isset($params[$param])) {
return $httpmethod;
}
}
}
// async media/upload calls may request a status by GET
if ($method === 'media/upload'
&& isset($params['command'])
&& $params['command'] === 'STATUS'
) {
return 'GET';
}
// prefer POST and PUT if parameters are set
if (count($params) > 0) {
if (in_array($method, $apimethods['POST'])) {
return 'POST';
}
if (in_array($method, $apimethods['PUT'])) {
return 'PUT';
}
}
foreach ($apimethods as $httpmethod => $methods) {
if (in_array($method, $methods)) {
return $httpmethod;
}
}
throw new \Exception('Can\'t find HTTP method to use for "' . $method . '".');
} | [
"protected",
"function",
"_detectMethod",
"(",
"$",
"method",
",",
"&",
"$",
"params",
")",
"{",
"if",
"(",
"isset",
"(",
"$",
"params",
"[",
"'httpmethod'",
"]",
")",
")",
"{",
"$",
"httpmethod",
"=",
"$",
"params",
"[",
"'httpmethod'",
"]",
";",
"u... | Detects HTTP method to use for API call
@param string $method The API method to call
@param array byref $params The parameters to send along
@return string The HTTP method that should be used | [
"Detects",
"HTTP",
"method",
"to",
"use",
"for",
"API",
"call"
] | train | https://github.com/jublo/codebird-php/blob/0c20a63e95640f56102e76d3ca14462b3908acc1/src/codebird.php#L1634-L1754 |
jublo/codebird-php | src/codebird.php | Codebird._getMultipartRequestFromParams | protected function _getMultipartRequestFromParams($method_template, $border, $params)
{
$request = '';
foreach ($params as $key => $value) {
// is it an array?
if (is_array($value)) {
throw new CodebirdMediaException('Using URL-encoded parameters is not supported for uploading media.');
}
$request .=
'--' . $border . "\r\n"
. 'Content-Disposition: form-data; name="' . $key . '"';
// check for filenames
$data = $this->_checkForFiles($method_template, $key, $value);
if ($data !== false) {
$value = $data;
}
$request .= "\r\n\r\n" . $value . "\r\n";
}
return $request;
} | php | protected function _getMultipartRequestFromParams($method_template, $border, $params)
{
$request = '';
foreach ($params as $key => $value) {
// is it an array?
if (is_array($value)) {
throw new CodebirdMediaException('Using URL-encoded parameters is not supported for uploading media.');
}
$request .=
'--' . $border . "\r\n"
. 'Content-Disposition: form-data; name="' . $key . '"';
// check for filenames
$data = $this->_checkForFiles($method_template, $key, $value);
if ($data !== false) {
$value = $data;
}
$request .= "\r\n\r\n" . $value . "\r\n";
}
return $request;
} | [
"protected",
"function",
"_getMultipartRequestFromParams",
"(",
"$",
"method_template",
",",
"$",
"border",
",",
"$",
"params",
")",
"{",
"$",
"request",
"=",
"''",
";",
"foreach",
"(",
"$",
"params",
"as",
"$",
"key",
"=>",
"$",
"value",
")",
"{",
"// i... | Merge multipart string from parameters array
@param string $method_template The method template to call
@param string $border The multipart border
@param array $params The parameters to send along
@return string request
@throws \Exception | [
"Merge",
"multipart",
"string",
"from",
"parameters",
"array"
] | train | https://github.com/jublo/codebird-php/blob/0c20a63e95640f56102e76d3ca14462b3908acc1/src/codebird.php#L1787-L1809 |
jublo/codebird-php | src/codebird.php | Codebird._checkForFiles | protected function _checkForFiles($method_template, $key, $value) {
if (!array_key_exists($method_template, self::$_possible_files)
|| !in_array($key, self::$_possible_files[$method_template])
) {
return false;
}
$data = $this->_buildBinaryBody($value);
if ($data === $value) {
return false;
}
return $data;
} | php | protected function _checkForFiles($method_template, $key, $value) {
if (!array_key_exists($method_template, self::$_possible_files)
|| !in_array($key, self::$_possible_files[$method_template])
) {
return false;
}
$data = $this->_buildBinaryBody($value);
if ($data === $value) {
return false;
}
return $data;
} | [
"protected",
"function",
"_checkForFiles",
"(",
"$",
"method_template",
",",
"$",
"key",
",",
"$",
"value",
")",
"{",
"if",
"(",
"!",
"array_key_exists",
"(",
"$",
"method_template",
",",
"self",
"::",
"$",
"_possible_files",
")",
"||",
"!",
"in_array",
"(... | Check for files
@param string $method_template The method template to call
@param string $key The parameter name
@param string $value The possible file name or URL
@return mixed | [
"Check",
"for",
"files"
] | train | https://github.com/jublo/codebird-php/blob/0c20a63e95640f56102e76d3ca14462b3908acc1/src/codebird.php#L1820-L1831 |
jublo/codebird-php | src/codebird.php | Codebird._buildMultipart | protected function _buildMultipart($method, $params)
{
// well, files will only work in multipart methods
if (! $this->_detectMultipart($method)) {
return;
}
// only check specific parameters
// method might have files?
if (! in_array($method, array_keys(self::$_possible_files))) {
return;
}
$multipart_border = '--------------------' . $this->_nonce();
$multipart_request =
$this->_getMultipartRequestFromParams($method, $multipart_border, $params)
. '--' . $multipart_border . '--';
return $multipart_request;
} | php | protected function _buildMultipart($method, $params)
{
// well, files will only work in multipart methods
if (! $this->_detectMultipart($method)) {
return;
}
// only check specific parameters
// method might have files?
if (! in_array($method, array_keys(self::$_possible_files))) {
return;
}
$multipart_border = '--------------------' . $this->_nonce();
$multipart_request =
$this->_getMultipartRequestFromParams($method, $multipart_border, $params)
. '--' . $multipart_border . '--';
return $multipart_request;
} | [
"protected",
"function",
"_buildMultipart",
"(",
"$",
"method",
",",
"$",
"params",
")",
"{",
"// well, files will only work in multipart methods",
"if",
"(",
"!",
"$",
"this",
"->",
"_detectMultipart",
"(",
"$",
"method",
")",
")",
"{",
"return",
";",
"}",
"/... | Detect filenames in upload parameters,
build multipart request from upload params
@param string $method The API method to call
@param array $params The parameters to send along
@return null|string | [
"Detect",
"filenames",
"in",
"upload",
"parameters",
"build",
"multipart",
"request",
"from",
"upload",
"params"
] | train | https://github.com/jublo/codebird-php/blob/0c20a63e95640f56102e76d3ca14462b3908acc1/src/codebird.php#L1843-L1862 |
jublo/codebird-php | src/codebird.php | Codebird._buildBinaryBody | protected function _buildBinaryBody($input)
{
if (// is it a file, a readable one?
@file_exists($input)
&& @is_readable($input)
) {
// try to read the file
$data = @file_get_contents($input);
if ($data !== false && strlen($data) !== 0) {
return $data;
}
} elseif (// is it a remote file?
filter_var($input, FILTER_VALIDATE_URL)
&& preg_match('/^https?:\/\//', $input)
) {
$data = $this->_fetchRemoteFile($input);
if ($data !== false) {
return $data;
}
}
return $input;
} | php | protected function _buildBinaryBody($input)
{
if (// is it a file, a readable one?
@file_exists($input)
&& @is_readable($input)
) {
// try to read the file
$data = @file_get_contents($input);
if ($data !== false && strlen($data) !== 0) {
return $data;
}
} elseif (// is it a remote file?
filter_var($input, FILTER_VALIDATE_URL)
&& preg_match('/^https?:\/\//', $input)
) {
$data = $this->_fetchRemoteFile($input);
if ($data !== false) {
return $data;
}
}
return $input;
} | [
"protected",
"function",
"_buildBinaryBody",
"(",
"$",
"input",
")",
"{",
"if",
"(",
"// is it a file, a readable one?",
"@",
"file_exists",
"(",
"$",
"input",
")",
"&&",
"@",
"is_readable",
"(",
"$",
"input",
")",
")",
"{",
"// try to read the file",
"$",
"da... | Detect filenames in upload parameters
@param mixed $input The data or file name to parse
@return null|string | [
"Detect",
"filenames",
"in",
"upload",
"parameters"
] | train | https://github.com/jublo/codebird-php/blob/0c20a63e95640f56102e76d3ca14462b3908acc1/src/codebird.php#L1871-L1892 |
jublo/codebird-php | src/codebird.php | Codebird._fetchRemoteFile | protected function _fetchRemoteFile($url)
{
// try to fetch the file
if ($this->_use_curl) {
$connection = $this->_getCurlInitialization($url);
$this->_curl_setopt($connection, CURLOPT_RETURNTRANSFER, 1);
$this->_curl_setopt($connection, CURLOPT_HEADER, 0);
// no SSL validation for downloading media
$this->_curl_setopt($connection, CURLOPT_SSL_VERIFYPEER, 1);
$this->_curl_setopt($connection, CURLOPT_SSL_VERIFYHOST, 2);
$this->_curl_setopt($connection, CURLOPT_TIMEOUT_MS, $this->_timeouts['remote']);
$this->_curl_setopt($connection, CURLOPT_CONNECTTIMEOUT_MS, $this->_timeouts['remote'] / 2);
// find files that have been redirected
$this->_curl_setopt($connection, CURLOPT_FOLLOWLOCATION, true);
// process compressed images
$this->_curl_setopt($connection, CURLOPT_ENCODING, 'gzip,deflate,sdch');
$result = $this->_curl_exec($connection);
if ($result !== false
&& $this->_curl_getinfo($connection, CURLINFO_HTTP_CODE) === 200
) {
return $result;
}
throw new CodebirdMediaException('Downloading a remote media file failed.');
return false;
}
// no cURL
$contextOptions = [
'http' => [
'method' => 'GET',
'protocol_version' => '1.1',
'timeout' => $this->_timeouts['remote']
],
'ssl' => [
'verify_peer' => false
]
];
list($result, $headers) = $this->_getNoCurlInitialization($url, $contextOptions);
if ($result !== false
&& preg_match('/^HTTP\/\d\.\d 200 OK$/', $headers[0])
) {
return $result;
}
throw new CodebirdMediaException('Downloading a remote media file failed.');
return false;
} | php | protected function _fetchRemoteFile($url)
{
// try to fetch the file
if ($this->_use_curl) {
$connection = $this->_getCurlInitialization($url);
$this->_curl_setopt($connection, CURLOPT_RETURNTRANSFER, 1);
$this->_curl_setopt($connection, CURLOPT_HEADER, 0);
// no SSL validation for downloading media
$this->_curl_setopt($connection, CURLOPT_SSL_VERIFYPEER, 1);
$this->_curl_setopt($connection, CURLOPT_SSL_VERIFYHOST, 2);
$this->_curl_setopt($connection, CURLOPT_TIMEOUT_MS, $this->_timeouts['remote']);
$this->_curl_setopt($connection, CURLOPT_CONNECTTIMEOUT_MS, $this->_timeouts['remote'] / 2);
// find files that have been redirected
$this->_curl_setopt($connection, CURLOPT_FOLLOWLOCATION, true);
// process compressed images
$this->_curl_setopt($connection, CURLOPT_ENCODING, 'gzip,deflate,sdch');
$result = $this->_curl_exec($connection);
if ($result !== false
&& $this->_curl_getinfo($connection, CURLINFO_HTTP_CODE) === 200
) {
return $result;
}
throw new CodebirdMediaException('Downloading a remote media file failed.');
return false;
}
// no cURL
$contextOptions = [
'http' => [
'method' => 'GET',
'protocol_version' => '1.1',
'timeout' => $this->_timeouts['remote']
],
'ssl' => [
'verify_peer' => false
]
];
list($result, $headers) = $this->_getNoCurlInitialization($url, $contextOptions);
if ($result !== false
&& preg_match('/^HTTP\/\d\.\d 200 OK$/', $headers[0])
) {
return $result;
}
throw new CodebirdMediaException('Downloading a remote media file failed.');
return false;
} | [
"protected",
"function",
"_fetchRemoteFile",
"(",
"$",
"url",
")",
"{",
"// try to fetch the file",
"if",
"(",
"$",
"this",
"->",
"_use_curl",
")",
"{",
"$",
"connection",
"=",
"$",
"this",
"->",
"_getCurlInitialization",
"(",
"$",
"url",
")",
";",
"$",
"t... | Fetches a remote file
@param string $url The URL to download from
@return mixed The file contents or FALSE
@throws \Exception | [
"Fetches",
"a",
"remote",
"file"
] | train | https://github.com/jublo/codebird-php/blob/0c20a63e95640f56102e76d3ca14462b3908acc1/src/codebird.php#L1902-L1946 |
jublo/codebird-php | src/codebird.php | Codebird._detectStreaming | protected function _detectStreaming($method) {
$streamings = [
'public' => [
'statuses/sample',
'statuses/filter'
]
];
foreach ($streamings as $key => $values) {
if (in_array($method, $values)) {
return $key;
}
}
return false;
} | php | protected function _detectStreaming($method) {
$streamings = [
'public' => [
'statuses/sample',
'statuses/filter'
]
];
foreach ($streamings as $key => $values) {
if (in_array($method, $values)) {
return $key;
}
}
return false;
} | [
"protected",
"function",
"_detectStreaming",
"(",
"$",
"method",
")",
"{",
"$",
"streamings",
"=",
"[",
"'public'",
"=>",
"[",
"'statuses/sample'",
",",
"'statuses/filter'",
"]",
"]",
";",
"foreach",
"(",
"$",
"streamings",
"as",
"$",
"key",
"=>",
"$",
"va... | Detects if API call should use streaming endpoint, and if yes, which one
@param string $method The API method to call
@return string|false Variant of streaming API to be used | [
"Detects",
"if",
"API",
"call",
"should",
"use",
"streaming",
"endpoint",
"and",
"if",
"yes",
"which",
"one"
] | train | https://github.com/jublo/codebird-php/blob/0c20a63e95640f56102e76d3ca14462b3908acc1/src/codebird.php#L2016-L2030 |
jublo/codebird-php | src/codebird.php | Codebird._getEndpoint | protected function _getEndpoint($method, $method_template)
{
$url = self::$_endpoints['rest'] . $method . '.json';
if (substr($method_template, 0, 22) === 'oauth/invalidate_token') {
$url = self::$_endpoints['rest'] . $method . '.json';
} elseif (substr($method_template, 0, 5) === 'oauth') {
$url = self::$_endpoints['oauth'] . $method;
} elseif ($this->_detectMedia($method_template)) {
$url = self::$_endpoints['media'] . $method . '.json';
} elseif ($method_template === 'statuses/oembed') {
$url = self::$_endpoints['publish'] . 'oembed';
} elseif ($variant = $this->_detectStreaming($method_template)) {
$url = self::$_endpoints['streaming'][$variant] . $method . '.json';
} elseif ($this->_detectBinaryBody($method_template)) {
$url = self::$_endpoints['ton'] . $method;
} elseif (substr($method_template, 0, 12) === 'ads/sandbox/') {
$url = self::$_endpoints['ads']['sandbox'] . substr($method, 12);
} elseif (substr($method_template, 0, 4) === 'ads/') {
$url = self::$_endpoints['ads']['production'] . substr($method, 4);
}
return $url;
} | php | protected function _getEndpoint($method, $method_template)
{
$url = self::$_endpoints['rest'] . $method . '.json';
if (substr($method_template, 0, 22) === 'oauth/invalidate_token') {
$url = self::$_endpoints['rest'] . $method . '.json';
} elseif (substr($method_template, 0, 5) === 'oauth') {
$url = self::$_endpoints['oauth'] . $method;
} elseif ($this->_detectMedia($method_template)) {
$url = self::$_endpoints['media'] . $method . '.json';
} elseif ($method_template === 'statuses/oembed') {
$url = self::$_endpoints['publish'] . 'oembed';
} elseif ($variant = $this->_detectStreaming($method_template)) {
$url = self::$_endpoints['streaming'][$variant] . $method . '.json';
} elseif ($this->_detectBinaryBody($method_template)) {
$url = self::$_endpoints['ton'] . $method;
} elseif (substr($method_template, 0, 12) === 'ads/sandbox/') {
$url = self::$_endpoints['ads']['sandbox'] . substr($method, 12);
} elseif (substr($method_template, 0, 4) === 'ads/') {
$url = self::$_endpoints['ads']['production'] . substr($method, 4);
}
return $url;
} | [
"protected",
"function",
"_getEndpoint",
"(",
"$",
"method",
",",
"$",
"method_template",
")",
"{",
"$",
"url",
"=",
"self",
"::",
"$",
"_endpoints",
"[",
"'rest'",
"]",
".",
"$",
"method",
".",
"'.json'",
";",
"if",
"(",
"substr",
"(",
"$",
"method_te... | Builds the complete API endpoint url
@param string $method The API method to call
@param string $method_template The API method to call
@return string The URL to send the request to | [
"Builds",
"the",
"complete",
"API",
"endpoint",
"url"
] | train | https://github.com/jublo/codebird-php/blob/0c20a63e95640f56102e76d3ca14462b3908acc1/src/codebird.php#L2040-L2061 |
jublo/codebird-php | src/codebird.php | Codebird._callApi | protected function _callApi($httpmethod, $method, $method_template, $params = [], $multipart = false, $app_only_auth = false)
{
if (! $app_only_auth
&& $this->_oauth_token === null
&& substr($method, 0, 5) !== 'oauth'
) {
throw new CodebirdCredentialsException('To call this API, the OAuth access token must be set.');
}
// use separate API access for streaming API
if ($this->_detectStreaming($method) !== false) {
return $this->_callApiStreaming($httpmethod, $method, $method_template, $params, $app_only_auth);
}
if ($this->_use_curl) {
return $this->_callApiCurl($httpmethod, $method, $method_template, $params, $multipart, $app_only_auth);
}
return $this->_callApiNoCurl($httpmethod, $method, $method_template, $params, $multipart, $app_only_auth);
} | php | protected function _callApi($httpmethod, $method, $method_template, $params = [], $multipart = false, $app_only_auth = false)
{
if (! $app_only_auth
&& $this->_oauth_token === null
&& substr($method, 0, 5) !== 'oauth'
) {
throw new CodebirdCredentialsException('To call this API, the OAuth access token must be set.');
}
// use separate API access for streaming API
if ($this->_detectStreaming($method) !== false) {
return $this->_callApiStreaming($httpmethod, $method, $method_template, $params, $app_only_auth);
}
if ($this->_use_curl) {
return $this->_callApiCurl($httpmethod, $method, $method_template, $params, $multipart, $app_only_auth);
}
return $this->_callApiNoCurl($httpmethod, $method, $method_template, $params, $multipart, $app_only_auth);
} | [
"protected",
"function",
"_callApi",
"(",
"$",
"httpmethod",
",",
"$",
"method",
",",
"$",
"method_template",
",",
"$",
"params",
"=",
"[",
"]",
",",
"$",
"multipart",
"=",
"false",
",",
"$",
"app_only_auth",
"=",
"false",
")",
"{",
"if",
"(",
"!",
"... | Calls the API
@param string $httpmethod The HTTP method to use for making the request
@param string $method The API method to call
@param string $method_template The API method template to call
@param array optional $params The parameters to send along
@param bool optional $multipart Whether to use multipart/form-data
@param bool optional $app_only_auth Whether to use app-only bearer authentication
@return string The API reply, encoded in the set return_format
@throws \Exception | [
"Calls",
"the",
"API"
] | train | https://github.com/jublo/codebird-php/blob/0c20a63e95640f56102e76d3ca14462b3908acc1/src/codebird.php#L2077-L2094 |
jublo/codebird-php | src/codebird.php | Codebird._callApiCurl | protected function _callApiCurl(
$httpmethod, $method, $method_template, $params = [], $multipart = false, $app_only_auth = false
)
{
list ($authorization, $url, $params, $request_headers)
= $this->_callApiPreparations(
$httpmethod, $method, $method_template, $params, $multipart, $app_only_auth
);
$connection = $this->_getCurlInitialization($url);
$request_headers[] = 'Authorization: ' . $authorization;
$request_headers[] = 'Expect:';
if ($httpmethod !== 'GET') {
$this->_curl_setopt($connection, CURLOPT_POST, 1);
$this->_curl_setopt($connection, CURLOPT_POSTFIELDS, $params);
if (in_array($httpmethod, ['POST', 'PUT', 'DELETE'])) {
$this->_curl_setopt($connection, CURLOPT_CUSTOMREQUEST, $httpmethod);
}
}
$this->_curl_setopt($connection, CURLOPT_HTTPHEADER, $request_headers);
$this->_curl_setopt($connection, CURLOPT_TIMEOUT_MS, $this->_timeouts['request']);
$this->_curl_setopt($connection, CURLOPT_CONNECTTIMEOUT_MS, $this->_timeouts['connect']);
$result = $this->_curl_exec($connection);
// catch request errors
if ($result === false) {
throw new \Exception('Request error for API call: ' . $this->_curl_error($connection));
}
// certificate validation results
$validation_result = $this->_curl_errno($connection);
$this->_validateSslCertificate($validation_result);
$httpstatus = $this->_curl_getinfo($connection, CURLINFO_HTTP_CODE);
list($headers, $reply) = $this->_parseApiHeaders($result);
// TON API & redirects
$reply = $this->_parseApiReplyPrefillHeaders($headers, $reply);
$reply = $this->_parseApiReply($reply);
$rate = $this->_getRateLimitInfo($headers);
$reply = $this->_appendHttpStatusAndRate($reply, $httpstatus, $rate);
return $reply;
} | php | protected function _callApiCurl(
$httpmethod, $method, $method_template, $params = [], $multipart = false, $app_only_auth = false
)
{
list ($authorization, $url, $params, $request_headers)
= $this->_callApiPreparations(
$httpmethod, $method, $method_template, $params, $multipart, $app_only_auth
);
$connection = $this->_getCurlInitialization($url);
$request_headers[] = 'Authorization: ' . $authorization;
$request_headers[] = 'Expect:';
if ($httpmethod !== 'GET') {
$this->_curl_setopt($connection, CURLOPT_POST, 1);
$this->_curl_setopt($connection, CURLOPT_POSTFIELDS, $params);
if (in_array($httpmethod, ['POST', 'PUT', 'DELETE'])) {
$this->_curl_setopt($connection, CURLOPT_CUSTOMREQUEST, $httpmethod);
}
}
$this->_curl_setopt($connection, CURLOPT_HTTPHEADER, $request_headers);
$this->_curl_setopt($connection, CURLOPT_TIMEOUT_MS, $this->_timeouts['request']);
$this->_curl_setopt($connection, CURLOPT_CONNECTTIMEOUT_MS, $this->_timeouts['connect']);
$result = $this->_curl_exec($connection);
// catch request errors
if ($result === false) {
throw new \Exception('Request error for API call: ' . $this->_curl_error($connection));
}
// certificate validation results
$validation_result = $this->_curl_errno($connection);
$this->_validateSslCertificate($validation_result);
$httpstatus = $this->_curl_getinfo($connection, CURLINFO_HTTP_CODE);
list($headers, $reply) = $this->_parseApiHeaders($result);
// TON API & redirects
$reply = $this->_parseApiReplyPrefillHeaders($headers, $reply);
$reply = $this->_parseApiReply($reply);
$rate = $this->_getRateLimitInfo($headers);
$reply = $this->_appendHttpStatusAndRate($reply, $httpstatus, $rate);
return $reply;
} | [
"protected",
"function",
"_callApiCurl",
"(",
"$",
"httpmethod",
",",
"$",
"method",
",",
"$",
"method_template",
",",
"$",
"params",
"=",
"[",
"]",
",",
"$",
"multipart",
"=",
"false",
",",
"$",
"app_only_auth",
"=",
"false",
")",
"{",
"list",
"(",
"$... | Calls the API using cURL
@param string $httpmethod The HTTP method to use for making the request
@param string $method The API method to call
@param string $method_template The API method template to call
@param array optional $params The parameters to send along
@param bool optional $multipart Whether to use multipart/form-data
@param bool optional $app_only_auth Whether to use app-only bearer authentication
@return string The API reply, encoded in the set return_format
@throws \Exception | [
"Calls",
"the",
"API",
"using",
"cURL"
] | train | https://github.com/jublo/codebird-php/blob/0c20a63e95640f56102e76d3ca14462b3908acc1/src/codebird.php#L2110-L2155 |
jublo/codebird-php | src/codebird.php | Codebird._callApiNoCurl | protected function _callApiNoCurl(
$httpmethod, $method, $method_template, $params = [], $multipart = false, $app_only_auth = false
)
{
list ($authorization, $url, $params, $request_headers)
= $this->_callApiPreparations(
$httpmethod, $method, $method_template, $params, $multipart, $app_only_auth
);
$hostname = parse_url($url, PHP_URL_HOST);
if ($hostname === false) {
throw new CodebirdEndpointException('Incorrect API endpoint host.');
}
$request_headers[] = 'Authorization: ' . $authorization;
$request_headers[] = 'Accept: */*';
$request_headers[] = 'Connection: Close';
if ($httpmethod !== 'GET' && ! $multipart) {
$request_headers[] = 'Content-Type: application/x-www-form-urlencoded';
}
$contextOptions = [
'http' => [
'method' => $httpmethod,
'protocol_version' => '1.1',
'header' => implode("\r\n", $request_headers),
'timeout' => $this->_timeouts['request'] / 1000,
'content' => in_array($httpmethod, ['POST', 'PUT']) ? $params : null,
'ignore_errors' => true
]
];
list($reply, $headers) = $this->_getNoCurlInitialization($url, $contextOptions, $hostname);
$result = '';
foreach ($headers as $header) {
$result .= $header . "\r\n";
}
$result .= "\r\n" . $reply;
// find HTTP status
$httpstatus = $this->_getHttpStatusFromHeaders($headers);
list($headers, $reply) = $this->_parseApiHeaders($result);
// TON API & redirects
$reply = $this->_parseApiReplyPrefillHeaders($headers, $reply);
$reply = $this->_parseApiReply($reply);
$rate = $this->_getRateLimitInfo($headers);
$reply = $this->_appendHttpStatusAndRate($reply, $httpstatus, $rate);
return $reply;
} | php | protected function _callApiNoCurl(
$httpmethod, $method, $method_template, $params = [], $multipart = false, $app_only_auth = false
)
{
list ($authorization, $url, $params, $request_headers)
= $this->_callApiPreparations(
$httpmethod, $method, $method_template, $params, $multipart, $app_only_auth
);
$hostname = parse_url($url, PHP_URL_HOST);
if ($hostname === false) {
throw new CodebirdEndpointException('Incorrect API endpoint host.');
}
$request_headers[] = 'Authorization: ' . $authorization;
$request_headers[] = 'Accept: */*';
$request_headers[] = 'Connection: Close';
if ($httpmethod !== 'GET' && ! $multipart) {
$request_headers[] = 'Content-Type: application/x-www-form-urlencoded';
}
$contextOptions = [
'http' => [
'method' => $httpmethod,
'protocol_version' => '1.1',
'header' => implode("\r\n", $request_headers),
'timeout' => $this->_timeouts['request'] / 1000,
'content' => in_array($httpmethod, ['POST', 'PUT']) ? $params : null,
'ignore_errors' => true
]
];
list($reply, $headers) = $this->_getNoCurlInitialization($url, $contextOptions, $hostname);
$result = '';
foreach ($headers as $header) {
$result .= $header . "\r\n";
}
$result .= "\r\n" . $reply;
// find HTTP status
$httpstatus = $this->_getHttpStatusFromHeaders($headers);
list($headers, $reply) = $this->_parseApiHeaders($result);
// TON API & redirects
$reply = $this->_parseApiReplyPrefillHeaders($headers, $reply);
$reply = $this->_parseApiReply($reply);
$rate = $this->_getRateLimitInfo($headers);
$reply = $this->_appendHttpStatusAndRate($reply, $httpstatus, $rate);
return $reply;
} | [
"protected",
"function",
"_callApiNoCurl",
"(",
"$",
"httpmethod",
",",
"$",
"method",
",",
"$",
"method_template",
",",
"$",
"params",
"=",
"[",
"]",
",",
"$",
"multipart",
"=",
"false",
",",
"$",
"app_only_auth",
"=",
"false",
")",
"{",
"list",
"(",
... | Calls the API without cURL
@param string $httpmethod The HTTP method to use for making the request
@param string $method The API method to call
@param string $method_template The API method template to call
@param array optional $params The parameters to send along
@param bool optional $multipart Whether to use multipart/form-data
@param bool optional $app_only_auth Whether to use app-only bearer authentication
@return string The API reply, encoded in the set return_format
@throws \Exception | [
"Calls",
"the",
"API",
"without",
"cURL"
] | train | https://github.com/jublo/codebird-php/blob/0c20a63e95640f56102e76d3ca14462b3908acc1/src/codebird.php#L2171-L2220 |
jublo/codebird-php | src/codebird.php | Codebird._callApiPreparationsGet | protected function _callApiPreparationsGet(
$httpmethod, $url, $params, $app_only_auth
) {
return [
$app_only_auth ? null : $this->_sign($httpmethod, $url, $params),
json_encode($params) === '[]' ? $url : $url . '?' . http_build_query($params)
];
} | php | protected function _callApiPreparationsGet(
$httpmethod, $url, $params, $app_only_auth
) {
return [
$app_only_auth ? null : $this->_sign($httpmethod, $url, $params),
json_encode($params) === '[]' ? $url : $url . '?' . http_build_query($params)
];
} | [
"protected",
"function",
"_callApiPreparationsGet",
"(",
"$",
"httpmethod",
",",
"$",
"url",
",",
"$",
"params",
",",
"$",
"app_only_auth",
")",
"{",
"return",
"[",
"$",
"app_only_auth",
"?",
"null",
":",
"$",
"this",
"->",
"_sign",
"(",
"$",
"httpmethod",... | Do preparations to make the API GET call
@param string $httpmethod The HTTP method to use for making the request
@param string $url The URL to call
@param array $params The parameters to send along
@param bool $app_only_auth Whether to use app-only bearer authentication
@return string[] (string authorization, string url) | [
"Do",
"preparations",
"to",
"make",
"the",
"API",
"GET",
"call"
] | train | https://github.com/jublo/codebird-php/blob/0c20a63e95640f56102e76d3ca14462b3908acc1/src/codebird.php#L2232-L2239 |
jublo/codebird-php | src/codebird.php | Codebird._callApiPreparationsPost | protected function _callApiPreparationsPost(
$httpmethod, $url, $method, $method_template, $params, $multipart, $app_only_auth
) {
$authorization = null;
$request_headers = [];
if ($multipart) {
if (! $app_only_auth) {
$authorization = $this->_sign($httpmethod, $url, []);
}
$params = $this->_buildMultipart($method, $params);
$first_newline = strpos($params, "\r\n");
$multipart_boundary = substr($params, 2, $first_newline - 2);
$request_headers[] = 'Content-Type: multipart/form-data; boundary='
. $multipart_boundary;
} elseif ($this->_detectJsonBody($method_template)) {
$authorization = $this->_sign($httpmethod, $url, []);
$params = json_encode($params);
$request_headers[] = 'Content-Type: application/json';
} elseif ($this->_detectBinaryBody($method_template)) {
// transform parametric headers to real headers
foreach ([
'Content-Length',
'Content-Range',
'Content-Type',
'X-TON-Content-Type',
'X-TON-Content-Length',
'X-TON-Expires'
] as $key) {
if (isset($params[$key])) {
$request_headers[] = $key . ': ' . $params[$key];
unset($params[$key]);
}
}
$sign_params = [];
parse_str(parse_url($method, PHP_URL_QUERY), $sign_params);
if ($sign_params === null) {
$sign_params = [];
}
$authorization = $this->_sign($httpmethod, $url, $sign_params);
if (isset($params['media'])) {
$params = $this->_buildBinaryBody($params['media']);
} else {
// resumable upload
$params = [];
}
} else {
// check for possible files in non-multipart methods
foreach ($params as $key => $value) {
$data = $this->_checkForFiles($method_template, $key, $value);
if ($data !== false) {
$params[$key] = base64_encode($data);
}
}
if (! $app_only_auth) {
$authorization = $this->_sign($httpmethod, $url, $params);
}
$params = http_build_query($params);
}
return [$authorization, $params, $request_headers];
} | php | protected function _callApiPreparationsPost(
$httpmethod, $url, $method, $method_template, $params, $multipart, $app_only_auth
) {
$authorization = null;
$request_headers = [];
if ($multipart) {
if (! $app_only_auth) {
$authorization = $this->_sign($httpmethod, $url, []);
}
$params = $this->_buildMultipart($method, $params);
$first_newline = strpos($params, "\r\n");
$multipart_boundary = substr($params, 2, $first_newline - 2);
$request_headers[] = 'Content-Type: multipart/form-data; boundary='
. $multipart_boundary;
} elseif ($this->_detectJsonBody($method_template)) {
$authorization = $this->_sign($httpmethod, $url, []);
$params = json_encode($params);
$request_headers[] = 'Content-Type: application/json';
} elseif ($this->_detectBinaryBody($method_template)) {
// transform parametric headers to real headers
foreach ([
'Content-Length',
'Content-Range',
'Content-Type',
'X-TON-Content-Type',
'X-TON-Content-Length',
'X-TON-Expires'
] as $key) {
if (isset($params[$key])) {
$request_headers[] = $key . ': ' . $params[$key];
unset($params[$key]);
}
}
$sign_params = [];
parse_str(parse_url($method, PHP_URL_QUERY), $sign_params);
if ($sign_params === null) {
$sign_params = [];
}
$authorization = $this->_sign($httpmethod, $url, $sign_params);
if (isset($params['media'])) {
$params = $this->_buildBinaryBody($params['media']);
} else {
// resumable upload
$params = [];
}
} else {
// check for possible files in non-multipart methods
foreach ($params as $key => $value) {
$data = $this->_checkForFiles($method_template, $key, $value);
if ($data !== false) {
$params[$key] = base64_encode($data);
}
}
if (! $app_only_auth) {
$authorization = $this->_sign($httpmethod, $url, $params);
}
$params = http_build_query($params);
}
return [$authorization, $params, $request_headers];
} | [
"protected",
"function",
"_callApiPreparationsPost",
"(",
"$",
"httpmethod",
",",
"$",
"url",
",",
"$",
"method",
",",
"$",
"method_template",
",",
"$",
"params",
",",
"$",
"multipart",
",",
"$",
"app_only_auth",
")",
"{",
"$",
"authorization",
"=",
"null",
... | Do preparations to make the API POST call
@param string $httpmethod The HTTP method to use for making the request
@param string $url The URL to call
@param string $method The API method to call
@param string $method_template The API method template to call
@param array $params The parameters to send along
@param bool $multipart Whether to use multipart/form-data
@param bool $app_only_auth Whether to use app-only bearer authentication
@return array (string authorization, array params, array request_headers) | [
"Do",
"preparations",
"to",
"make",
"the",
"API",
"POST",
"call"
] | train | https://github.com/jublo/codebird-php/blob/0c20a63e95640f56102e76d3ca14462b3908acc1/src/codebird.php#L2254-L2313 |
jublo/codebird-php | src/codebird.php | Codebird._appendHttpStatusAndRate | protected function _appendHttpStatusAndRate($reply, $httpstatus, $rate)
{
switch ($this->_return_format) {
case CODEBIRD_RETURNFORMAT_ARRAY:
$reply['httpstatus'] = $httpstatus;
$reply['rate'] = $rate;
break;
case CODEBIRD_RETURNFORMAT_OBJECT:
$reply->httpstatus = $httpstatus;
$reply->rate = $rate;
break;
case CODEBIRD_RETURNFORMAT_JSON:
$reply = $this->_json_decode($reply);
$reply->httpstatus = $httpstatus;
$reply->rate = $rate;
$reply = json_encode($reply);
break;
}
return $reply;
} | php | protected function _appendHttpStatusAndRate($reply, $httpstatus, $rate)
{
switch ($this->_return_format) {
case CODEBIRD_RETURNFORMAT_ARRAY:
$reply['httpstatus'] = $httpstatus;
$reply['rate'] = $rate;
break;
case CODEBIRD_RETURNFORMAT_OBJECT:
$reply->httpstatus = $httpstatus;
$reply->rate = $rate;
break;
case CODEBIRD_RETURNFORMAT_JSON:
$reply = $this->_json_decode($reply);
$reply->httpstatus = $httpstatus;
$reply->rate = $rate;
$reply = json_encode($reply);
break;
}
return $reply;
} | [
"protected",
"function",
"_appendHttpStatusAndRate",
"(",
"$",
"reply",
",",
"$",
"httpstatus",
",",
"$",
"rate",
")",
"{",
"switch",
"(",
"$",
"this",
"->",
"_return_format",
")",
"{",
"case",
"CODEBIRD_RETURNFORMAT_ARRAY",
":",
"$",
"reply",
"[",
"'httpstatu... | Appends HTTP status and rate limiting info to the reply
@param array|object|string $reply The reply to append to
@param string $httpstatus The HTTP status code to append
@param mixed $rate The rate limiting info to append | [
"Appends",
"HTTP",
"status",
"and",
"rate",
"limiting",
"info",
"to",
"the",
"reply"
] | train | https://github.com/jublo/codebird-php/blob/0c20a63e95640f56102e76d3ca14462b3908acc1/src/codebird.php#L2322-L2341 |
jublo/codebird-php | src/codebird.php | Codebird._getBearerAuthorization | protected function _getBearerAuthorization()
{
if (self::$_consumer_key === null
&& self::$_bearer_token === null
) {
throw new CodebirdCredentialsException('To make an app-only auth API request, consumer key or bearer token must be set.');
}
// automatically fetch bearer token, if necessary
if (self::$_bearer_token === null) {
$this->oauth2_token();
}
return 'Bearer ' . self::$_bearer_token;
} | php | protected function _getBearerAuthorization()
{
if (self::$_consumer_key === null
&& self::$_bearer_token === null
) {
throw new CodebirdCredentialsException('To make an app-only auth API request, consumer key or bearer token must be set.');
}
// automatically fetch bearer token, if necessary
if (self::$_bearer_token === null) {
$this->oauth2_token();
}
return 'Bearer ' . self::$_bearer_token;
} | [
"protected",
"function",
"_getBearerAuthorization",
"(",
")",
"{",
"if",
"(",
"self",
"::",
"$",
"_consumer_key",
"===",
"null",
"&&",
"self",
"::",
"$",
"_bearer_token",
"===",
"null",
")",
"{",
"throw",
"new",
"CodebirdCredentialsException",
"(",
"'To make an ... | Get Bearer authorization string
@return string authorization
@throws \Exception | [
"Get",
"Bearer",
"authorization",
"string"
] | train | https://github.com/jublo/codebird-php/blob/0c20a63e95640f56102e76d3ca14462b3908acc1/src/codebird.php#L2349-L2361 |
jublo/codebird-php | src/codebird.php | Codebird._callApiPreparations | protected function _callApiPreparations(
$httpmethod, $method, $method_template, $params, $multipart, $app_only_auth
)
{
$url = $this->_getEndpoint($method, $method_template);
$request_headers = [];
if ($httpmethod === 'GET') {
// GET
list ($authorization, $url) =
$this->_callApiPreparationsGet($httpmethod, $url, $params, $app_only_auth);
} else {
// POST
list ($authorization, $params, $request_headers) =
$this->_callApiPreparationsPost($httpmethod, $url, $method, $method_template, $params, $multipart, $app_only_auth);
}
if ($app_only_auth) {
$authorization = $this->_getBearerAuthorization();
}
return [
$authorization, $url, $params, $request_headers
];
} | php | protected function _callApiPreparations(
$httpmethod, $method, $method_template, $params, $multipart, $app_only_auth
)
{
$url = $this->_getEndpoint($method, $method_template);
$request_headers = [];
if ($httpmethod === 'GET') {
// GET
list ($authorization, $url) =
$this->_callApiPreparationsGet($httpmethod, $url, $params, $app_only_auth);
} else {
// POST
list ($authorization, $params, $request_headers) =
$this->_callApiPreparationsPost($httpmethod, $url, $method, $method_template, $params, $multipart, $app_only_auth);
}
if ($app_only_auth) {
$authorization = $this->_getBearerAuthorization();
}
return [
$authorization, $url, $params, $request_headers
];
} | [
"protected",
"function",
"_callApiPreparations",
"(",
"$",
"httpmethod",
",",
"$",
"method",
",",
"$",
"method_template",
",",
"$",
"params",
",",
"$",
"multipart",
",",
"$",
"app_only_auth",
")",
"{",
"$",
"url",
"=",
"$",
"this",
"->",
"_getEndpoint",
"(... | Do preparations to make the API call
@param string $httpmethod The HTTP method to use for making the request
@param string $method The API method to call
@param string $method_template The API method template to call
@param array $params The parameters to send along
@param bool $multipart Whether to use multipart/form-data
@param bool $app_only_auth Whether to use app-only bearer authentication
@return array (string authorization, string url, array params, array request_headers) | [
"Do",
"preparations",
"to",
"make",
"the",
"API",
"call"
] | train | https://github.com/jublo/codebird-php/blob/0c20a63e95640f56102e76d3ca14462b3908acc1/src/codebird.php#L2375-L2397 |
jublo/codebird-php | src/codebird.php | Codebird._callApiStreaming | protected function _callApiStreaming(
$httpmethod, $method, $method_template, $params = [], $app_only_auth = false
)
{
if ($this->_streaming_callback === null) {
throw new \Exception('Set streaming callback before consuming a stream.');
}
$params['delimited'] = 'length';
list ($authorization, $url, $params, $request_headers)
= $this->_callApiPreparations(
$httpmethod, $method, $method_template, $params, false, $app_only_auth
);
$hostname = parse_url($url, PHP_URL_HOST);
$path = parse_url($url, PHP_URL_PATH);
$query = parse_url($url, PHP_URL_QUERY);
if ($hostname === false) {
throw new CodebirdEndpointException('Incorrect API endpoint host.');
}
$request_headers[] = 'Authorization: ' . $authorization;
$request_headers[] = 'Accept: */*';
if ($httpmethod !== 'GET') {
$request_headers[] = 'Content-Type: application/x-www-form-urlencoded';
$request_headers[] = 'Content-Length: ' . strlen($params);
}
$errno = 0;
$errstr = '';
$connection = stream_socket_client(
'ssl://' . $hostname . ':443',
$errno, $errstr,
$this->_timeouts['connect'],
STREAM_CLIENT_CONNECT
);
// send request
$request = $httpmethod . ' '
. $path . ($query ? '?' . $query : '') . " HTTP/1.1\r\n"
. 'Host: ' . $hostname . "\r\n"
. implode("\r\n", $request_headers)
. "\r\n\r\n";
if ($httpmethod !== 'GET') {
$request .= $params;
}
fputs($connection, $request);
stream_set_blocking($connection, 0);
stream_set_timeout($connection, 0);
// collect headers
do {
$result = stream_get_line($connection, 1048576, "\r\n\r\n");
} while(!$result);
$headers = explode("\r\n", $result);
// find HTTP status
$httpstatus = $this->_getHttpStatusFromHeaders($headers);
list($headers,) = $this->_parseApiHeaders($result);
$rate = $this->_getRateLimitInfo($headers);
if ($httpstatus !== '200') {
$reply = [
'httpstatus' => $httpstatus,
'rate' => $rate
];
switch ($this->_return_format) {
case CODEBIRD_RETURNFORMAT_ARRAY:
return $reply;
case CODEBIRD_RETURNFORMAT_OBJECT:
return (object) $reply;
case CODEBIRD_RETURNFORMAT_JSON:
return json_encode($reply);
}
}
$signal_function = function_exists('pcntl_signal_dispatch');
$data = '';
$last_message = $this->_time();
$message_length = 0;
while (!feof($connection)) {
// call signal handlers, if any
if ($signal_function) {
pcntl_signal_dispatch();
}
$connection_array = [$connection];
$write = $except = null;
if (false === ($num_changed_streams = stream_select($connection_array, $write, $except, 0, 200000))) {
break;
} elseif ($num_changed_streams === 0) {
if ($this->_time() - $last_message >= 1) {
// deliver empty message, allow callback to cancel stream
$cancel_stream = $this->_deliverStreamingMessage(null);
if ($cancel_stream) {
break;
}
$last_message = $this->_time();
}
continue;
}
$chunk_length = fgets($connection, 10);
if ($chunk_length === '' || !$chunk_length = hexdec($chunk_length)) {
continue;
}
$chunk = '';
do {
$chunk .= fread($connection, $chunk_length);
$chunk_length -= strlen($chunk);
} while($chunk_length > 0);
if(0 === $message_length) {
$message_length = (int) strstr($chunk, "\r\n", true);
if ($message_length) {
$chunk = substr($chunk, strpos($chunk, "\r\n") + 2);
} else {
continue;
}
$data = $chunk;
} else {
$data .= $chunk;
}
if (strlen($data) < $message_length) {
continue;
}
$reply = $this->_parseApiReply($data);
switch ($this->_return_format) {
case CODEBIRD_RETURNFORMAT_ARRAY:
$reply['httpstatus'] = $httpstatus;
$reply['rate'] = $rate;
break;
case CODEBIRD_RETURNFORMAT_OBJECT:
$reply->httpstatus = $httpstatus;
$reply->rate = $rate;
break;
}
$cancel_stream = $this->_deliverStreamingMessage($reply);
if ($cancel_stream) {
fclose($connection);
break;
}
$data = '';
$message_length = 0;
$last_message = $this->_time();
}
return;
} | php | protected function _callApiStreaming(
$httpmethod, $method, $method_template, $params = [], $app_only_auth = false
)
{
if ($this->_streaming_callback === null) {
throw new \Exception('Set streaming callback before consuming a stream.');
}
$params['delimited'] = 'length';
list ($authorization, $url, $params, $request_headers)
= $this->_callApiPreparations(
$httpmethod, $method, $method_template, $params, false, $app_only_auth
);
$hostname = parse_url($url, PHP_URL_HOST);
$path = parse_url($url, PHP_URL_PATH);
$query = parse_url($url, PHP_URL_QUERY);
if ($hostname === false) {
throw new CodebirdEndpointException('Incorrect API endpoint host.');
}
$request_headers[] = 'Authorization: ' . $authorization;
$request_headers[] = 'Accept: */*';
if ($httpmethod !== 'GET') {
$request_headers[] = 'Content-Type: application/x-www-form-urlencoded';
$request_headers[] = 'Content-Length: ' . strlen($params);
}
$errno = 0;
$errstr = '';
$connection = stream_socket_client(
'ssl://' . $hostname . ':443',
$errno, $errstr,
$this->_timeouts['connect'],
STREAM_CLIENT_CONNECT
);
// send request
$request = $httpmethod . ' '
. $path . ($query ? '?' . $query : '') . " HTTP/1.1\r\n"
. 'Host: ' . $hostname . "\r\n"
. implode("\r\n", $request_headers)
. "\r\n\r\n";
if ($httpmethod !== 'GET') {
$request .= $params;
}
fputs($connection, $request);
stream_set_blocking($connection, 0);
stream_set_timeout($connection, 0);
// collect headers
do {
$result = stream_get_line($connection, 1048576, "\r\n\r\n");
} while(!$result);
$headers = explode("\r\n", $result);
// find HTTP status
$httpstatus = $this->_getHttpStatusFromHeaders($headers);
list($headers,) = $this->_parseApiHeaders($result);
$rate = $this->_getRateLimitInfo($headers);
if ($httpstatus !== '200') {
$reply = [
'httpstatus' => $httpstatus,
'rate' => $rate
];
switch ($this->_return_format) {
case CODEBIRD_RETURNFORMAT_ARRAY:
return $reply;
case CODEBIRD_RETURNFORMAT_OBJECT:
return (object) $reply;
case CODEBIRD_RETURNFORMAT_JSON:
return json_encode($reply);
}
}
$signal_function = function_exists('pcntl_signal_dispatch');
$data = '';
$last_message = $this->_time();
$message_length = 0;
while (!feof($connection)) {
// call signal handlers, if any
if ($signal_function) {
pcntl_signal_dispatch();
}
$connection_array = [$connection];
$write = $except = null;
if (false === ($num_changed_streams = stream_select($connection_array, $write, $except, 0, 200000))) {
break;
} elseif ($num_changed_streams === 0) {
if ($this->_time() - $last_message >= 1) {
// deliver empty message, allow callback to cancel stream
$cancel_stream = $this->_deliverStreamingMessage(null);
if ($cancel_stream) {
break;
}
$last_message = $this->_time();
}
continue;
}
$chunk_length = fgets($connection, 10);
if ($chunk_length === '' || !$chunk_length = hexdec($chunk_length)) {
continue;
}
$chunk = '';
do {
$chunk .= fread($connection, $chunk_length);
$chunk_length -= strlen($chunk);
} while($chunk_length > 0);
if(0 === $message_length) {
$message_length = (int) strstr($chunk, "\r\n", true);
if ($message_length) {
$chunk = substr($chunk, strpos($chunk, "\r\n") + 2);
} else {
continue;
}
$data = $chunk;
} else {
$data .= $chunk;
}
if (strlen($data) < $message_length) {
continue;
}
$reply = $this->_parseApiReply($data);
switch ($this->_return_format) {
case CODEBIRD_RETURNFORMAT_ARRAY:
$reply['httpstatus'] = $httpstatus;
$reply['rate'] = $rate;
break;
case CODEBIRD_RETURNFORMAT_OBJECT:
$reply->httpstatus = $httpstatus;
$reply->rate = $rate;
break;
}
$cancel_stream = $this->_deliverStreamingMessage($reply);
if ($cancel_stream) {
fclose($connection);
break;
}
$data = '';
$message_length = 0;
$last_message = $this->_time();
}
return;
} | [
"protected",
"function",
"_callApiStreaming",
"(",
"$",
"httpmethod",
",",
"$",
"method",
",",
"$",
"method_template",
",",
"$",
"params",
"=",
"[",
"]",
",",
"$",
"app_only_auth",
"=",
"false",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"_streaming_callback"... | Calls the streaming API
@param string $httpmethod The HTTP method to use for making the request
@param string $method The API method to call
@param string $method_template The API method template to call
@param array optional $params The parameters to send along
@param bool optional $app_only_auth Whether to use app-only bearer authentication
@return void
@throws \Exception | [
"Calls",
"the",
"streaming",
"API"
] | train | https://github.com/jublo/codebird-php/blob/0c20a63e95640f56102e76d3ca14462b3908acc1/src/codebird.php#L2412-L2566 |
jublo/codebird-php | src/codebird.php | Codebird._parseApiHeaders | protected function _parseApiHeaders($reply) {
// split headers and body
$headers = [];
$reply = explode("\r\n\r\n", $reply, 4);
// check if using proxy
$proxy_tester = strtolower(substr($reply[0], 0, 35));
if ($proxy_tester === 'http/1.0 200 connection established'
|| $proxy_tester === 'http/1.1 200 connection established'
) {
array_shift($reply);
}
$headers_array = explode("\r\n", $reply[0]);
foreach ($headers_array as $header) {
$header_array = explode(': ', $header, 2);
$key = $header_array[0];
$value = '';
if (count($header_array) > 1) {
$value = $header_array[1];
}
$headers[$key] = $value;
}
if (count($reply) > 1) {
$reply = $reply[1];
} else {
$reply = '';
}
return [$headers, $reply];
} | php | protected function _parseApiHeaders($reply) {
// split headers and body
$headers = [];
$reply = explode("\r\n\r\n", $reply, 4);
// check if using proxy
$proxy_tester = strtolower(substr($reply[0], 0, 35));
if ($proxy_tester === 'http/1.0 200 connection established'
|| $proxy_tester === 'http/1.1 200 connection established'
) {
array_shift($reply);
}
$headers_array = explode("\r\n", $reply[0]);
foreach ($headers_array as $header) {
$header_array = explode(': ', $header, 2);
$key = $header_array[0];
$value = '';
if (count($header_array) > 1) {
$value = $header_array[1];
}
$headers[$key] = $value;
}
if (count($reply) > 1) {
$reply = $reply[1];
} else {
$reply = '';
}
return [$headers, $reply];
} | [
"protected",
"function",
"_parseApiHeaders",
"(",
"$",
"reply",
")",
"{",
"// split headers and body",
"$",
"headers",
"=",
"[",
"]",
";",
"$",
"reply",
"=",
"explode",
"(",
"\"\\r\\n\\r\\n\"",
",",
"$",
"reply",
",",
"4",
")",
";",
"// check if using proxy",
... | Parses the API reply to separate headers from the body
@param string $reply The actual raw HTTP request reply
@return array (headers, reply) | [
"Parses",
"the",
"API",
"reply",
"to",
"separate",
"headers",
"from",
"the",
"body"
] | train | https://github.com/jublo/codebird-php/blob/0c20a63e95640f56102e76d3ca14462b3908acc1/src/codebird.php#L2587-L2618 |
jublo/codebird-php | src/codebird.php | Codebird._parseApiReplyPrefillHeaders | protected function _parseApiReplyPrefillHeaders($headers, $reply)
{
if ($reply === '' && (isset($headers['Location']) || isset($headers['location']))) {
$reply = [
'Location' => isset($headers['Location']) ? $headers['Location'] : $headers['location']
];
if (isset($headers['X-TON-Min-Chunk-Size'])) {
$reply['X-TON-Min-Chunk-Size'] = $headers['X-TON-Min-Chunk-Size'];
}
if (isset($headers['X-TON-Max-Chunk-Size'])) {
$reply['X-TON-Max-Chunk-Size'] = $headers['X-TON-Max-Chunk-Size'];
}
if (isset($headers['Range'])) {
$reply['Range'] = $headers['Range'];
}
$reply = json_encode($reply);
}
return $reply;
} | php | protected function _parseApiReplyPrefillHeaders($headers, $reply)
{
if ($reply === '' && (isset($headers['Location']) || isset($headers['location']))) {
$reply = [
'Location' => isset($headers['Location']) ? $headers['Location'] : $headers['location']
];
if (isset($headers['X-TON-Min-Chunk-Size'])) {
$reply['X-TON-Min-Chunk-Size'] = $headers['X-TON-Min-Chunk-Size'];
}
if (isset($headers['X-TON-Max-Chunk-Size'])) {
$reply['X-TON-Max-Chunk-Size'] = $headers['X-TON-Max-Chunk-Size'];
}
if (isset($headers['Range'])) {
$reply['Range'] = $headers['Range'];
}
$reply = json_encode($reply);
}
return $reply;
} | [
"protected",
"function",
"_parseApiReplyPrefillHeaders",
"(",
"$",
"headers",
",",
"$",
"reply",
")",
"{",
"if",
"(",
"$",
"reply",
"===",
"''",
"&&",
"(",
"isset",
"(",
"$",
"headers",
"[",
"'Location'",
"]",
")",
"||",
"isset",
"(",
"$",
"headers",
"... | Parses the API headers to return Location and Ton API headers
@param array $headers The headers list
@param string $reply The actual HTTP body
@return string $reply | [
"Parses",
"the",
"API",
"headers",
"to",
"return",
"Location",
"and",
"Ton",
"API",
"headers"
] | train | https://github.com/jublo/codebird-php/blob/0c20a63e95640f56102e76d3ca14462b3908acc1/src/codebird.php#L2628-L2646 |
jublo/codebird-php | src/codebird.php | Codebird._parseApiReply | protected function _parseApiReply($reply)
{
$need_array = $this->_return_format === CODEBIRD_RETURNFORMAT_ARRAY;
if ($reply === '[]') {
switch ($this->_return_format) {
case CODEBIRD_RETURNFORMAT_ARRAY:
return [];
case CODEBIRD_RETURNFORMAT_JSON:
return '{}';
case CODEBIRD_RETURNFORMAT_OBJECT:
return new \stdClass;
}
}
if (! $parsed = $this->_json_decode($reply, $need_array)) {
if ($reply) {
// assume query format
$reply = explode('&', $reply);
foreach ($reply as $element) {
if (stristr($element, '=')) {
list($key, $value) = explode('=', $element, 2);
$parsed[$key] = $value;
} else {
$parsed['message'] = $element;
}
}
}
$reply = json_encode($parsed);
}
switch ($this->_return_format) {
case CODEBIRD_RETURNFORMAT_ARRAY:
return $parsed;
case CODEBIRD_RETURNFORMAT_JSON:
return $reply;
case CODEBIRD_RETURNFORMAT_OBJECT:
return (object) $parsed;
}
return $parsed;
} | php | protected function _parseApiReply($reply)
{
$need_array = $this->_return_format === CODEBIRD_RETURNFORMAT_ARRAY;
if ($reply === '[]') {
switch ($this->_return_format) {
case CODEBIRD_RETURNFORMAT_ARRAY:
return [];
case CODEBIRD_RETURNFORMAT_JSON:
return '{}';
case CODEBIRD_RETURNFORMAT_OBJECT:
return new \stdClass;
}
}
if (! $parsed = $this->_json_decode($reply, $need_array)) {
if ($reply) {
// assume query format
$reply = explode('&', $reply);
foreach ($reply as $element) {
if (stristr($element, '=')) {
list($key, $value) = explode('=', $element, 2);
$parsed[$key] = $value;
} else {
$parsed['message'] = $element;
}
}
}
$reply = json_encode($parsed);
}
switch ($this->_return_format) {
case CODEBIRD_RETURNFORMAT_ARRAY:
return $parsed;
case CODEBIRD_RETURNFORMAT_JSON:
return $reply;
case CODEBIRD_RETURNFORMAT_OBJECT:
return (object) $parsed;
}
return $parsed;
} | [
"protected",
"function",
"_parseApiReply",
"(",
"$",
"reply",
")",
"{",
"$",
"need_array",
"=",
"$",
"this",
"->",
"_return_format",
"===",
"CODEBIRD_RETURNFORMAT_ARRAY",
";",
"if",
"(",
"$",
"reply",
"===",
"'[]'",
")",
"{",
"switch",
"(",
"$",
"this",
"-... | Parses the API reply to encode it in the set return_format
@param string $reply The actual HTTP body, JSON-encoded or URL-encoded
@return array|string|object The parsed reply | [
"Parses",
"the",
"API",
"reply",
"to",
"encode",
"it",
"in",
"the",
"set",
"return_format"
] | train | https://github.com/jublo/codebird-php/blob/0c20a63e95640f56102e76d3ca14462b3908acc1/src/codebird.php#L2655-L2692 |
geocoder-php/google-maps-provider | GoogleMaps.php | GoogleMaps.business | public static function business(HttpClient $client, string $clientId, string $privateKey = null, string $region = null, string $apiKey = null, string $channel = null)
{
$provider = new self($client, $region, $apiKey);
$provider->clientId = $clientId;
$provider->privateKey = $privateKey;
$provider->channel = $channel;
return $provider;
} | php | public static function business(HttpClient $client, string $clientId, string $privateKey = null, string $region = null, string $apiKey = null, string $channel = null)
{
$provider = new self($client, $region, $apiKey);
$provider->clientId = $clientId;
$provider->privateKey = $privateKey;
$provider->channel = $channel;
return $provider;
} | [
"public",
"static",
"function",
"business",
"(",
"HttpClient",
"$",
"client",
",",
"string",
"$",
"clientId",
",",
"string",
"$",
"privateKey",
"=",
"null",
",",
"string",
"$",
"region",
"=",
"null",
",",
"string",
"$",
"apiKey",
"=",
"null",
",",
"strin... | Google Maps for Business
https://developers.google.com/maps/documentation/business/.
@param HttpClient $client An HTTP adapter
@param string $clientId Your Client ID
@param string $privateKey Your Private Key (optional)
@param string $region Region biasing (optional)
@param string $apiKey Google Geocoding API key (optional)
@param string $channel Google Channel parameter (optional)
@return GoogleMaps | [
"Google",
"Maps",
"for",
"Business",
"https",
":",
"//",
"developers",
".",
"google",
".",
"com",
"/",
"maps",
"/",
"documentation",
"/",
"business",
"/",
"."
] | train | https://github.com/geocoder-php/google-maps-provider/blob/307ca3590b67d23d0658808bb3615f2be3154eee/GoogleMaps.php#L82-L90 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.