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
madewithlove/elasticsearcher
src/Managers/IndicesManager.php
IndicesManager.getRegistered
public function getRegistered($indexName) { if (!$this->isRegistered($indexName)) { throw new Exception('Index ['.$indexName.'] could not be found in the register of the indices manager.'); } return $this->indices[$indexName]; }
php
public function getRegistered($indexName) { if (!$this->isRegistered($indexName)) { throw new Exception('Index ['.$indexName.'] could not be found in the register of the indices manager.'); } return $this->indices[$indexName]; }
[ "public", "function", "getRegistered", "(", "$", "indexName", ")", "{", "if", "(", "!", "$", "this", "->", "isRegistered", "(", "$", "indexName", ")", ")", "{", "throw", "new", "Exception", "(", "'Index ['", ".", "$", "indexName", ".", "'] could not be fou...
Get a registered index. When not found it will throw an exception. If you do not want the exception being thrown, use getRegistered first. @return AbstractIndex @throws Exception @param string $indexName
[ "Get", "a", "registered", "index", ".", "When", "not", "found", "it", "will", "throw", "an", "exception", ".", "If", "you", "do", "not", "want", "the", "exception", "being", "thrown", "use", "getRegistered", "first", "." ]
train
https://github.com/madewithlove/elasticsearcher/blob/1d195d7ac47247c8f8b17d09b85e12e75970fd13/src/Managers/IndicesManager.php#L84-L91
madewithlove/elasticsearcher
src/Managers/IndicesManager.php
IndicesManager.get
public function get($indexName) { $index = $this->getRegistered($indexName); $params = [ 'index' => $index->getInternalName() ]; return $this->elasticSearcher->getClient()->indices()->getMapping($params); }
php
public function get($indexName) { $index = $this->getRegistered($indexName); $params = [ 'index' => $index->getInternalName() ]; return $this->elasticSearcher->getClient()->indices()->getMapping($params); }
[ "public", "function", "get", "(", "$", "indexName", ")", "{", "$", "index", "=", "$", "this", "->", "getRegistered", "(", "$", "indexName", ")", ";", "$", "params", "=", "[", "'index'", "=>", "$", "index", "->", "getInternalName", "(", ")", "]", ";",...
@return array @param string $indexName
[ "@return", "array" ]
train
https://github.com/madewithlove/elasticsearcher/blob/1d195d7ac47247c8f8b17d09b85e12e75970fd13/src/Managers/IndicesManager.php#L109-L118
madewithlove/elasticsearcher
src/Managers/IndicesManager.php
IndicesManager.getType
public function getType($indexName, $type) { $index = $this->getRegistered($indexName); $params = [ 'index' => $index->getInternalName(), 'type' => $type ]; return $this->elasticSearcher->getClient()->indices()->getMapping($params); }
php
public function getType($indexName, $type) { $index = $this->getRegistered($indexName); $params = [ 'index' => $index->getInternalName(), 'type' => $type ]; return $this->elasticSearcher->getClient()->indices()->getMapping($params); }
[ "public", "function", "getType", "(", "$", "indexName", ",", "$", "type", ")", "{", "$", "index", "=", "$", "this", "->", "getRegistered", "(", "$", "indexName", ")", ";", "$", "params", "=", "[", "'index'", "=>", "$", "index", "->", "getInternalName",...
@return array @param string $indexName @param string $type
[ "@return", "array" ]
train
https://github.com/madewithlove/elasticsearcher/blob/1d195d7ac47247c8f8b17d09b85e12e75970fd13/src/Managers/IndicesManager.php#L126-L136
madewithlove/elasticsearcher
src/Managers/IndicesManager.php
IndicesManager.update
public function update($indexName) { $index = $this->getRegistered($indexName); foreach ($index->getTypes() as $type => $typeBody) { $params = [ 'index' => $index->getInternalName(), 'type' => $type, 'body' => [$type => $typeBody] ]; $this->elasticSearcher->getClient()->indices()->putMapping($params); } }
php
public function update($indexName) { $index = $this->getRegistered($indexName); foreach ($index->getTypes() as $type => $typeBody) { $params = [ 'index' => $index->getInternalName(), 'type' => $type, 'body' => [$type => $typeBody] ]; $this->elasticSearcher->getClient()->indices()->putMapping($params); } }
[ "public", "function", "update", "(", "$", "indexName", ")", "{", "$", "index", "=", "$", "this", "->", "getRegistered", "(", "$", "indexName", ")", ";", "foreach", "(", "$", "index", "->", "getTypes", "(", ")", "as", "$", "type", "=>", "$", "typeBody...
Update the index and all its types. This should be used when wanting to reflect changes in the Index object with the elasticsearch server. @param string $indexName
[ "Update", "the", "index", "and", "all", "its", "types", ".", "This", "should", "be", "used", "when", "wanting", "to", "reflect", "changes", "in", "the", "Index", "object", "with", "the", "elasticsearch", "server", "." ]
train
https://github.com/madewithlove/elasticsearcher/blob/1d195d7ac47247c8f8b17d09b85e12e75970fd13/src/Managers/IndicesManager.php#L159-L172
madewithlove/elasticsearcher
src/Managers/IndicesManager.php
IndicesManager.existsType
public function existsType($indexName, $type) { $index = $this->getRegistered($indexName); $params = [ 'index' => $index->getInternalName(), 'type' => $type ]; return $this->elasticSearcher->getClient()->indices()->existsType($params); }
php
public function existsType($indexName, $type) { $index = $this->getRegistered($indexName); $params = [ 'index' => $index->getInternalName(), 'type' => $type ]; return $this->elasticSearcher->getClient()->indices()->existsType($params); }
[ "public", "function", "existsType", "(", "$", "indexName", ",", "$", "type", ")", "{", "$", "index", "=", "$", "this", "->", "getRegistered", "(", "$", "indexName", ")", ";", "$", "params", "=", "[", "'index'", "=>", "$", "index", "->", "getInternalNam...
@return bool @param string $indexName @param string $type
[ "@return", "bool" ]
train
https://github.com/madewithlove/elasticsearcher/blob/1d195d7ac47247c8f8b17d09b85e12e75970fd13/src/Managers/IndicesManager.php#L226-L236
madewithlove/elasticsearcher
src/Traits/BodyTrait.php
BodyTrait.set
public function set($key, $value) { Arr::set($this->body, $key, $value); return $this; }
php
public function set($key, $value) { Arr::set($this->body, $key, $value); return $this; }
[ "public", "function", "set", "(", "$", "key", ",", "$", "value", ")", "{", "Arr", "::", "set", "(", "$", "this", "->", "body", ",", "$", "key", ",", "$", "value", ")", ";", "return", "$", "this", ";", "}" ]
Set a value in the body using the dotted notation. @param string $key @param mixed $value @return $this
[ "Set", "a", "value", "in", "the", "body", "using", "the", "dotted", "notation", "." ]
train
https://github.com/madewithlove/elasticsearcher/blob/1d195d7ac47247c8f8b17d09b85e12e75970fd13/src/Traits/BodyTrait.php#L47-L52
madewithlove/elasticsearcher
src/Managers/DocumentsManager.php
DocumentsManager.index
public function index($indexName, $type, array $data) { $index = $this->elasticSearcher->indicesManager()->getRegistered($indexName); $params = [ 'index' => $index->getInternalName(), 'type' => $type, 'body' => $data ]; // If an ID exists in the data set, use it, otherwise let elasticsearch generate one. if (array_key_exists('id', $data)) { $params['id'] = $data['id']; } return $this->elasticSearcher->getClient()->index($params); }
php
public function index($indexName, $type, array $data) { $index = $this->elasticSearcher->indicesManager()->getRegistered($indexName); $params = [ 'index' => $index->getInternalName(), 'type' => $type, 'body' => $data ]; // If an ID exists in the data set, use it, otherwise let elasticsearch generate one. if (array_key_exists('id', $data)) { $params['id'] = $data['id']; } return $this->elasticSearcher->getClient()->index($params); }
[ "public", "function", "index", "(", "$", "indexName", ",", "$", "type", ",", "array", "$", "data", ")", "{", "$", "index", "=", "$", "this", "->", "elasticSearcher", "->", "indicesManager", "(", ")", "->", "getRegistered", "(", "$", "indexName", ")", "...
Create a document. @return array @param string $indexName @param string $type @param array $data
[ "Create", "a", "document", "." ]
train
https://github.com/madewithlove/elasticsearcher/blob/1d195d7ac47247c8f8b17d09b85e12e75970fd13/src/Managers/DocumentsManager.php#L22-L38
madewithlove/elasticsearcher
src/Managers/DocumentsManager.php
DocumentsManager.bulkIndex
public function bulkIndex($indexName, $type, array $data) { $params = ['body' => []]; foreach ($data as $item) { $header = [ '_index' => $indexName, '_type' => $type, ]; if (array_key_exists('id', $item)) { $header['_id'] = $item['id']; } // The bulk operation expects two JSON objects for each item // the first one should describe the operation, index, type // and ID. The later one is the document body. $params['body'][] = ['index' => $header]; $params['body'][] = $item; } $this->elasticSearcher->getClient()->bulk($params); }
php
public function bulkIndex($indexName, $type, array $data) { $params = ['body' => []]; foreach ($data as $item) { $header = [ '_index' => $indexName, '_type' => $type, ]; if (array_key_exists('id', $item)) { $header['_id'] = $item['id']; } // The bulk operation expects two JSON objects for each item // the first one should describe the operation, index, type // and ID. The later one is the document body. $params['body'][] = ['index' => $header]; $params['body'][] = $item; } $this->elasticSearcher->getClient()->bulk($params); }
[ "public", "function", "bulkIndex", "(", "$", "indexName", ",", "$", "type", ",", "array", "$", "data", ")", "{", "$", "params", "=", "[", "'body'", "=>", "[", "]", "]", ";", "foreach", "(", "$", "data", "as", "$", "item", ")", "{", "$", "header",...
Index a set of documents. @param string $indexName @param string $type @param array $data
[ "Index", "a", "set", "of", "documents", "." ]
train
https://github.com/madewithlove/elasticsearcher/blob/1d195d7ac47247c8f8b17d09b85e12e75970fd13/src/Managers/DocumentsManager.php#L47-L69
madewithlove/elasticsearcher
src/Managers/DocumentsManager.php
DocumentsManager.delete
public function delete($indexName, $type, $id) { $index = $this->elasticSearcher->indicesManager()->getRegistered($indexName); $params = [ 'index' => $index->getInternalName(), 'type' => $type, 'id' => $id ]; return $this->elasticSearcher->getClient()->delete($params); }
php
public function delete($indexName, $type, $id) { $index = $this->elasticSearcher->indicesManager()->getRegistered($indexName); $params = [ 'index' => $index->getInternalName(), 'type' => $type, 'id' => $id ]; return $this->elasticSearcher->getClient()->delete($params); }
[ "public", "function", "delete", "(", "$", "indexName", ",", "$", "type", ",", "$", "id", ")", "{", "$", "index", "=", "$", "this", "->", "elasticSearcher", "->", "indicesManager", "(", ")", "->", "getRegistered", "(", "$", "indexName", ")", ";", "$", ...
@return array @param string $indexName @param string $type @param string $id
[ "@return", "array" ]
train
https://github.com/madewithlove/elasticsearcher/blob/1d195d7ac47247c8f8b17d09b85e12e75970fd13/src/Managers/DocumentsManager.php#L78-L89
madewithlove/elasticsearcher
src/Managers/DocumentsManager.php
DocumentsManager.update
public function update($indexName, $type, $id, array $data) { $index = $this->elasticSearcher->indicesManager()->getRegistered($indexName); $params = [ 'index' => $index->getInternalName(), 'type' => $type, 'id' => $id, 'body' => ['doc' => $data] ]; return $this->elasticSearcher->getClient()->update($params); }
php
public function update($indexName, $type, $id, array $data) { $index = $this->elasticSearcher->indicesManager()->getRegistered($indexName); $params = [ 'index' => $index->getInternalName(), 'type' => $type, 'id' => $id, 'body' => ['doc' => $data] ]; return $this->elasticSearcher->getClient()->update($params); }
[ "public", "function", "update", "(", "$", "indexName", ",", "$", "type", ",", "$", "id", ",", "array", "$", "data", ")", "{", "$", "index", "=", "$", "this", "->", "elasticSearcher", "->", "indicesManager", "(", ")", "->", "getRegistered", "(", "$", ...
Partial updating of an existing document. @return array @param string $indexName @param string $type @param string $id @param array $data
[ "Partial", "updating", "of", "an", "existing", "document", "." ]
train
https://github.com/madewithlove/elasticsearcher/blob/1d195d7ac47247c8f8b17d09b85e12e75970fd13/src/Managers/DocumentsManager.php#L101-L113
madewithlove/elasticsearcher
src/Managers/DocumentsManager.php
DocumentsManager.updateOrIndex
public function updateOrIndex($indexName, $type, $id, array $data) { if ($this->exists($indexName, $type, $id)) { return $this->update($indexName, $type, $id, $data); } else { return $this->index($indexName, $type, $data); } }
php
public function updateOrIndex($indexName, $type, $id, array $data) { if ($this->exists($indexName, $type, $id)) { return $this->update($indexName, $type, $id, $data); } else { return $this->index($indexName, $type, $data); } }
[ "public", "function", "updateOrIndex", "(", "$", "indexName", ",", "$", "type", ",", "$", "id", ",", "array", "$", "data", ")", "{", "if", "(", "$", "this", "->", "exists", "(", "$", "indexName", ",", "$", "type", ",", "$", "id", ")", ")", "{", ...
Update a document. Create it if it doesn't exist. @return array @param string $indexName @param string $type @param string $id @param array $data
[ "Update", "a", "document", ".", "Create", "it", "if", "it", "doesn", "t", "exist", "." ]
train
https://github.com/madewithlove/elasticsearcher/blob/1d195d7ac47247c8f8b17d09b85e12e75970fd13/src/Managers/DocumentsManager.php#L145-L152
madewithlove/elasticsearcher
src/Fragments/Traits/PaginatedTrait.php
PaginatedTrait.paginate
public function paginate($page, $perPage = 30) { $this->set('from', max(0, $perPage * ($page - 1))); $this->set('size', $perPage); return $this; }
php
public function paginate($page, $perPage = 30) { $this->set('from', max(0, $perPage * ($page - 1))); $this->set('size', $perPage); return $this; }
[ "public", "function", "paginate", "(", "$", "page", ",", "$", "perPage", "=", "30", ")", "{", "$", "this", "->", "set", "(", "'from'", ",", "max", "(", "0", ",", "$", "perPage", "*", "(", "$", "page", "-", "1", ")", ")", ")", ";", "$", "this"...
@param int $page @param int $perPage @return static
[ "@param", "int", "$page", "@param", "int", "$perPage" ]
train
https://github.com/madewithlove/elasticsearcher/blob/1d195d7ac47247c8f8b17d09b85e12e75970fd13/src/Fragments/Traits/PaginatedTrait.php#L18-L24
yidas/codeigniter-queue-worker
src/Controller.php
Controller.listen
public function listen() { // Env check if (!$this->_isLinux()) { die("Error environment: Queue Listener requires Linux OS, you could use `work` or `single` instead."); } // Pre-work check if (!method_exists($this, 'handleListen')) throw new Exception("You need to declare `handleListen()` method in your worker controller.", 500); if (!method_exists($this, 'handleWork')) throw new Exception("You need to declare `handleWork()` method in your worker controller.", 500); if ($this->logPath && !file_exists($this->logPath)) { // Try to access or create log file if ($this->_log('')) { throw new Exception("Log file doesn't exist: `{$this->logPath}`.", 500); } } // INI setting if ($this->debug) { error_reporting(-1); ini_set('display_errors', 1); } set_time_limit(0); // Worker command builder // Be careful to avoid infinite loop by opening listener itself $workerAction = 'work'; $route = $this->router->fetch_directory() . $this->router->fetch_class() . "/{$workerAction}"; $workerCmd = "{$this->phpCommand} " . FCPATH . "index.php {$route}"; // Static variables $startTime = 0; $workerCount = 0; $workingFlag = false; // Setting check $this->workerMaxNum = ($this->workerMaxNum >= 1) ? floor($this->workerMaxNum) : 1; $this->workerStartNum = ($this->workerStartNum <= $this->workerMaxNum) ? floor($this->workerStartNum) : $this->workerMaxNum; $this->workerWaitSeconds = ($this->workerWaitSeconds >= 1) ? $this->workerWaitSeconds : 10; while (true) { // Loading insurance sleep(0.1); // Call customized listener process, assigns works while catching true by callback return $hasEvent = ($this->handleListen($this->_staticListen)) ? true : false; // Start works if exists if ($hasEvent) { // First time to assign works if (!$workingFlag) { $workingFlag = true; $startTime = microtime(true); $this->_log("Queue Listener - Job detect"); $this->_log("Queue Listener - Start dispatch"); if ($this->workerStartNum > 1) { // Execute extra worker numbers for ($i=1; $i < $this->workerStartNum ; $i++) { $workerCount ++; $r = $this->_workerCmd($workerCmd, $workerCount); } } } // Max running worker numbers check, otherwise keeps dispatching more workers if ($this->workerMaxNum <= $workerCount) { // Worker heath check if ($this->workerHeathCheck) { foreach ($this->_pidStack as $id => $pid) { $isAlive = $this->_isPidAlive($pid); if (!$isAlive) { $this->_log("Queue Listener - Worker health check: Missing #{$id} (PID: {$pid})"); $r = $this->_workerCmd($workerCmd, $id); } } } sleep($this->workerWaitSeconds); continue; } // Assign works $workerCount ++; // Create a worker $r = $this->_workerCmd($workerCmd, $workerCount); sleep($this->workerWaitSeconds); continue; } // The end of assignment (No more work), close the assignment if ($workingFlag) { $workingFlag = false; $workerCount = 0; // Clear worker stack $this->_pidStack = []; $costSeconds = number_format(microtime(true) - $startTime, 2, '.', ''); $this->_log("Queue Listener - Job empty"); $this->_log("Queue Listener - Stop dispatch, total cost: {$costSeconds}s"); } // Idle if ($this->listenerSleep) { sleep($this->listenerSleep); } } }
php
public function listen() { // Env check if (!$this->_isLinux()) { die("Error environment: Queue Listener requires Linux OS, you could use `work` or `single` instead."); } // Pre-work check if (!method_exists($this, 'handleListen')) throw new Exception("You need to declare `handleListen()` method in your worker controller.", 500); if (!method_exists($this, 'handleWork')) throw new Exception("You need to declare `handleWork()` method in your worker controller.", 500); if ($this->logPath && !file_exists($this->logPath)) { // Try to access or create log file if ($this->_log('')) { throw new Exception("Log file doesn't exist: `{$this->logPath}`.", 500); } } // INI setting if ($this->debug) { error_reporting(-1); ini_set('display_errors', 1); } set_time_limit(0); // Worker command builder // Be careful to avoid infinite loop by opening listener itself $workerAction = 'work'; $route = $this->router->fetch_directory() . $this->router->fetch_class() . "/{$workerAction}"; $workerCmd = "{$this->phpCommand} " . FCPATH . "index.php {$route}"; // Static variables $startTime = 0; $workerCount = 0; $workingFlag = false; // Setting check $this->workerMaxNum = ($this->workerMaxNum >= 1) ? floor($this->workerMaxNum) : 1; $this->workerStartNum = ($this->workerStartNum <= $this->workerMaxNum) ? floor($this->workerStartNum) : $this->workerMaxNum; $this->workerWaitSeconds = ($this->workerWaitSeconds >= 1) ? $this->workerWaitSeconds : 10; while (true) { // Loading insurance sleep(0.1); // Call customized listener process, assigns works while catching true by callback return $hasEvent = ($this->handleListen($this->_staticListen)) ? true : false; // Start works if exists if ($hasEvent) { // First time to assign works if (!$workingFlag) { $workingFlag = true; $startTime = microtime(true); $this->_log("Queue Listener - Job detect"); $this->_log("Queue Listener - Start dispatch"); if ($this->workerStartNum > 1) { // Execute extra worker numbers for ($i=1; $i < $this->workerStartNum ; $i++) { $workerCount ++; $r = $this->_workerCmd($workerCmd, $workerCount); } } } // Max running worker numbers check, otherwise keeps dispatching more workers if ($this->workerMaxNum <= $workerCount) { // Worker heath check if ($this->workerHeathCheck) { foreach ($this->_pidStack as $id => $pid) { $isAlive = $this->_isPidAlive($pid); if (!$isAlive) { $this->_log("Queue Listener - Worker health check: Missing #{$id} (PID: {$pid})"); $r = $this->_workerCmd($workerCmd, $id); } } } sleep($this->workerWaitSeconds); continue; } // Assign works $workerCount ++; // Create a worker $r = $this->_workerCmd($workerCmd, $workerCount); sleep($this->workerWaitSeconds); continue; } // The end of assignment (No more work), close the assignment if ($workingFlag) { $workingFlag = false; $workerCount = 0; // Clear worker stack $this->_pidStack = []; $costSeconds = number_format(microtime(true) - $startTime, 2, '.', ''); $this->_log("Queue Listener - Job empty"); $this->_log("Queue Listener - Stop dispatch, total cost: {$costSeconds}s"); } // Idle if ($this->listenerSleep) { sleep($this->listenerSleep); } } }
[ "public", "function", "listen", "(", ")", "{", "// Env check", "if", "(", "!", "$", "this", "->", "_isLinux", "(", ")", ")", "{", "die", "(", "\"Error environment: Queue Listener requires Linux OS, you could use `work` or `single` instead.\"", ")", ";", "}", "// Pre-w...
Action for activating a worker listener @return void
[ "Action", "for", "activating", "a", "worker", "listener" ]
train
https://github.com/yidas/codeigniter-queue-worker/blob/3cf7ac84e715e7fabbb1925363b85f444023fd64/src/Controller.php#L158-L270
yidas/codeigniter-queue-worker
src/Controller.php
Controller.work
public function work($id=1) { // Pre-work check if (!method_exists($this, 'handleWork')) throw new Exception("You need to declare `handleWork()` method in your worker controller.", 500); // INI setting if ($this->debug) { error_reporting(-1); ini_set('display_errors', 1); } set_time_limit(0); // Start worker $startTime = microtime(true); $pid = getmypid(); // Print worker close $this->_print("Queue Worker - Create #{$id} (PID: {$pid})"); // Call customized worker process, stops till catch false by callback return while ($this->handleWork($this->_staticWork)) { // Sleep if set if ($this->workerSleep) { sleep($this->workerSleep); } // Loading insurance sleep(0.1); } // Print worker close $costSeconds = number_format(microtime(true) - $startTime, 2, '.', ''); $this->_print("Queue Worker - Close #{$id} (PID: {$pid}) | cost: {$costSeconds}s"); return; }
php
public function work($id=1) { // Pre-work check if (!method_exists($this, 'handleWork')) throw new Exception("You need to declare `handleWork()` method in your worker controller.", 500); // INI setting if ($this->debug) { error_reporting(-1); ini_set('display_errors', 1); } set_time_limit(0); // Start worker $startTime = microtime(true); $pid = getmypid(); // Print worker close $this->_print("Queue Worker - Create #{$id} (PID: {$pid})"); // Call customized worker process, stops till catch false by callback return while ($this->handleWork($this->_staticWork)) { // Sleep if set if ($this->workerSleep) { sleep($this->workerSleep); } // Loading insurance sleep(0.1); } // Print worker close $costSeconds = number_format(microtime(true) - $startTime, 2, '.', ''); $this->_print("Queue Worker - Close #{$id} (PID: {$pid}) | cost: {$costSeconds}s"); return; }
[ "public", "function", "work", "(", "$", "id", "=", "1", ")", "{", "// Pre-work check", "if", "(", "!", "method_exists", "(", "$", "this", ",", "'handleWork'", ")", ")", "throw", "new", "Exception", "(", "\"You need to declare `handleWork()` method in your worker c...
Action for creating a worker @param integer $id @return void
[ "Action", "for", "creating", "a", "worker" ]
train
https://github.com/yidas/codeigniter-queue-worker/blob/3cf7ac84e715e7fabbb1925363b85f444023fd64/src/Controller.php#L278-L312
yidas/codeigniter-queue-worker
src/Controller.php
Controller.launch
public function launch($action='listen') { // Env check if (!$this->_isLinux()) { die("Error environment: Queue Launcher requires Linux OS, you could use `work` or `single` instead."); } // Action check if (!in_array($action, ['listen', 'work'])) { die("Action: `{$action}` is invalid for Launcher."); } // Null so far $logPath = '/dev/null'; // Action command builder $route = $this->router->fetch_directory() . $this->router->fetch_class() . "/{$action}"; $cmd = "{$this->phpCommand} " . FCPATH . "index.php {$route}"; // Check process exists $search = str_replace('/', '\/', $route); // $result = shell_exec("pgrep -f \"{$search}\""); // Lacks of display info // Find out the process by name $psCmd = "ps aux | grep \"{$search}\" | grep -v grep"; $psInfoCmd = "ps aux | egrep \"PID|{$search}\" | grep -v grep"; $exist = (shell_exec($psCmd)) ? true : false; if ($exist) { $psInfo = shell_exec($psInfoCmd); die("Skip: Same process `{$action}` is running: {$route}.\n------\n{$psInfo}"); } // Launch by calling command $launchCmd = "{$cmd} > {$logPath} &"; $result = shell_exec($launchCmd); $result = shell_exec($psCmd); $psInfo = shell_exec($psInfoCmd); echo "Success to launch process `{$action}`: {$route}.\nCalled command: {$launchCmd}\n------\n{$psInfo}"; return; }
php
public function launch($action='listen') { // Env check if (!$this->_isLinux()) { die("Error environment: Queue Launcher requires Linux OS, you could use `work` or `single` instead."); } // Action check if (!in_array($action, ['listen', 'work'])) { die("Action: `{$action}` is invalid for Launcher."); } // Null so far $logPath = '/dev/null'; // Action command builder $route = $this->router->fetch_directory() . $this->router->fetch_class() . "/{$action}"; $cmd = "{$this->phpCommand} " . FCPATH . "index.php {$route}"; // Check process exists $search = str_replace('/', '\/', $route); // $result = shell_exec("pgrep -f \"{$search}\""); // Lacks of display info // Find out the process by name $psCmd = "ps aux | grep \"{$search}\" | grep -v grep"; $psInfoCmd = "ps aux | egrep \"PID|{$search}\" | grep -v grep"; $exist = (shell_exec($psCmd)) ? true : false; if ($exist) { $psInfo = shell_exec($psInfoCmd); die("Skip: Same process `{$action}` is running: {$route}.\n------\n{$psInfo}"); } // Launch by calling command $launchCmd = "{$cmd} > {$logPath} &"; $result = shell_exec($launchCmd); $result = shell_exec($psCmd); $psInfo = shell_exec($psInfoCmd); echo "Success to launch process `{$action}`: {$route}.\nCalled command: {$launchCmd}\n------\n{$psInfo}"; return; }
[ "public", "function", "launch", "(", "$", "action", "=", "'listen'", ")", "{", "// Env check", "if", "(", "!", "$", "this", "->", "_isLinux", "(", ")", ")", "{", "die", "(", "\"Error environment: Queue Launcher requires Linux OS, you could use `work` or `single` inste...
Launcher for guaranteeing unique process This launcher would launch specified process if there are no any other same process running by launcher. Using this for launching `listen` could ensure there are always one listener running at the same time with repeated launch calling likes crontab, which could also ensure listener process would never gone away. @param string $action @return void
[ "Launcher", "for", "guaranteeing", "unique", "process" ]
train
https://github.com/yidas/codeigniter-queue-worker/blob/3cf7ac84e715e7fabbb1925363b85f444023fd64/src/Controller.php#L325-L366
yidas/codeigniter-queue-worker
src/Controller.php
Controller.single
public function single($force=false) { // Pre-work check if (!method_exists($this, 'handleSingle')) throw new Exception("You need to declare `handleSingle()` method in your worker controller.", 500); // Shared lock flag builder $lockFile = sys_get_temp_dir() . "/yidas-codeiginiter-queue-worker_" . str_replace('/', '_', $this->router->fetch_directory()) . get_called_class() . '.lock'; // Single check for process uniqueness if (!$force && file_exists($lockFile)) { $lockData = json_decode(file_get_contents($lockFile), true); // Check expires time if (isset($lockData['expires_at']) && time() <= $lockData['expires_at']) { die("Single is already running: {$lockFile}\n"); } } // Start Single - Set identified lock // Close Single - Release identified lock register_shutdown_function(function() use ($lockFile) { @unlink($lockFile); }); // Create lock file $this->_singleUpdateLock($lockFile); // Call customized worker process, stops till catch false by callback return while ($this->handleSingle($this->_staticSingle)) { // Sleep if set if ($this->singleSleep) { sleep($this->singleSleep); } // Refresh lock file $this->_singleUpdateLock($lockFile); } }
php
public function single($force=false) { // Pre-work check if (!method_exists($this, 'handleSingle')) throw new Exception("You need to declare `handleSingle()` method in your worker controller.", 500); // Shared lock flag builder $lockFile = sys_get_temp_dir() . "/yidas-codeiginiter-queue-worker_" . str_replace('/', '_', $this->router->fetch_directory()) . get_called_class() . '.lock'; // Single check for process uniqueness if (!$force && file_exists($lockFile)) { $lockData = json_decode(file_get_contents($lockFile), true); // Check expires time if (isset($lockData['expires_at']) && time() <= $lockData['expires_at']) { die("Single is already running: {$lockFile}\n"); } } // Start Single - Set identified lock // Close Single - Release identified lock register_shutdown_function(function() use ($lockFile) { @unlink($lockFile); }); // Create lock file $this->_singleUpdateLock($lockFile); // Call customized worker process, stops till catch false by callback return while ($this->handleSingle($this->_staticSingle)) { // Sleep if set if ($this->singleSleep) { sleep($this->singleSleep); } // Refresh lock file $this->_singleUpdateLock($lockFile); } }
[ "public", "function", "single", "(", "$", "force", "=", "false", ")", "{", "// Pre-work check", "if", "(", "!", "method_exists", "(", "$", "this", ",", "'handleSingle'", ")", ")", "throw", "new", "Exception", "(", "\"You need to declare `handleSingle()` method in ...
Action for activating a single listened worker Single process ensures unique process running, which prevents the same The reason which this doesn't use process check method such as `ps`, `pgrep`, is that the process ID or name are unrecognizable as unique for ensuring only one Single process is running. @return void
[ "Action", "for", "activating", "a", "single", "listened", "worker" ]
train
https://github.com/yidas/codeigniter-queue-worker/blob/3cf7ac84e715e7fabbb1925363b85f444023fd64/src/Controller.php#L379-L422
yidas/codeigniter-queue-worker
src/Controller.php
Controller._singleUpdateLock
public function _singleUpdateLock($lockFile) { $lockData = [ 'pid' => getmypid(), 'expires_at' => time() + $this->singleSleep + $this->singleLockTimeout, ]; return file_put_contents($lockFile, json_encode($lockData)); }
php
public function _singleUpdateLock($lockFile) { $lockData = [ 'pid' => getmypid(), 'expires_at' => time() + $this->singleSleep + $this->singleLockTimeout, ]; return file_put_contents($lockFile, json_encode($lockData)); }
[ "public", "function", "_singleUpdateLock", "(", "$", "lockFile", ")", "{", "$", "lockData", "=", "[", "'pid'", "=>", "getmypid", "(", ")", ",", "'expires_at'", "=>", "time", "(", ")", "+", "$", "this", "->", "singleSleep", "+", "$", "this", "->", "sing...
Single process creates or extends lock file Extended second bases on sleep time and lock expiration @param string $lockFile @return void
[ "Single", "process", "creates", "or", "extends", "lock", "file" ]
train
https://github.com/yidas/codeigniter-queue-worker/blob/3cf7ac84e715e7fabbb1925363b85f444023fd64/src/Controller.php#L480-L488
yidas/codeigniter-queue-worker
src/Controller.php
Controller._workerCmd
protected function _workerCmd($workerCmd, $workerCount) { // Shell command builder $cmd = "{$workerCmd}/{$workerCount}"; $cmd = ($this->logPath) ? "{$cmd} >> {$this->logPath}" : $cmd; // Process handler $process = proc_open("{$cmd} &", self::$_procDescriptorspec, $pipe); // Find out worker command's PID $status = proc_get_status($process); $pid = $status['pid'] + 1; // Stack workers $this->_pidStack[$workerCount] = $pid; // Close proc_close($process); // Log $time = date("Y-m-d H:i:s"); $this->_log("Queue Listener - Dispatch Worker #{$workerCount} (PID: {$pid})"); return true; }
php
protected function _workerCmd($workerCmd, $workerCount) { // Shell command builder $cmd = "{$workerCmd}/{$workerCount}"; $cmd = ($this->logPath) ? "{$cmd} >> {$this->logPath}" : $cmd; // Process handler $process = proc_open("{$cmd} &", self::$_procDescriptorspec, $pipe); // Find out worker command's PID $status = proc_get_status($process); $pid = $status['pid'] + 1; // Stack workers $this->_pidStack[$workerCount] = $pid; // Close proc_close($process); // Log $time = date("Y-m-d H:i:s"); $this->_log("Queue Listener - Dispatch Worker #{$workerCount} (PID: {$pid})"); return true; }
[ "protected", "function", "_workerCmd", "(", "$", "workerCmd", ",", "$", "workerCount", ")", "{", "// Shell command builder", "$", "cmd", "=", "\"{$workerCmd}/{$workerCount}\"", ";", "$", "cmd", "=", "(", "$", "this", "->", "logPath", ")", "?", "\"{$cmd} >> {$thi...
Command for creating a worker @param string $workerCmd @param integer $workerCount @return string Command result
[ "Command", "for", "creating", "a", "worker" ]
train
https://github.com/yidas/codeigniter-queue-worker/blob/3cf7ac84e715e7fabbb1925363b85f444023fd64/src/Controller.php#L497-L518
yidas/codeigniter-queue-worker
src/Controller.php
Controller._log
protected function _log($textLine, $logPath=null) { // Return back to console also $this->_print($textLine); $logPath = ($logPath) ? $logPath : $this->logPath; if ($logPath) return file_put_contents($logPath, $this->_formatTextLine($textLine), FILE_APPEND); else return false; }
php
protected function _log($textLine, $logPath=null) { // Return back to console also $this->_print($textLine); $logPath = ($logPath) ? $logPath : $this->logPath; if ($logPath) return file_put_contents($logPath, $this->_formatTextLine($textLine), FILE_APPEND); else return false; }
[ "protected", "function", "_log", "(", "$", "textLine", ",", "$", "logPath", "=", "null", ")", "{", "// Return back to console also", "$", "this", "->", "_print", "(", "$", "textLine", ")", ";", "$", "logPath", "=", "(", "$", "logPath", ")", "?", "$", "...
Log to file @param string $textLine @param string Specified log file path @return integer|boolean The number of bytes that were written to the file, or FALSE on failure.
[ "Log", "to", "file" ]
train
https://github.com/yidas/codeigniter-queue-worker/blob/3cf7ac84e715e7fabbb1925363b85f444023fd64/src/Controller.php#L527-L538
yidas/codeigniter-queue-worker
examples/myjobs/MyjobsWithRedis.php
MyjobsWithRedis.popJob
public function popJob() { // Assume storing JSON string data in queue // Using LPOP or RPOP depends on your producer push $taskJSON = $this->redisClient->lpop(self::QUEUE_KEY); return json_decode($taskJSON, true); }
php
public function popJob() { // Assume storing JSON string data in queue // Using LPOP or RPOP depends on your producer push $taskJSON = $this->redisClient->lpop(self::QUEUE_KEY); return json_decode($taskJSON, true); }
[ "public", "function", "popJob", "(", ")", "{", "// Assume storing JSON string data in queue", "// Using LPOP or RPOP depends on your producer push", "$", "taskJSON", "=", "$", "this", "->", "redisClient", "->", "lpop", "(", "self", "::", "QUEUE_KEY", ")", ";", "return",...
Pop up a job from Redis queue @return array
[ "Pop", "up", "a", "job", "from", "Redis", "queue" ]
train
https://github.com/yidas/codeigniter-queue-worker/blob/3cf7ac84e715e7fabbb1925363b85f444023fd64/examples/myjobs/MyjobsWithRedis.php#L61-L68
VisualAppeal/PHP-Auto-Update
src/AutoUpdate.php
AutoUpdate.setTempDir
public function setTempDir($dir) { $dir = $this->addTrailingSlash($dir); if (!is_dir($dir)) { $this->log->addDebug(sprintf('Creating new temporary directory "%s"', $dir)); if (!mkdir($dir, 0755, true)) { $this->log->addCritical(sprintf('Could not create temporary directory "%s"', $dir)); return false; } } $this->tempDir = $dir; return true; }
php
public function setTempDir($dir) { $dir = $this->addTrailingSlash($dir); if (!is_dir($dir)) { $this->log->addDebug(sprintf('Creating new temporary directory "%s"', $dir)); if (!mkdir($dir, 0755, true)) { $this->log->addCritical(sprintf('Could not create temporary directory "%s"', $dir)); return false; } } $this->tempDir = $dir; return true; }
[ "public", "function", "setTempDir", "(", "$", "dir", ")", "{", "$", "dir", "=", "$", "this", "->", "addTrailingSlash", "(", "$", "dir", ")", ";", "if", "(", "!", "is_dir", "(", "$", "dir", ")", ")", "{", "$", "this", "->", "log", "->", "addDebug"...
Set the temporary download directory. @param string $dir @return bool
[ "Set", "the", "temporary", "download", "directory", "." ]
train
https://github.com/VisualAppeal/PHP-Auto-Update/blob/fd0a2253385cc1880f713edc758bf142b0f10766/src/AutoUpdate.php#L221-L238
VisualAppeal/PHP-Auto-Update
src/AutoUpdate.php
AutoUpdate.setInstallDir
public function setInstallDir($dir) { $dir = $this->addTrailingSlash($dir); if (!is_dir($dir)) { $this->log->addDebug(sprintf('Creating new install directory "%s"', $dir)); if (!mkdir($dir, 0755, true)) { $this->log->addCritical(sprintf('Could not create install directory "%s"', $dir)); return false; } } $this->installDir = $dir; return true; }
php
public function setInstallDir($dir) { $dir = $this->addTrailingSlash($dir); if (!is_dir($dir)) { $this->log->addDebug(sprintf('Creating new install directory "%s"', $dir)); if (!mkdir($dir, 0755, true)) { $this->log->addCritical(sprintf('Could not create install directory "%s"', $dir)); return false; } } $this->installDir = $dir; return true; }
[ "public", "function", "setInstallDir", "(", "$", "dir", ")", "{", "$", "dir", "=", "$", "this", "->", "addTrailingSlash", "(", "$", "dir", ")", ";", "if", "(", "!", "is_dir", "(", "$", "dir", ")", ")", "{", "$", "this", "->", "log", "->", "addDeb...
Set the install directory. @param string $dir @return bool
[ "Set", "the", "install", "directory", "." ]
train
https://github.com/VisualAppeal/PHP-Auto-Update/blob/fd0a2253385cc1880f713edc758bf142b0f10766/src/AutoUpdate.php#L246-L263
VisualAppeal/PHP-Auto-Update
src/AutoUpdate.php
AutoUpdate.setCache
public function setCache($adapter, $ttl = 3600) { $adapter->setOption('ttl', $ttl); $this->cache = new Cache($adapter); return $this; }
php
public function setCache($adapter, $ttl = 3600) { $adapter->setOption('ttl', $ttl); $this->cache = new Cache($adapter); return $this; }
[ "public", "function", "setCache", "(", "$", "adapter", ",", "$", "ttl", "=", "3600", ")", "{", "$", "adapter", "->", "setOption", "(", "'ttl'", ",", "$", "ttl", ")", ";", "$", "this", "->", "cache", "=", "new", "Cache", "(", "$", "adapter", ")", ...
Set the cache component. @param \Desarrolla2\Cache\Adapter\AdapterInterface $adapter See https://github.com/desarrolla2/Cache @param int $ttl Time to live in seconds @return $this
[ "Set", "the", "cache", "component", "." ]
train
https://github.com/VisualAppeal/PHP-Auto-Update/blob/fd0a2253385cc1880f713edc758bf142b0f10766/src/AutoUpdate.php#L311-L317
VisualAppeal/PHP-Auto-Update
src/AutoUpdate.php
AutoUpdate.setBasicAuth
public function setBasicAuth($username, $password) { $this->username = $username; $this->password = $password; return $this; }
php
public function setBasicAuth($username, $password) { $this->username = $username; $this->password = $password; return $this; }
[ "public", "function", "setBasicAuth", "(", "$", "username", ",", "$", "password", ")", "{", "$", "this", "->", "username", "=", "$", "username", ";", "$", "this", "->", "password", "=", "$", "password", ";", "return", "$", "this", ";", "}" ]
Set username and password for basic authentication. @param string $username @param string $password @return $this
[ "Set", "username", "and", "password", "for", "basic", "authentication", "." ]
train
https://github.com/VisualAppeal/PHP-Auto-Update/blob/fd0a2253385cc1880f713edc758bf142b0f10766/src/AutoUpdate.php#L339-L345
VisualAppeal/PHP-Auto-Update
src/AutoUpdate.php
AutoUpdate.addLogHandler
public function addLogHandler(\Monolog\Handler\HandlerInterface $handler) { $this->log->pushHandler($handler); return $this; }
php
public function addLogHandler(\Monolog\Handler\HandlerInterface $handler) { $this->log->pushHandler($handler); return $this; }
[ "public", "function", "addLogHandler", "(", "\\", "Monolog", "\\", "Handler", "\\", "HandlerInterface", "$", "handler", ")", "{", "$", "this", "->", "log", "->", "pushHandler", "(", "$", "handler", ")", ";", "return", "$", "this", ";", "}" ]
Add a new logging handler. @param \Monolog\Handler\HandlerInterface $handler See https://github.com/Seldaek/monolog @return $this
[ "Add", "a", "new", "logging", "handler", "." ]
train
https://github.com/VisualAppeal/PHP-Auto-Update/blob/fd0a2253385cc1880f713edc758bf142b0f10766/src/AutoUpdate.php#L371-L376
VisualAppeal/PHP-Auto-Update
src/AutoUpdate.php
AutoUpdate.checkUpdate
public function checkUpdate() { $this->log->addNotice('Checking for a new update...'); // Reset previous updates $this->latestVersion = '0.0.0'; $this->updates = []; $versions = $this->cache->get('update-versions'); // Create absolute url to update file $updateFile = $this->updateUrl . '/' . $this->updateFile; if (!empty($this->branch)) { $updateFile .= '.' . $this->branch; } // Check if cache is empty if ($versions === null || $versions === false) { $this->log->addDebug(sprintf('Get new updates from %s', $updateFile)); // Read update file from update server if (function_exists('curl_version') && $this->_isValidUrl($updateFile)) { $update = $this->_downloadCurl($updateFile); if ($update === false) { $this->log->addError(sprintf('Could not download update file "%s" via curl!', $updateFile)); throw new DownloadException($updateFile); } } else { // TODO: Throw exception on error $update = @file_get_contents($updateFile, false, $this->_useBasicAuth()); if ($update === false) { $this->log->addError(sprintf('Could not download update file "%s" via file_get_contents!', $updateFile)); throw new DownloadException($updateFile); } } // Parse update file $updateFileExtension = substr(strrchr($this->updateFile, '.'), 1); switch ($updateFileExtension) { case 'ini': $versions = parse_ini_string($update, true); if (!is_array($versions)) { $this->log->addError('Unable to parse ini update file!'); throw new ParserException; } $versions = array_map(function ($block) { return isset($block['url']) ? $block['url'] : false; }, $versions); break; case 'json': $versions = (array)json_decode($update); if (!is_array($versions)) { $this->log->addError('Unable to parse json update file!'); throw new ParserException; } break; default: $this->log->addError(sprintf('Unknown file extension "%s"', $updateFileExtension)); throw new ParserException; } $this->cache->set('update-versions', $versions); } else { $this->log->addDebug('Got updates from cache'); } if (!is_array($versions)) { $this->log->addError(sprintf('Could not read versions from server %s', $updateFile)); return false; } // Check for latest version foreach ($versions as $version => $updateUrl) { if (Comparator::greaterThan($version, $this->currentVersion)) { if (Comparator::greaterThan($version, $this->latestVersion)) { $this->latestVersion = $version; } $this->updates[] = [ 'version' => $version, 'url' => $updateUrl, ]; } } // Sort versions to install usort($this->updates, function ($a, $b) { if (Comparator::equalTo($a['version'], $b['version'])) { return 0; } return Comparator::lessThan($a['version'], $b['version']) ? -1 : 1; }); if ($this->newVersionAvailable()) { $this->log->addDebug(sprintf('New version "%s" available', $this->latestVersion)); return true; } else { $this->log->addDebug('No new version available'); return self::NO_UPDATE_AVAILABLE; } }
php
public function checkUpdate() { $this->log->addNotice('Checking for a new update...'); // Reset previous updates $this->latestVersion = '0.0.0'; $this->updates = []; $versions = $this->cache->get('update-versions'); // Create absolute url to update file $updateFile = $this->updateUrl . '/' . $this->updateFile; if (!empty($this->branch)) { $updateFile .= '.' . $this->branch; } // Check if cache is empty if ($versions === null || $versions === false) { $this->log->addDebug(sprintf('Get new updates from %s', $updateFile)); // Read update file from update server if (function_exists('curl_version') && $this->_isValidUrl($updateFile)) { $update = $this->_downloadCurl($updateFile); if ($update === false) { $this->log->addError(sprintf('Could not download update file "%s" via curl!', $updateFile)); throw new DownloadException($updateFile); } } else { // TODO: Throw exception on error $update = @file_get_contents($updateFile, false, $this->_useBasicAuth()); if ($update === false) { $this->log->addError(sprintf('Could not download update file "%s" via file_get_contents!', $updateFile)); throw new DownloadException($updateFile); } } // Parse update file $updateFileExtension = substr(strrchr($this->updateFile, '.'), 1); switch ($updateFileExtension) { case 'ini': $versions = parse_ini_string($update, true); if (!is_array($versions)) { $this->log->addError('Unable to parse ini update file!'); throw new ParserException; } $versions = array_map(function ($block) { return isset($block['url']) ? $block['url'] : false; }, $versions); break; case 'json': $versions = (array)json_decode($update); if (!is_array($versions)) { $this->log->addError('Unable to parse json update file!'); throw new ParserException; } break; default: $this->log->addError(sprintf('Unknown file extension "%s"', $updateFileExtension)); throw new ParserException; } $this->cache->set('update-versions', $versions); } else { $this->log->addDebug('Got updates from cache'); } if (!is_array($versions)) { $this->log->addError(sprintf('Could not read versions from server %s', $updateFile)); return false; } // Check for latest version foreach ($versions as $version => $updateUrl) { if (Comparator::greaterThan($version, $this->currentVersion)) { if (Comparator::greaterThan($version, $this->latestVersion)) { $this->latestVersion = $version; } $this->updates[] = [ 'version' => $version, 'url' => $updateUrl, ]; } } // Sort versions to install usort($this->updates, function ($a, $b) { if (Comparator::equalTo($a['version'], $b['version'])) { return 0; } return Comparator::lessThan($a['version'], $b['version']) ? -1 : 1; }); if ($this->newVersionAvailable()) { $this->log->addDebug(sprintf('New version "%s" available', $this->latestVersion)); return true; } else { $this->log->addDebug('No new version available'); return self::NO_UPDATE_AVAILABLE; } }
[ "public", "function", "checkUpdate", "(", ")", "{", "$", "this", "->", "log", "->", "addNotice", "(", "'Checking for a new update...'", ")", ";", "// Reset previous updates", "$", "this", "->", "latestVersion", "=", "'0.0.0'", ";", "$", "this", "->", "updates", ...
Check for a new version @return int|bool true: New version is available false: Error while checking for update int: Status code (i.e. AutoUpdate::NO_UPDATE_AVAILABLE) @throws DownloadException @throws ParserException
[ "Check", "for", "a", "new", "version" ]
train
https://github.com/VisualAppeal/PHP-Auto-Update/blob/fd0a2253385cc1880f713edc758bf142b0f10766/src/AutoUpdate.php#L442-L556
VisualAppeal/PHP-Auto-Update
src/AutoUpdate.php
AutoUpdate._downloadCurl
protected function _downloadCurl($url) { $curl = curl_init(); curl_setopt($curl, CURLOPT_URL, $url); curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); if ($this->sslVerifyHost) { curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 2); } else { curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0); } curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, $this->sslVerifyHost); $update = curl_exec($curl); $error = false; if (curl_error($curl)) { $error = true; $this->log->addError(sprintf( 'Could not download update "%s" via curl: %s!', $url, curl_error($curl) )); } curl_close($curl); if ($error === true) { return false; } return $update; }
php
protected function _downloadCurl($url) { $curl = curl_init(); curl_setopt($curl, CURLOPT_URL, $url); curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); if ($this->sslVerifyHost) { curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 2); } else { curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0); } curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, $this->sslVerifyHost); $update = curl_exec($curl); $error = false; if (curl_error($curl)) { $error = true; $this->log->addError(sprintf( 'Could not download update "%s" via curl: %s!', $url, curl_error($curl) )); } curl_close($curl); if ($error === true) { return false; } return $update; }
[ "protected", "function", "_downloadCurl", "(", "$", "url", ")", "{", "$", "curl", "=", "curl_init", "(", ")", ";", "curl_setopt", "(", "$", "curl", ",", "CURLOPT_URL", ",", "$", "url", ")", ";", "curl_setopt", "(", "$", "curl", ",", "CURLOPT_RETURNTRANSF...
Download file via curl. @param string $url URL to file @return string|false
[ "Download", "file", "via", "curl", "." ]
train
https://github.com/VisualAppeal/PHP-Auto-Update/blob/fd0a2253385cc1880f713edc758bf142b0f10766/src/AutoUpdate.php#L585-L614
VisualAppeal/PHP-Auto-Update
src/AutoUpdate.php
AutoUpdate._downloadUpdate
protected function _downloadUpdate($updateUrl, $updateFile) { $this->log->addInfo(sprintf('Downloading update "%s" to "%s"', $updateUrl, $updateFile)); if (function_exists('curl_version') && $this->_isValidUrl($updateUrl)) { $update = $this->_downloadCurl($updateUrl); if ($update === false) { return false; } } elseif (ini_get('allow_url_fopen')) { // TODO: Throw exception on error $update = @file_get_contents($updateUrl, false, $this->_useBasicAuth()); if ($update === false) { $this->log->addError(sprintf('Could not download update "%s"!', $updateUrl)); throw new DownloadException($updateUrl); } } else { throw new \Exception('No valid download method found!'); } $handle = fopen($updateFile, 'w'); if (!$handle) { $this->log->addError(sprintf('Could not open file handle to save update to "%s"!', $updateFile)); return false; } if (!fwrite($handle, $update)) { $this->log->addError(sprintf('Could not write update to file "%s"!', $updateFile)); fclose($handle); return false; } fclose($handle); return true; }
php
protected function _downloadUpdate($updateUrl, $updateFile) { $this->log->addInfo(sprintf('Downloading update "%s" to "%s"', $updateUrl, $updateFile)); if (function_exists('curl_version') && $this->_isValidUrl($updateUrl)) { $update = $this->_downloadCurl($updateUrl); if ($update === false) { return false; } } elseif (ini_get('allow_url_fopen')) { // TODO: Throw exception on error $update = @file_get_contents($updateUrl, false, $this->_useBasicAuth()); if ($update === false) { $this->log->addError(sprintf('Could not download update "%s"!', $updateUrl)); throw new DownloadException($updateUrl); } } else { throw new \Exception('No valid download method found!'); } $handle = fopen($updateFile, 'w'); if (!$handle) { $this->log->addError(sprintf('Could not open file handle to save update to "%s"!', $updateFile)); return false; } if (!fwrite($handle, $update)) { $this->log->addError(sprintf('Could not write update to file "%s"!', $updateFile)); fclose($handle); return false; } fclose($handle); return true; }
[ "protected", "function", "_downloadUpdate", "(", "$", "updateUrl", ",", "$", "updateFile", ")", "{", "$", "this", "->", "log", "->", "addInfo", "(", "sprintf", "(", "'Downloading update \"%s\" to \"%s\"'", ",", "$", "updateUrl", ",", "$", "updateFile", ")", ")...
Download the update @param string $updateUrl Url where to download from @param string $updateFile Path where to save the download @return bool @throws DownloadException @throws \Exception
[ "Download", "the", "update" ]
train
https://github.com/VisualAppeal/PHP-Auto-Update/blob/fd0a2253385cc1880f713edc758bf142b0f10766/src/AutoUpdate.php#L625-L663
VisualAppeal/PHP-Auto-Update
src/AutoUpdate.php
AutoUpdate._simulateInstall
protected function _simulateInstall($updateFile) { $this->log->addNotice('[SIMULATE] Install new version'); clearstatcache(); // Check if zip file could be opened $zip = zip_open($updateFile); if (!is_resource($zip)) { $this->log->addError(sprintf('Could not open zip file "%s", error: %d', $updateFile, $zip)); return false; } $i = -1; $files = []; $simulateSuccess = true; while ($file = zip_read($zip)) { $i++; $filename = zip_entry_name($file); $foldername = $this->installDir . dirname($filename); $absoluteFilename = $this->installDir . $filename; $files[$i] = [ 'filename' => $filename, 'foldername' => $foldername, 'absolute_filename' => $absoluteFilename, ]; $this->log->addDebug(sprintf('[SIMULATE] Updating file "%s"', $filename)); // Check if parent directory is writable if (!is_dir($foldername)) { mkdir($foldername); $this->log->addDebug(sprintf('[SIMULATE] Create directory "%s"', $foldername)); $files[$i]['parent_folder_exists'] = false; $parent = dirname($foldername); if (!is_writable($parent)) { $files[$i]['parent_folder_writable'] = false; $simulateSuccess = false; $this->log->addWarning(sprintf('[SIMULATE] Directory "%s" has to be writeable!', $parent)); } else { $files[$i]['parent_folder_writable'] = true; } } // Skip if entry is a directory if (substr($filename, -1, 1) == DIRECTORY_SEPARATOR) { continue; } // Read file contents from archive $contents = zip_entry_read($file, zip_entry_filesize($file)); if ($contents === false) { $files[$i]['extractable'] = false; $simulateSuccess = false; $this->log->addWarning(sprintf('[SIMULATE] Coud not read contents of file "%s" from zip file!', $filename)); } // Write to file if (file_exists($absoluteFilename)) { $files[$i]['file_exists'] = true; if (!is_writable($absoluteFilename)) { $files[$i]['file_writable'] = false; $simulateSuccess = false; $this->log->addWarning(sprintf('[SIMULATE] Could not overwrite "%s"!', $absoluteFilename)); } } else { $files[$i]['file_exists'] = false; if (is_dir($foldername)) { if (!is_writable($foldername)) { $files[$i]['file_writable'] = false; $simulateSuccess = false; $this->log->addWarning(sprintf('[SIMULATE] The file "%s" could not be created!', $absoluteFilename)); } else { $files[$i]['file_writable'] = true; } } else { $files[$i]['file_writable'] = true; $this->log->addDebug(sprintf('[SIMULATE] The file "%s" could be created', $absoluteFilename)); } } if ($filename == $this->updateScriptName) { $this->log->addDebug(sprintf('[SIMULATE] Update script "%s" found', $absoluteFilename)); $files[$i]['update_script'] = true; } else { $files[$i]['update_script'] = false; } } $this->simulationResults = $files; return $simulateSuccess; }
php
protected function _simulateInstall($updateFile) { $this->log->addNotice('[SIMULATE] Install new version'); clearstatcache(); // Check if zip file could be opened $zip = zip_open($updateFile); if (!is_resource($zip)) { $this->log->addError(sprintf('Could not open zip file "%s", error: %d', $updateFile, $zip)); return false; } $i = -1; $files = []; $simulateSuccess = true; while ($file = zip_read($zip)) { $i++; $filename = zip_entry_name($file); $foldername = $this->installDir . dirname($filename); $absoluteFilename = $this->installDir . $filename; $files[$i] = [ 'filename' => $filename, 'foldername' => $foldername, 'absolute_filename' => $absoluteFilename, ]; $this->log->addDebug(sprintf('[SIMULATE] Updating file "%s"', $filename)); // Check if parent directory is writable if (!is_dir($foldername)) { mkdir($foldername); $this->log->addDebug(sprintf('[SIMULATE] Create directory "%s"', $foldername)); $files[$i]['parent_folder_exists'] = false; $parent = dirname($foldername); if (!is_writable($parent)) { $files[$i]['parent_folder_writable'] = false; $simulateSuccess = false; $this->log->addWarning(sprintf('[SIMULATE] Directory "%s" has to be writeable!', $parent)); } else { $files[$i]['parent_folder_writable'] = true; } } // Skip if entry is a directory if (substr($filename, -1, 1) == DIRECTORY_SEPARATOR) { continue; } // Read file contents from archive $contents = zip_entry_read($file, zip_entry_filesize($file)); if ($contents === false) { $files[$i]['extractable'] = false; $simulateSuccess = false; $this->log->addWarning(sprintf('[SIMULATE] Coud not read contents of file "%s" from zip file!', $filename)); } // Write to file if (file_exists($absoluteFilename)) { $files[$i]['file_exists'] = true; if (!is_writable($absoluteFilename)) { $files[$i]['file_writable'] = false; $simulateSuccess = false; $this->log->addWarning(sprintf('[SIMULATE] Could not overwrite "%s"!', $absoluteFilename)); } } else { $files[$i]['file_exists'] = false; if (is_dir($foldername)) { if (!is_writable($foldername)) { $files[$i]['file_writable'] = false; $simulateSuccess = false; $this->log->addWarning(sprintf('[SIMULATE] The file "%s" could not be created!', $absoluteFilename)); } else { $files[$i]['file_writable'] = true; } } else { $files[$i]['file_writable'] = true; $this->log->addDebug(sprintf('[SIMULATE] The file "%s" could be created', $absoluteFilename)); } } if ($filename == $this->updateScriptName) { $this->log->addDebug(sprintf('[SIMULATE] Update script "%s" found', $absoluteFilename)); $files[$i]['update_script'] = true; } else { $files[$i]['update_script'] = false; } } $this->simulationResults = $files; return $simulateSuccess; }
[ "protected", "function", "_simulateInstall", "(", "$", "updateFile", ")", "{", "$", "this", "->", "log", "->", "addNotice", "(", "'[SIMULATE] Install new version'", ")", ";", "clearstatcache", "(", ")", ";", "// Check if zip file could be opened", "$", "zip", "=", ...
Simulate update process. @param string $updateFile @return bool
[ "Simulate", "update", "process", "." ]
train
https://github.com/VisualAppeal/PHP-Auto-Update/blob/fd0a2253385cc1880f713edc758bf142b0f10766/src/AutoUpdate.php#L671-L773
VisualAppeal/PHP-Auto-Update
src/AutoUpdate.php
AutoUpdate._install
protected function _install($updateFile, $simulateInstall, $version) { $this->log->addNotice(sprintf('Trying to install update "%s"', $updateFile)); // Check if install should be simulated if ($simulateInstall) { if ($this->_simulateInstall($updateFile)) { $this->log->addNotice(sprintf('Simulation of update "%s" process succeeded', $version)); return true; } $this->log->addCritical(sprintf('Simulation of update "%s" process failed!', $version)); return self::ERROR_SIMULATE; } clearstatcache(); // Install only if simulateInstall === false // Check if zip file could be opened $zip = zip_open($updateFile); if (!is_resource($zip)) { $this->log->addError(sprintf('Could not open zip file "%s", error: %d', $updateFile, $zip)); return false; } // Read every file from archive while ($file = zip_read($zip)) { $filename = str_replace(array('/', '\\'), DIRECTORY_SEPARATOR, zip_entry_name($file)); $foldername = str_replace(array('/', '\\'), DIRECTORY_SEPARATOR, $this->installDir . dirname($filename)); $absoluteFilename = str_replace(array('/', '\\'), DIRECTORY_SEPARATOR, $this->installDir . $filename); $this->log->addDebug(sprintf('Updating file "%s"', $filename)); if (!is_dir($foldername)) { if (!mkdir($foldername, $this->dirPermissions, true)) { $this->log->addError(sprintf('Directory "%s" has to be writeable!', $foldername)); return false; } } // Skip if entry is a directory if (substr($filename, -1, 1) == DIRECTORY_SEPARATOR) { continue; } // Read file contents from archive $contents = zip_entry_read($file, zip_entry_filesize($file)); if ($contents === false) { $this->log->addError(sprintf('Coud not read zip entry "%s"', $file)); continue; } // Write to file if (file_exists($absoluteFilename)) { if (!is_writable($absoluteFilename)) { $this->log->addError(sprintf('Could not overwrite "%s"!', $absoluteFilename)); zip_close($zip); return false; } } else { // touch will fail if PHP is not the owner of the file, and file_put_contents is faster than touch. if (file_put_contents($absoluteFilename, '') === false) { $this->log->addError(sprintf('The file "%s" could not be created!', $absoluteFilename)); zip_close($zip); return false; } $this->log->addDebug(sprintf('File "%s" created', $absoluteFilename)); } $updateHandle = fopen($absoluteFilename, 'w'); if (!$updateHandle) { $this->log->addError(sprintf('Could not open file "%s"!', $absoluteFilename)); zip_close($zip); return false; } if (false === fwrite($updateHandle, $contents)) { $this->log->addError(sprintf('Could not write to file "%s"!', $absoluteFilename)); zip_close($zip); return false; } fclose($updateHandle); //If file is a update script, include if ($filename == $this->updateScriptName) { $this->log->addDebug(sprintf('Try to include update script "%s"', $absoluteFilename)); require($absoluteFilename); $this->log->addInfo(sprintf('Update script "%s" included!', $absoluteFilename)); if (!unlink($absoluteFilename)) { $this->log->addWarning(sprintf('Could not delete update script "%s"!', $absoluteFilename)); } } } zip_close($zip); $this->log->addNotice(sprintf('Update "%s" successfully installed', $version)); return true; }
php
protected function _install($updateFile, $simulateInstall, $version) { $this->log->addNotice(sprintf('Trying to install update "%s"', $updateFile)); // Check if install should be simulated if ($simulateInstall) { if ($this->_simulateInstall($updateFile)) { $this->log->addNotice(sprintf('Simulation of update "%s" process succeeded', $version)); return true; } $this->log->addCritical(sprintf('Simulation of update "%s" process failed!', $version)); return self::ERROR_SIMULATE; } clearstatcache(); // Install only if simulateInstall === false // Check if zip file could be opened $zip = zip_open($updateFile); if (!is_resource($zip)) { $this->log->addError(sprintf('Could not open zip file "%s", error: %d', $updateFile, $zip)); return false; } // Read every file from archive while ($file = zip_read($zip)) { $filename = str_replace(array('/', '\\'), DIRECTORY_SEPARATOR, zip_entry_name($file)); $foldername = str_replace(array('/', '\\'), DIRECTORY_SEPARATOR, $this->installDir . dirname($filename)); $absoluteFilename = str_replace(array('/', '\\'), DIRECTORY_SEPARATOR, $this->installDir . $filename); $this->log->addDebug(sprintf('Updating file "%s"', $filename)); if (!is_dir($foldername)) { if (!mkdir($foldername, $this->dirPermissions, true)) { $this->log->addError(sprintf('Directory "%s" has to be writeable!', $foldername)); return false; } } // Skip if entry is a directory if (substr($filename, -1, 1) == DIRECTORY_SEPARATOR) { continue; } // Read file contents from archive $contents = zip_entry_read($file, zip_entry_filesize($file)); if ($contents === false) { $this->log->addError(sprintf('Coud not read zip entry "%s"', $file)); continue; } // Write to file if (file_exists($absoluteFilename)) { if (!is_writable($absoluteFilename)) { $this->log->addError(sprintf('Could not overwrite "%s"!', $absoluteFilename)); zip_close($zip); return false; } } else { // touch will fail if PHP is not the owner of the file, and file_put_contents is faster than touch. if (file_put_contents($absoluteFilename, '') === false) { $this->log->addError(sprintf('The file "%s" could not be created!', $absoluteFilename)); zip_close($zip); return false; } $this->log->addDebug(sprintf('File "%s" created', $absoluteFilename)); } $updateHandle = fopen($absoluteFilename, 'w'); if (!$updateHandle) { $this->log->addError(sprintf('Could not open file "%s"!', $absoluteFilename)); zip_close($zip); return false; } if (false === fwrite($updateHandle, $contents)) { $this->log->addError(sprintf('Could not write to file "%s"!', $absoluteFilename)); zip_close($zip); return false; } fclose($updateHandle); //If file is a update script, include if ($filename == $this->updateScriptName) { $this->log->addDebug(sprintf('Try to include update script "%s"', $absoluteFilename)); require($absoluteFilename); $this->log->addInfo(sprintf('Update script "%s" included!', $absoluteFilename)); if (!unlink($absoluteFilename)) { $this->log->addWarning(sprintf('Could not delete update script "%s"!', $absoluteFilename)); } } } zip_close($zip); $this->log->addNotice(sprintf('Update "%s" successfully installed', $version)); return true; }
[ "protected", "function", "_install", "(", "$", "updateFile", ",", "$", "simulateInstall", ",", "$", "version", ")", "{", "$", "this", "->", "log", "->", "addNotice", "(", "sprintf", "(", "'Trying to install update \"%s\"'", ",", "$", "updateFile", ")", ")", ...
Install update. @param string $updateFile Path to the update file @param bool $simulateInstall Check for directory and file permissions instead of installing the update @param $version @return bool
[ "Install", "update", "." ]
train
https://github.com/VisualAppeal/PHP-Auto-Update/blob/fd0a2253385cc1880f713edc758bf142b0f10766/src/AutoUpdate.php#L783-L896
VisualAppeal/PHP-Auto-Update
src/AutoUpdate.php
AutoUpdate.update
public function update($simulateInstall = true, $deleteDownload = true) { $this->log->addInfo('Trying to perform update'); // Check for latest version if ($this->latestVersion === null || count($this->updates) === 0) { $this->checkUpdate(); } if ($this->latestVersion === null || count($this->updates) === 0) { $this->log->addError('Could not get latest version from server!'); return self::ERROR_VERSION_CHECK; } // Check if current version is up to date if (!$this->newVersionAvailable()) { $this->log->addWarning('No update available!'); return self::NO_UPDATE_AVAILABLE; } foreach ($this->updates as $update) { $this->log->addDebug(sprintf('Update to version "%s"', $update['version'])); // Check for temp directory if (empty($this->tempDir) || !is_dir($this->tempDir) || !is_writable($this->tempDir)) { $this->log->addCritical(sprintf('Temporary directory "%s" does not exist or is not writeable!', $this->tempDir)); return self::ERROR_TEMP_DIR; } // Check for install directory if (empty($this->installDir) || !is_dir($this->installDir) || !is_writable($this->installDir)) { $this->log->addCritical(sprintf('Install directory "%s" does not exist or is not writeable!', $this->installDir)); return self::ERROR_INSTALL_DIR; } $updateFile = $this->tempDir . $update['version'] . '.zip'; // Download update if (!is_file($updateFile)) { if (!$this->_downloadUpdate($update['url'], $updateFile)) { $this->log->addCritical(sprintf('Failed to download update from "%s" to "%s"!', $update['url'], $updateFile)); return self::ERROR_DOWNLOAD_UPDATE; } $this->log->addDebug(sprintf('Latest update downloaded to "%s"', $updateFile)); } else { $this->log->addInfo(sprintf('Latest update already downloaded to "%s"', $updateFile)); } // Install update $result = $this->_install($updateFile, $simulateInstall, $update['version']); if ($result === true) { $this->runOnEachUpdateFinishCallbacks($update['version']); if ($deleteDownload) { $this->log->addDebug(sprintf('Trying to delete update file "%s" after successfull update', $updateFile)); if (unlink($updateFile)) { $this->log->addInfo(sprintf('Update file "%s" deleted after successfull update', $updateFile)); } else { $this->log->addError(sprintf('Could not delete update file "%s" after successfull update!', $updateFile)); return self::ERROR_DELETE_TEMP_UPDATE; } } } else { if ($deleteDownload) { $this->log->addDebug(sprintf('Trying to delete update file "%s" after failed update', $updateFile)); if (unlink($updateFile)) { $this->log->addInfo(sprintf('Update file "%s" deleted after failed update', $updateFile)); } else { $this->log->addError(sprintf('Could not delete update file "%s" after failed update!', $updateFile)); } } return $result; } } $this->runOnAllUpdateFinishCallbacks($this->getVersionsToUpdate()); return true; }
php
public function update($simulateInstall = true, $deleteDownload = true) { $this->log->addInfo('Trying to perform update'); // Check for latest version if ($this->latestVersion === null || count($this->updates) === 0) { $this->checkUpdate(); } if ($this->latestVersion === null || count($this->updates) === 0) { $this->log->addError('Could not get latest version from server!'); return self::ERROR_VERSION_CHECK; } // Check if current version is up to date if (!$this->newVersionAvailable()) { $this->log->addWarning('No update available!'); return self::NO_UPDATE_AVAILABLE; } foreach ($this->updates as $update) { $this->log->addDebug(sprintf('Update to version "%s"', $update['version'])); // Check for temp directory if (empty($this->tempDir) || !is_dir($this->tempDir) || !is_writable($this->tempDir)) { $this->log->addCritical(sprintf('Temporary directory "%s" does not exist or is not writeable!', $this->tempDir)); return self::ERROR_TEMP_DIR; } // Check for install directory if (empty($this->installDir) || !is_dir($this->installDir) || !is_writable($this->installDir)) { $this->log->addCritical(sprintf('Install directory "%s" does not exist or is not writeable!', $this->installDir)); return self::ERROR_INSTALL_DIR; } $updateFile = $this->tempDir . $update['version'] . '.zip'; // Download update if (!is_file($updateFile)) { if (!$this->_downloadUpdate($update['url'], $updateFile)) { $this->log->addCritical(sprintf('Failed to download update from "%s" to "%s"!', $update['url'], $updateFile)); return self::ERROR_DOWNLOAD_UPDATE; } $this->log->addDebug(sprintf('Latest update downloaded to "%s"', $updateFile)); } else { $this->log->addInfo(sprintf('Latest update already downloaded to "%s"', $updateFile)); } // Install update $result = $this->_install($updateFile, $simulateInstall, $update['version']); if ($result === true) { $this->runOnEachUpdateFinishCallbacks($update['version']); if ($deleteDownload) { $this->log->addDebug(sprintf('Trying to delete update file "%s" after successfull update', $updateFile)); if (unlink($updateFile)) { $this->log->addInfo(sprintf('Update file "%s" deleted after successfull update', $updateFile)); } else { $this->log->addError(sprintf('Could not delete update file "%s" after successfull update!', $updateFile)); return self::ERROR_DELETE_TEMP_UPDATE; } } } else { if ($deleteDownload) { $this->log->addDebug(sprintf('Trying to delete update file "%s" after failed update', $updateFile)); if (unlink($updateFile)) { $this->log->addInfo(sprintf('Update file "%s" deleted after failed update', $updateFile)); } else { $this->log->addError(sprintf('Could not delete update file "%s" after failed update!', $updateFile)); } } return $result; } } $this->runOnAllUpdateFinishCallbacks($this->getVersionsToUpdate()); return true; }
[ "public", "function", "update", "(", "$", "simulateInstall", "=", "true", ",", "$", "deleteDownload", "=", "true", ")", "{", "$", "this", "->", "log", "->", "addInfo", "(", "'Trying to perform update'", ")", ";", "// Check for latest version", "if", "(", "$", ...
Update to the latest version @param bool $simulateInstall Check for directory and file permissions before copying files (Default: true) @param bool $deleteDownload Delete download after update (Default: true) @return integer|bool @throws DownloadException @throws ParserException
[ "Update", "to", "the", "latest", "version" ]
train
https://github.com/VisualAppeal/PHP-Auto-Update/blob/fd0a2253385cc1880f713edc758bf142b0f10766/src/AutoUpdate.php#L908-L993
Wolfcast/BrowserDetection
lib/BrowserDetection.php
BrowserDetection.addCustomBrowserDetection
public function addCustomBrowserDetection($browserName, $uaNameToLookFor = '', $isMobile = false, $isRobot = false, $separator = '/', $uaNameFindWords = true) { if ($browserName == '') { return false; } if (array_key_exists($browserName, $this->_customBrowserDetection)) { unset($this->_customBrowserDetection[$browserName]); } if ($uaNameToLookFor == '') { $uaNameToLookFor = $browserName; } $this->_customBrowserDetection[$browserName] = array('uaNameToLookFor' => $uaNameToLookFor, 'isMobile' => $isMobile == true, 'isRobot' => $isRobot == true, 'separator' => $separator, 'uaNameFindWords' => $uaNameFindWords == true); return true; }
php
public function addCustomBrowserDetection($browserName, $uaNameToLookFor = '', $isMobile = false, $isRobot = false, $separator = '/', $uaNameFindWords = true) { if ($browserName == '') { return false; } if (array_key_exists($browserName, $this->_customBrowserDetection)) { unset($this->_customBrowserDetection[$browserName]); } if ($uaNameToLookFor == '') { $uaNameToLookFor = $browserName; } $this->_customBrowserDetection[$browserName] = array('uaNameToLookFor' => $uaNameToLookFor, 'isMobile' => $isMobile == true, 'isRobot' => $isRobot == true, 'separator' => $separator, 'uaNameFindWords' => $uaNameFindWords == true); return true; }
[ "public", "function", "addCustomBrowserDetection", "(", "$", "browserName", ",", "$", "uaNameToLookFor", "=", "''", ",", "$", "isMobile", "=", "false", ",", "$", "isRobot", "=", "false", ",", "$", "separator", "=", "'/'", ",", "$", "uaNameFindWords", "=", ...
Dynamically add support for a new Web browser. @param string $browserName The Web browser name (used for display). @param mixed $uaNameToLookFor (optional) The string (or array of strings) representing the browser name to find in the user agent. If omitted, $browserName will be used. @param boolean $isMobile (optional) Determines if the browser is from a mobile device. @param boolean $isRobot (optional) Determines if the browser is a robot or not. @param string $separator (optional) The separator string used to split the browser name and the version number in the user agent. @param boolean $uaNameFindWords (optional) Determines if the browser name to find should match a word instead of a part of a word. For example "Bar" would not be found in "FooBar" when true but would be found in "Foo Bar". When set to false, the browser name can be found anywhere in the user agent string. @see removeCustomBrowserDetection() @return boolean Returns true if the custom rule has been added, false otherwise.
[ "Dynamically", "add", "support", "for", "a", "new", "Web", "browser", "." ]
train
https://github.com/Wolfcast/BrowserDetection/blob/9350b2d69aa8dfd2d526000bc0fb52a0baf611d2/lib/BrowserDetection.php#L337-L351
Wolfcast/BrowserDetection
lib/BrowserDetection.php
BrowserDetection.addCustomPlatformDetection
public function addCustomPlatformDetection($platformName, $platformNameToLookFor = '', $isMobile = false) { if ($platformName == '') { return false; } if (array_key_exists($platformName, $this->_customPlatformDetection)) { unset($this->_customPlatformDetection[$platformName]); } if ($platformNameToLookFor == '') { $platformNameToLookFor = $platformName; } $this->_customPlatformDetection[$platformName] = array('platformNameToLookFor' => $platformNameToLookFor, 'isMobile' => $isMobile == true); return true; }
php
public function addCustomPlatformDetection($platformName, $platformNameToLookFor = '', $isMobile = false) { if ($platformName == '') { return false; } if (array_key_exists($platformName, $this->_customPlatformDetection)) { unset($this->_customPlatformDetection[$platformName]); } if ($platformNameToLookFor == '') { $platformNameToLookFor = $platformName; } $this->_customPlatformDetection[$platformName] = array('platformNameToLookFor' => $platformNameToLookFor, 'isMobile' => $isMobile == true); return true; }
[ "public", "function", "addCustomPlatformDetection", "(", "$", "platformName", ",", "$", "platformNameToLookFor", "=", "''", ",", "$", "isMobile", "=", "false", ")", "{", "if", "(", "$", "platformName", "==", "''", ")", "{", "return", "false", ";", "}", "if...
Dynamically add support for a new platform. @param string $platformName The platform name (used for display). @param mixed $platformNameToLookFor (optional) The string (or array of strings) representing the platform name to find in the user agent. If omitted, $platformName will be used. @param boolean $isMobile (optional) Determines if the platform is from a mobile device. @see removeCustomPlatformDetection() @return boolean Returns true if the custom rule has been added, false otherwise.
[ "Dynamically", "add", "support", "for", "a", "new", "platform", "." ]
train
https://github.com/Wolfcast/BrowserDetection/blob/9350b2d69aa8dfd2d526000bc0fb52a0baf611d2/lib/BrowserDetection.php#L362-L375
Wolfcast/BrowserDetection
lib/BrowserDetection.php
BrowserDetection.compareVersions
public function compareVersions($sourceVer, $compareVer) { $sourceVer = explode('.', $sourceVer); foreach ($sourceVer as $k => $v) { $sourceVer[$k] = $this->parseInt($v); } $compareVer = explode('.', $compareVer); foreach ($compareVer as $k => $v) { $compareVer[$k] = $this->parseInt($v); } if (count($sourceVer) != count($compareVer)) { if (count($sourceVer) > count($compareVer)) { for ($i = count($compareVer); $i < count($sourceVer); $i++) { $compareVer[$i] = 0; } } else { for ($i = count($sourceVer); $i < count($compareVer); $i++) { $sourceVer[$i] = 0; } } } foreach ($sourceVer as $i => $srcVerPart) { if ($srcVerPart > $compareVer[$i]) { return 1; } else { if ($srcVerPart < $compareVer[$i]) { return -1; } } } return 0; }
php
public function compareVersions($sourceVer, $compareVer) { $sourceVer = explode('.', $sourceVer); foreach ($sourceVer as $k => $v) { $sourceVer[$k] = $this->parseInt($v); } $compareVer = explode('.', $compareVer); foreach ($compareVer as $k => $v) { $compareVer[$k] = $this->parseInt($v); } if (count($sourceVer) != count($compareVer)) { if (count($sourceVer) > count($compareVer)) { for ($i = count($compareVer); $i < count($sourceVer); $i++) { $compareVer[$i] = 0; } } else { for ($i = count($sourceVer); $i < count($compareVer); $i++) { $sourceVer[$i] = 0; } } } foreach ($sourceVer as $i => $srcVerPart) { if ($srcVerPart > $compareVer[$i]) { return 1; } else { if ($srcVerPart < $compareVer[$i]) { return -1; } } } return 0; }
[ "public", "function", "compareVersions", "(", "$", "sourceVer", ",", "$", "compareVer", ")", "{", "$", "sourceVer", "=", "explode", "(", "'.'", ",", "$", "sourceVer", ")", ";", "foreach", "(", "$", "sourceVer", "as", "$", "k", "=>", "$", "v", ")", "{...
Compare two version number strings. @param string $sourceVer The source version number. @param string $compareVer The version number to compare with the source version number. @return int Returns -1 if $sourceVer < $compareVer, 0 if $sourceVer == $compareVer or 1 if $sourceVer > $compareVer.
[ "Compare", "two", "version", "number", "strings", "." ]
train
https://github.com/Wolfcast/BrowserDetection/blob/9350b2d69aa8dfd2d526000bc0fb52a0baf611d2/lib/BrowserDetection.php#L384-L419
Wolfcast/BrowserDetection
lib/BrowserDetection.php
BrowserDetection.getIECompatibilityView
public function getIECompatibilityView($asArray = false) { if ($asArray) { return array('browser' => $this->_compatibilityViewName, 'version' => $this->_compatibilityViewVer); } else { return trim($this->_compatibilityViewName . ' ' . $this->_compatibilityViewVer); } }
php
public function getIECompatibilityView($asArray = false) { if ($asArray) { return array('browser' => $this->_compatibilityViewName, 'version' => $this->_compatibilityViewVer); } else { return trim($this->_compatibilityViewName . ' ' . $this->_compatibilityViewVer); } }
[ "public", "function", "getIECompatibilityView", "(", "$", "asArray", "=", "false", ")", "{", "if", "(", "$", "asArray", ")", "{", "return", "array", "(", "'browser'", "=>", "$", "this", "->", "_compatibilityViewName", ",", "'version'", "=>", "$", "this", "...
Get the name and version of the browser emulated in the compatibility view mode (if any). Since Internet Explorer 8, IE can be put in compatibility mode to make websites that were created for older browsers, especially IE 6 and 7, look better in IE 8+ which renders web pages closer to the standards and thus differently from those older versions of IE. @param boolean $asArray (optional) Determines if the return value must be an array (true) or a string (false). @return mixed If a string was requested, the function returns the name and version of the browser emulated in the compatibility view mode or an empty string if the browser is not in compatibility view mode. If an array was requested, an array with the keys 'browser' and 'version' is returned.
[ "Get", "the", "name", "and", "version", "of", "the", "browser", "emulated", "in", "the", "compatibility", "view", "mode", "(", "if", "any", ")", ".", "Since", "Internet", "Explorer", "8", "IE", "can", "be", "put", "in", "compatibility", "mode", "to", "ma...
train
https://github.com/Wolfcast/BrowserDetection/blob/9350b2d69aa8dfd2d526000bc0fb52a0baf611d2/lib/BrowserDetection.php#L441-L448
Wolfcast/BrowserDetection
lib/BrowserDetection.php
BrowserDetection.getPlatformVersion
public function getPlatformVersion($returnVersionNumbers = false, $returnServerFlavor = false) { if ($this->_platformVersion == self::PLATFORM_VERSION_UNKNOWN || $this->_platformVersion == '') { return self::PLATFORM_VERSION_UNKNOWN; } if ($returnVersionNumbers) { return $this->_platformVersion; } else { switch ($this->getPlatform()) { case self::PLATFORM_WINDOWS: if (substr($this->_platformVersion, 0, 3) == 'NT ') { return $this->windowsNTVerToStr(substr($this->_platformVersion, 3), $returnServerFlavor); } else { return $this->windowsVerToStr($this->_platformVersion); } break; case self::PLATFORM_MACINTOSH: return $this->macVerToStr($this->_platformVersion); case self::PLATFORM_ANDROID: return $this->androidVerToStr($this->_platformVersion); case self::PLATFORM_IOS: return $this->iOSVerToStr($this->_platformVersion); default: return self::PLATFORM_VERSION_UNKNOWN; } } }
php
public function getPlatformVersion($returnVersionNumbers = false, $returnServerFlavor = false) { if ($this->_platformVersion == self::PLATFORM_VERSION_UNKNOWN || $this->_platformVersion == '') { return self::PLATFORM_VERSION_UNKNOWN; } if ($returnVersionNumbers) { return $this->_platformVersion; } else { switch ($this->getPlatform()) { case self::PLATFORM_WINDOWS: if (substr($this->_platformVersion, 0, 3) == 'NT ') { return $this->windowsNTVerToStr(substr($this->_platformVersion, 3), $returnServerFlavor); } else { return $this->windowsVerToStr($this->_platformVersion); } break; case self::PLATFORM_MACINTOSH: return $this->macVerToStr($this->_platformVersion); case self::PLATFORM_ANDROID: return $this->androidVerToStr($this->_platformVersion); case self::PLATFORM_IOS: return $this->iOSVerToStr($this->_platformVersion); default: return self::PLATFORM_VERSION_UNKNOWN; } } }
[ "public", "function", "getPlatformVersion", "(", "$", "returnVersionNumbers", "=", "false", ",", "$", "returnServerFlavor", "=", "false", ")", "{", "if", "(", "$", "this", "->", "_platformVersion", "==", "self", "::", "PLATFORM_VERSION_UNKNOWN", "||", "$", "this...
Get the platform version on which the browser is run on. It can be returned as a string number like 'NT 6.3' or as a name like 'Windows 8.1'. When returning version string numbers for Windows NT OS families the number is prefixed by 'NT ' to differentiate from older Windows 3.x & 9x release. At the moment only the Windows and Android operating systems are supported. @param boolean $returnVersionNumbers (optional) Determines if the return value must be versions numbers as a string (true) or the version name (false). @param boolean $returnServerFlavor (optional) Since some Windows NT versions have the same values, this flag determines if the Server flavor is returned or not. For instance Windows 8.1 and Windows Server 2012 R2 both use version 6.3. This parameter is only useful when testing for Windows. @return string Returns the version name/version numbers of the platform or the constant PLATFORM_VERSION_UNKNOWN if unknown.
[ "Get", "the", "platform", "version", "on", "which", "the", "browser", "is", "run", "on", ".", "It", "can", "be", "returned", "as", "a", "string", "number", "like", "NT", "6", ".", "3", "or", "as", "a", "name", "like", "Windows", "8", ".", "1", ".",...
train
https://github.com/Wolfcast/BrowserDetection/blob/9350b2d69aa8dfd2d526000bc0fb52a0baf611d2/lib/BrowserDetection.php#L483-L513
Wolfcast/BrowserDetection
lib/BrowserDetection.php
BrowserDetection.removeCustomBrowserDetection
public function removeCustomBrowserDetection($browserName) { if (array_key_exists($browserName, $this->_customBrowserDetection)) { unset($this->_customBrowserDetection[$browserName]); return true; } return false; }
php
public function removeCustomBrowserDetection($browserName) { if (array_key_exists($browserName, $this->_customBrowserDetection)) { unset($this->_customBrowserDetection[$browserName]); return true; } return false; }
[ "public", "function", "removeCustomBrowserDetection", "(", "$", "browserName", ")", "{", "if", "(", "array_key_exists", "(", "$", "browserName", ",", "$", "this", "->", "_customBrowserDetection", ")", ")", "{", "unset", "(", "$", "this", "->", "_customBrowserDet...
Remove support for a previously added Web browser. @param string $browserName The Web browser name as used when added. @see addCustomBrowserDetection() @return boolean Returns true if the custom rule has been found and removed, false otherwise.
[ "Remove", "support", "for", "a", "previously", "added", "Web", "browser", "." ]
train
https://github.com/Wolfcast/BrowserDetection/blob/9350b2d69aa8dfd2d526000bc0fb52a0baf611d2/lib/BrowserDetection.php#L588-L596
Wolfcast/BrowserDetection
lib/BrowserDetection.php
BrowserDetection.removeCustomPlatformDetection
public function removeCustomPlatformDetection($platformName) { if (array_key_exists($platformName, $this->_customPlatformDetection)) { unset($this->_customPlatformDetection[$platformName]); return true; } return false; }
php
public function removeCustomPlatformDetection($platformName) { if (array_key_exists($platformName, $this->_customPlatformDetection)) { unset($this->_customPlatformDetection[$platformName]); return true; } return false; }
[ "public", "function", "removeCustomPlatformDetection", "(", "$", "platformName", ")", "{", "if", "(", "array_key_exists", "(", "$", "platformName", ",", "$", "this", "->", "_customPlatformDetection", ")", ")", "{", "unset", "(", "$", "this", "->", "_customPlatfo...
Remove support for a previously added platform. @param string $platformName The platform name as used when added. @see addCustomPlatformDetection() @return boolean Returns true if the custom rule has been found and removed, false otherwise.
[ "Remove", "support", "for", "a", "previously", "added", "platform", "." ]
train
https://github.com/Wolfcast/BrowserDetection/blob/9350b2d69aa8dfd2d526000bc0fb52a0baf611d2/lib/BrowserDetection.php#L604-L612
Wolfcast/BrowserDetection
lib/BrowserDetection.php
BrowserDetection.setUserAgent
public function setUserAgent($agentString = '') { if (!is_string($agentString) || trim($agentString) == '') { //https://bugs.php.net/bug.php?id=49184 if (filter_has_var(INPUT_SERVER, 'HTTP_USER_AGENT')) { $agentString = filter_input(INPUT_SERVER, 'HTTP_USER_AGENT', FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_LOW); } else if (array_key_exists('HTTP_USER_AGENT', $_SERVER) && is_string($_SERVER['HTTP_USER_AGENT'])) { $agentString = filter_var($_SERVER['HTTP_USER_AGENT'], FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_LOW); } else { $agentString = ''; } if ($agentString === false || $agentString === NULL) { //filter_input or filter_var failed $agentString = ''; } } $this->reset(); $this->_agent = $agentString; $this->detect(); }
php
public function setUserAgent($agentString = '') { if (!is_string($agentString) || trim($agentString) == '') { //https://bugs.php.net/bug.php?id=49184 if (filter_has_var(INPUT_SERVER, 'HTTP_USER_AGENT')) { $agentString = filter_input(INPUT_SERVER, 'HTTP_USER_AGENT', FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_LOW); } else if (array_key_exists('HTTP_USER_AGENT', $_SERVER) && is_string($_SERVER['HTTP_USER_AGENT'])) { $agentString = filter_var($_SERVER['HTTP_USER_AGENT'], FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_LOW); } else { $agentString = ''; } if ($agentString === false || $agentString === NULL) { //filter_input or filter_var failed $agentString = ''; } } $this->reset(); $this->_agent = $agentString; $this->detect(); }
[ "public", "function", "setUserAgent", "(", "$", "agentString", "=", "''", ")", "{", "if", "(", "!", "is_string", "(", "$", "agentString", ")", "||", "trim", "(", "$", "agentString", ")", "==", "''", ")", "{", "//https://bugs.php.net/bug.php?id=49184", "if", ...
Set the user agent to use with the class. @param string $agentString (optional) The value of the user agent. If an empty string is sent (default), $_SERVER['HTTP_USER_AGENT'] will be used.
[ "Set", "the", "user", "agent", "to", "use", "with", "the", "class", "." ]
train
https://github.com/Wolfcast/BrowserDetection/blob/9350b2d69aa8dfd2d526000bc0fb52a0baf611d2/lib/BrowserDetection.php#L619-L640
Wolfcast/BrowserDetection
lib/BrowserDetection.php
BrowserDetection.androidVerToStr
protected function androidVerToStr($androidVer) { //https://en.wikipedia.org/wiki/Android_version_history if ($this->compareVersions($androidVer, '10') >= 0 && $this->compareVersions($androidVer, '11') < 0) { return 'Android Q'; //Still in beta will replace with final name when released } else if ($this->compareVersions($androidVer, '9') >= 0 && $this->compareVersions($androidVer, '10') < 0) { return 'Pie'; } else if ($this->compareVersions($androidVer, '8') >= 0 && $this->compareVersions($androidVer, '9') < 0) { return 'Oreo'; } else if ($this->compareVersions($androidVer, '7') >= 0 && $this->compareVersions($androidVer, '8') < 0) { return 'Nougat'; } else if ($this->compareVersions($androidVer, '6') >= 0 && $this->compareVersions($androidVer, '7') < 0) { return 'Marshmallow'; } else if ($this->compareVersions($androidVer, '5') >= 0 && $this->compareVersions($androidVer, '5.2') < 0) { return 'Lollipop'; } else if ($this->compareVersions($androidVer, '4.4') >= 0 && $this->compareVersions($androidVer, '4.5') < 0) { return 'KitKat'; } else if ($this->compareVersions($androidVer, '4.1') >= 0 && $this->compareVersions($androidVer, '4.4') < 0) { return 'Jelly Bean'; } else if ($this->compareVersions($androidVer, '4') >= 0 && $this->compareVersions($androidVer, '4.1') < 0) { return 'Ice Cream Sandwich'; } else if ($this->compareVersions($androidVer, '3') >= 0 && $this->compareVersions($androidVer, '3.3') < 0) { return 'Honeycomb'; } else if ($this->compareVersions($androidVer, '2.3') >= 0 && $this->compareVersions($androidVer, '2.4') < 0) { return 'Gingerbread'; } else if ($this->compareVersions($androidVer, '2.2') >= 0 && $this->compareVersions($androidVer, '2.3') < 0) { return 'Froyo'; } else if ($this->compareVersions($androidVer, '2') >= 0 && $this->compareVersions($androidVer, '2.2') < 0) { return 'Eclair'; } else if ($this->compareVersions($androidVer, '1.6') == 0) { return 'Donut'; } else if ($this->compareVersions($androidVer, '1.5') == 0) { return 'Cupcake'; } else { return self::PLATFORM_VERSION_UNKNOWN; //Unknown/unnamed Android version } }
php
protected function androidVerToStr($androidVer) { //https://en.wikipedia.org/wiki/Android_version_history if ($this->compareVersions($androidVer, '10') >= 0 && $this->compareVersions($androidVer, '11') < 0) { return 'Android Q'; //Still in beta will replace with final name when released } else if ($this->compareVersions($androidVer, '9') >= 0 && $this->compareVersions($androidVer, '10') < 0) { return 'Pie'; } else if ($this->compareVersions($androidVer, '8') >= 0 && $this->compareVersions($androidVer, '9') < 0) { return 'Oreo'; } else if ($this->compareVersions($androidVer, '7') >= 0 && $this->compareVersions($androidVer, '8') < 0) { return 'Nougat'; } else if ($this->compareVersions($androidVer, '6') >= 0 && $this->compareVersions($androidVer, '7') < 0) { return 'Marshmallow'; } else if ($this->compareVersions($androidVer, '5') >= 0 && $this->compareVersions($androidVer, '5.2') < 0) { return 'Lollipop'; } else if ($this->compareVersions($androidVer, '4.4') >= 0 && $this->compareVersions($androidVer, '4.5') < 0) { return 'KitKat'; } else if ($this->compareVersions($androidVer, '4.1') >= 0 && $this->compareVersions($androidVer, '4.4') < 0) { return 'Jelly Bean'; } else if ($this->compareVersions($androidVer, '4') >= 0 && $this->compareVersions($androidVer, '4.1') < 0) { return 'Ice Cream Sandwich'; } else if ($this->compareVersions($androidVer, '3') >= 0 && $this->compareVersions($androidVer, '3.3') < 0) { return 'Honeycomb'; } else if ($this->compareVersions($androidVer, '2.3') >= 0 && $this->compareVersions($androidVer, '2.4') < 0) { return 'Gingerbread'; } else if ($this->compareVersions($androidVer, '2.2') >= 0 && $this->compareVersions($androidVer, '2.3') < 0) { return 'Froyo'; } else if ($this->compareVersions($androidVer, '2') >= 0 && $this->compareVersions($androidVer, '2.2') < 0) { return 'Eclair'; } else if ($this->compareVersions($androidVer, '1.6') == 0) { return 'Donut'; } else if ($this->compareVersions($androidVer, '1.5') == 0) { return 'Cupcake'; } else { return self::PLATFORM_VERSION_UNKNOWN; //Unknown/unnamed Android version } }
[ "protected", "function", "androidVerToStr", "(", "$", "androidVer", ")", "{", "//https://en.wikipedia.org/wiki/Android_version_history", "if", "(", "$", "this", "->", "compareVersions", "(", "$", "androidVer", ",", "'10'", ")", ">=", "0", "&&", "$", "this", "->", ...
Convert the Android version numbers to the operating system name. For instance '1.6' returns 'Donut'. @access protected @param string $androidVer The Android version numbers as a string. @return string The operating system name or the constant PLATFORM_VERSION_UNKNOWN if nothing match the version numbers.
[ "Convert", "the", "Android", "version", "numbers", "to", "the", "operating", "system", "name", ".", "For", "instance", "1", ".", "6", "returns", "Donut", "." ]
train
https://github.com/Wolfcast/BrowserDetection/blob/9350b2d69aa8dfd2d526000bc0fb52a0baf611d2/lib/BrowserDetection.php#L653-L690
Wolfcast/BrowserDetection
lib/BrowserDetection.php
BrowserDetection.checkBrowserBlackBerry
protected function checkBrowserBlackBerry() { $found = false; //Tablet OS check if ($this->checkSimpleBrowserUA('RIM Tablet OS', $this->_agent, self::BROWSER_TABLET_OS, true)) { return true; } //Version 6, 7 & 10 check (versions 8 & 9 does not exists) if ($this->checkBrowserUAWithVersion(array('BlackBerry', 'BB10'), $this->_agent, self::BROWSER_BLACKBERRY, true)) { if ($this->getVersion() == self::VERSION_UNKNOWN) { $found = true; } else { return true; } } //Version 4.2 to 5.0 check if ($this->checkSimpleBrowserUA('BlackBerry', $this->_agent, self::BROWSER_BLACKBERRY, true, false, '/', false)) { if ($this->getVersion() == self::VERSION_UNKNOWN) { $found = true; } else { return true; } } return $found; }
php
protected function checkBrowserBlackBerry() { $found = false; //Tablet OS check if ($this->checkSimpleBrowserUA('RIM Tablet OS', $this->_agent, self::BROWSER_TABLET_OS, true)) { return true; } //Version 6, 7 & 10 check (versions 8 & 9 does not exists) if ($this->checkBrowserUAWithVersion(array('BlackBerry', 'BB10'), $this->_agent, self::BROWSER_BLACKBERRY, true)) { if ($this->getVersion() == self::VERSION_UNKNOWN) { $found = true; } else { return true; } } //Version 4.2 to 5.0 check if ($this->checkSimpleBrowserUA('BlackBerry', $this->_agent, self::BROWSER_BLACKBERRY, true, false, '/', false)) { if ($this->getVersion() == self::VERSION_UNKNOWN) { $found = true; } else { return true; } } return $found; }
[ "protected", "function", "checkBrowserBlackBerry", "(", ")", "{", "$", "found", "=", "false", ";", "//Tablet OS check", "if", "(", "$", "this", "->", "checkSimpleBrowserUA", "(", "'RIM Tablet OS'", ",", "$", "this", "->", "_agent", ",", "self", "::", "BROWSER_...
Determine if the browser is the BlackBerry browser or not. @access protected @link http://supportforums.blackberry.com/t5/Web-and-WebWorks-Development/How-to-detect-the-BlackBerry-Browser/ta-p/559862 @return boolean Returns true if the browser is the BlackBerry browser, false otherwise.
[ "Determine", "if", "the", "browser", "is", "the", "BlackBerry", "browser", "or", "not", "." ]
train
https://github.com/Wolfcast/BrowserDetection/blob/9350b2d69aa8dfd2d526000bc0fb52a0baf611d2/lib/BrowserDetection.php#L721-L749
Wolfcast/BrowserDetection
lib/BrowserDetection.php
BrowserDetection.checkBrowserCustom
protected function checkBrowserCustom() { foreach ($this->_customBrowserDetection as $browserName => $customBrowser) { $uaNameToLookFor = $customBrowser['uaNameToLookFor']; $isMobile = $customBrowser['isMobile']; $isRobot = $customBrowser['isRobot']; $separator = $customBrowser['separator']; $uaNameFindWords = $customBrowser['uaNameFindWords']; if ($this->checkSimpleBrowserUA($uaNameToLookFor, $this->_agent, $browserName, $isMobile, $isRobot, $separator, $uaNameFindWords)) { return true; } } return false; }
php
protected function checkBrowserCustom() { foreach ($this->_customBrowserDetection as $browserName => $customBrowser) { $uaNameToLookFor = $customBrowser['uaNameToLookFor']; $isMobile = $customBrowser['isMobile']; $isRobot = $customBrowser['isRobot']; $separator = $customBrowser['separator']; $uaNameFindWords = $customBrowser['uaNameFindWords']; if ($this->checkSimpleBrowserUA($uaNameToLookFor, $this->_agent, $browserName, $isMobile, $isRobot, $separator, $uaNameFindWords)) { return true; } } return false; }
[ "protected", "function", "checkBrowserCustom", "(", ")", "{", "foreach", "(", "$", "this", "->", "_customBrowserDetection", "as", "$", "browserName", "=>", "$", "customBrowser", ")", "{", "$", "uaNameToLookFor", "=", "$", "customBrowser", "[", "'uaNameToLookFor'",...
Determine if the browser is among the custom browser rules or not. Rules are checked in the order they were added. @access protected @return boolean Returns true if we found the browser we were looking for in the custom rules, false otherwise.
[ "Determine", "if", "the", "browser", "is", "among", "the", "custom", "browser", "rules", "or", "not", ".", "Rules", "are", "checked", "in", "the", "order", "they", "were", "added", "." ]
train
https://github.com/Wolfcast/BrowserDetection/blob/9350b2d69aa8dfd2d526000bc0fb52a0baf611d2/lib/BrowserDetection.php#L768-L781
Wolfcast/BrowserDetection
lib/BrowserDetection.php
BrowserDetection.checkBrowserFirefox
protected function checkBrowserFirefox() { //Safari heavily matches with Firefox, ensure that Safari is filtered out... if (preg_match('/.*Firefox[ (\/]*([a-z0-9.-]*)/i', $this->_agent, $matches) && !$this->containString($this->_agent, 'Safari')) { $this->setBrowser(self::BROWSER_FIREFOX); $this->setVersion($matches[1]); $this->setMobile(false); $this->setRobot(false); return true; } return false; }
php
protected function checkBrowserFirefox() { //Safari heavily matches with Firefox, ensure that Safari is filtered out... if (preg_match('/.*Firefox[ (\/]*([a-z0-9.-]*)/i', $this->_agent, $matches) && !$this->containString($this->_agent, 'Safari')) { $this->setBrowser(self::BROWSER_FIREFOX); $this->setVersion($matches[1]); $this->setMobile(false); $this->setRobot(false); return true; } return false; }
[ "protected", "function", "checkBrowserFirefox", "(", ")", "{", "//Safari heavily matches with Firefox, ensure that Safari is filtered out...", "if", "(", "preg_match", "(", "'/.*Firefox[ (\\/]*([a-z0-9.-]*)/i'", ",", "$", "this", "->", "_agent", ",", "$", "matches", ")", "&...
Determine if the browser is Firefox or not. @access protected @link http://www.mozilla.org/en-US/firefox/new/ @return boolean Returns true if the browser is Firefox, false otherwise.
[ "Determine", "if", "the", "browser", "is", "Firefox", "or", "not", "." ]
train
https://github.com/Wolfcast/BrowserDetection/blob/9350b2d69aa8dfd2d526000bc0fb52a0baf611d2/lib/BrowserDetection.php#L809-L823
Wolfcast/BrowserDetection
lib/BrowserDetection.php
BrowserDetection.checkBrowserGooglebot
protected function checkBrowserGooglebot() { if ($this->checkSimpleBrowserUA('Googlebot', $this->_agent, self::BROWSER_GOOGLEBOT, false, true)) { if ($this->containString($this->_agent, 'googlebot-mobile')) { $this->setMobile(true); } return true; } return false; }
php
protected function checkBrowserGooglebot() { if ($this->checkSimpleBrowserUA('Googlebot', $this->_agent, self::BROWSER_GOOGLEBOT, false, true)) { if ($this->containString($this->_agent, 'googlebot-mobile')) { $this->setMobile(true); } return true; } return false; }
[ "protected", "function", "checkBrowserGooglebot", "(", ")", "{", "if", "(", "$", "this", "->", "checkSimpleBrowserUA", "(", "'Googlebot'", ",", "$", "this", "->", "_agent", ",", "self", "::", "BROWSER_GOOGLEBOT", ",", "false", ",", "true", ")", ")", "{", "...
Determine if the browser is the Googlebot crawler or not. @access protected @return boolean Returns true if the browser is Googlebot, false otherwise.
[ "Determine", "if", "the", "browser", "is", "the", "Googlebot", "crawler", "or", "not", "." ]
train
https://github.com/Wolfcast/BrowserDetection/blob/9350b2d69aa8dfd2d526000bc0fb52a0baf611d2/lib/BrowserDetection.php#L830-L842
Wolfcast/BrowserDetection
lib/BrowserDetection.php
BrowserDetection.checkBrowserInternetExplorer
protected function checkBrowserInternetExplorer() { //Test for Internet Explorer Mobile (formerly Pocket Internet Explorer) if ($this->checkSimpleBrowserUA(array('IEMobile', 'MSPIE'), $this->_agent, self::BROWSER_IE_MOBILE, true)) { return true; } //Several browsers uses IE compatibility UAs filter these browsers out (but after testing for IE Mobile) if ($this->containString($this->_agent, 'Opera') || $this->containString($this->_agent, array('BlackBerry', 'Nokia'), true, false)) { return false; } //Test for Internet Explorer 1 if ($this->checkSimpleBrowserUA('Microsoft Internet Explorer', $this->_agent, self::BROWSER_IE)) { if ($this->getVersion() == self::VERSION_UNKNOWN) { if (preg_match('/308|425|426|474|0b1/i', $this->_agent)) { $this->setVersion('1.5'); } else { $this->setVersion('1.0'); } } return true; } //Test for Internet Explorer 2+ if ($this->containString($this->_agent, array('MSIE', 'Trident'))) { $version = ''; if ($this->containString($this->_agent, 'Trident')) { //Test for Internet Explorer 11+ (check the rv: string) if ($this->containString($this->_agent, 'rv:', true, false)) { if ($this->checkSimpleBrowserUA('Trident', $this->_agent, self::BROWSER_IE, false, false, 'rv:')) { return true; } } else { //Test for Internet Explorer 8, 9 & 10 (check the Trident string) if (preg_match('/Trident\/([\d]+)/i', $this->_agent, $foundVersion)) { //Trident started with version 4.0 on IE 8 $verFromTrident = $this->parseInt($foundVersion[1]) + 4; if ($verFromTrident >= 8) { $version = $verFromTrident . '.0'; } } } //If we have the IE version from Trident, we can check for the compatibility view mode if ($version != '') { $emulatedVer = ''; preg_match_all('/MSIE\s*([^\s;$]+)/i', $this->_agent, $foundVersions); foreach ($foundVersions[1] as $currVer) { //Keep the lowest MSIE version for the emulated version (in compatibility view mode) if ($emulatedVer == '' || $this->compareVersions($emulatedVer, $currVer) == 1) { $emulatedVer = $currVer; } } //Set the compatibility view mode if $version != $emulatedVer if ($this->compareVersions($version, $emulatedVer) != 0) { $this->_compatibilityViewName = self::BROWSER_IE; $this->_compatibilityViewVer = $this->cleanVersion($emulatedVer); } } } //Test for Internet Explorer 2-7 versions if needed if ($version == '') { preg_match_all('/MSIE\s+([^\s;$]+)/i', $this->_agent, $foundVersions); foreach ($foundVersions[1] as $currVer) { //Keep the highest MSIE version if ($version == '' || $this->compareVersions($version, $currVer) == -1) { $version = $currVer; } } } $this->setBrowser(self::BROWSER_IE); $this->setVersion($version); $this->setMobile(false); $this->setRobot(false); return true; } return false; }
php
protected function checkBrowserInternetExplorer() { //Test for Internet Explorer Mobile (formerly Pocket Internet Explorer) if ($this->checkSimpleBrowserUA(array('IEMobile', 'MSPIE'), $this->_agent, self::BROWSER_IE_MOBILE, true)) { return true; } //Several browsers uses IE compatibility UAs filter these browsers out (but after testing for IE Mobile) if ($this->containString($this->_agent, 'Opera') || $this->containString($this->_agent, array('BlackBerry', 'Nokia'), true, false)) { return false; } //Test for Internet Explorer 1 if ($this->checkSimpleBrowserUA('Microsoft Internet Explorer', $this->_agent, self::BROWSER_IE)) { if ($this->getVersion() == self::VERSION_UNKNOWN) { if (preg_match('/308|425|426|474|0b1/i', $this->_agent)) { $this->setVersion('1.5'); } else { $this->setVersion('1.0'); } } return true; } //Test for Internet Explorer 2+ if ($this->containString($this->_agent, array('MSIE', 'Trident'))) { $version = ''; if ($this->containString($this->_agent, 'Trident')) { //Test for Internet Explorer 11+ (check the rv: string) if ($this->containString($this->_agent, 'rv:', true, false)) { if ($this->checkSimpleBrowserUA('Trident', $this->_agent, self::BROWSER_IE, false, false, 'rv:')) { return true; } } else { //Test for Internet Explorer 8, 9 & 10 (check the Trident string) if (preg_match('/Trident\/([\d]+)/i', $this->_agent, $foundVersion)) { //Trident started with version 4.0 on IE 8 $verFromTrident = $this->parseInt($foundVersion[1]) + 4; if ($verFromTrident >= 8) { $version = $verFromTrident . '.0'; } } } //If we have the IE version from Trident, we can check for the compatibility view mode if ($version != '') { $emulatedVer = ''; preg_match_all('/MSIE\s*([^\s;$]+)/i', $this->_agent, $foundVersions); foreach ($foundVersions[1] as $currVer) { //Keep the lowest MSIE version for the emulated version (in compatibility view mode) if ($emulatedVer == '' || $this->compareVersions($emulatedVer, $currVer) == 1) { $emulatedVer = $currVer; } } //Set the compatibility view mode if $version != $emulatedVer if ($this->compareVersions($version, $emulatedVer) != 0) { $this->_compatibilityViewName = self::BROWSER_IE; $this->_compatibilityViewVer = $this->cleanVersion($emulatedVer); } } } //Test for Internet Explorer 2-7 versions if needed if ($version == '') { preg_match_all('/MSIE\s+([^\s;$]+)/i', $this->_agent, $foundVersions); foreach ($foundVersions[1] as $currVer) { //Keep the highest MSIE version if ($version == '' || $this->compareVersions($version, $currVer) == -1) { $version = $currVer; } } } $this->setBrowser(self::BROWSER_IE); $this->setVersion($version); $this->setMobile(false); $this->setRobot(false); return true; } return false; }
[ "protected", "function", "checkBrowserInternetExplorer", "(", ")", "{", "//Test for Internet Explorer Mobile (formerly Pocket Internet Explorer)", "if", "(", "$", "this", "->", "checkSimpleBrowserUA", "(", "array", "(", "'IEMobile'", ",", "'MSPIE'", ")", ",", "$", "this",...
Determine if the browser is Internet Explorer or not. @access protected @link http://www.microsoft.com/ie/ @link http://en.wikipedia.org/wiki/Internet_Explorer_Mobile @return boolean Returns true if the browser is Internet Explorer, false otherwise.
[ "Determine", "if", "the", "browser", "is", "Internet", "Explorer", "or", "not", "." ]
train
https://github.com/Wolfcast/BrowserDetection/blob/9350b2d69aa8dfd2d526000bc0fb52a0baf611d2/lib/BrowserDetection.php#L885-L968
Wolfcast/BrowserDetection
lib/BrowserDetection.php
BrowserDetection.checkBrowserNetscape
protected function checkBrowserNetscape() { //BlackBerry & Nokia UAs can conflict with Netscape UAs if ($this->containString($this->_agent, array('BlackBerry', 'Nokia'), true, false)) { return false; } //Netscape v6 to v9 check if ($this->checkSimpleBrowserUA(array('Netscape', 'Navigator', 'Netscape6'), $this->_agent, self::BROWSER_NETSCAPE)) { return true; } //Netscape v1-4 (v5 don't exists) $found = false; if ($this->containString($this->_agent, 'Mozilla') && !$this->containString($this->_agent, 'rv:', true, false)) { $version = ''; $verParts = explode('/', stristr($this->_agent, 'Mozilla')); if (count($verParts) > 1) { $verParts = explode(' ', $verParts[1]); $verParts = explode('.', $verParts[0]); $majorVer = $this->parseInt($verParts[0]); if ($majorVer > 0 && $majorVer < 5) { $version = implode('.', $verParts); $found = true; if (strtolower(substr($version, -4)) == '-sgi') { $version = substr($version, 0, -4); } else { if (strtolower(substr($version, -4)) == 'gold') { $version = substr($version, 0, -4) . ' Gold'; //Doubles spaces (if any) will be normalized by setVersion() } } } } } if ($found) { $this->setBrowser(self::BROWSER_NETSCAPE); $this->setVersion($version); $this->setMobile(false); $this->setRobot(false); } return $found; }
php
protected function checkBrowserNetscape() { //BlackBerry & Nokia UAs can conflict with Netscape UAs if ($this->containString($this->_agent, array('BlackBerry', 'Nokia'), true, false)) { return false; } //Netscape v6 to v9 check if ($this->checkSimpleBrowserUA(array('Netscape', 'Navigator', 'Netscape6'), $this->_agent, self::BROWSER_NETSCAPE)) { return true; } //Netscape v1-4 (v5 don't exists) $found = false; if ($this->containString($this->_agent, 'Mozilla') && !$this->containString($this->_agent, 'rv:', true, false)) { $version = ''; $verParts = explode('/', stristr($this->_agent, 'Mozilla')); if (count($verParts) > 1) { $verParts = explode(' ', $verParts[1]); $verParts = explode('.', $verParts[0]); $majorVer = $this->parseInt($verParts[0]); if ($majorVer > 0 && $majorVer < 5) { $version = implode('.', $verParts); $found = true; if (strtolower(substr($version, -4)) == '-sgi') { $version = substr($version, 0, -4); } else { if (strtolower(substr($version, -4)) == 'gold') { $version = substr($version, 0, -4) . ' Gold'; //Doubles spaces (if any) will be normalized by setVersion() } } } } } if ($found) { $this->setBrowser(self::BROWSER_NETSCAPE); $this->setVersion($version); $this->setMobile(false); $this->setRobot(false); } return $found; }
[ "protected", "function", "checkBrowserNetscape", "(", ")", "{", "//BlackBerry & Nokia UAs can conflict with Netscape UAs", "if", "(", "$", "this", "->", "containString", "(", "$", "this", "->", "_agent", ",", "array", "(", "'BlackBerry'", ",", "'Nokia'", ")", ",", ...
Determine if the browser is Netscape or not. Official support for this browser ended on March 1st, 2008. @access protected @link http://en.wikipedia.org/wiki/Netscape @return boolean Returns true if the browser is Netscape, false otherwise.
[ "Determine", "if", "the", "browser", "is", "Netscape", "or", "not", ".", "Official", "support", "for", "this", "browser", "ended", "on", "March", "1st", "2008", "." ]
train
https://github.com/Wolfcast/BrowserDetection/blob/9350b2d69aa8dfd2d526000bc0fb52a0baf611d2/lib/BrowserDetection.php#L1031-L1076
Wolfcast/BrowserDetection
lib/BrowserDetection.php
BrowserDetection.checkBrowserNokia
protected function checkBrowserNokia() { if ($this->containString($this->_agent, array('Nokia5800', 'Nokia5530', 'Nokia5230'), true, false)) { $this->setBrowser(self::BROWSER_NOKIA); $this->setVersion('7.0'); $this->setMobile(true); $this->setRobot(false); return true; } if ($this->checkSimpleBrowserUA(array('NokiaBrowser', 'BrowserNG', 'Series60', 'S60', 'S40OviBrowser'), $this->_agent, self::BROWSER_NOKIA, true)) { return true; } return false; }
php
protected function checkBrowserNokia() { if ($this->containString($this->_agent, array('Nokia5800', 'Nokia5530', 'Nokia5230'), true, false)) { $this->setBrowser(self::BROWSER_NOKIA); $this->setVersion('7.0'); $this->setMobile(true); $this->setRobot(false); return true; } if ($this->checkSimpleBrowserUA(array('NokiaBrowser', 'BrowserNG', 'Series60', 'S60', 'S40OviBrowser'), $this->_agent, self::BROWSER_NOKIA, true)) { return true; } return false; }
[ "protected", "function", "checkBrowserNokia", "(", ")", "{", "if", "(", "$", "this", "->", "containString", "(", "$", "this", "->", "_agent", ",", "array", "(", "'Nokia5800'", ",", "'Nokia5530'", ",", "'Nokia5230'", ")", ",", "true", ",", "false", ")", "...
Determine if the browser is a Nokia browser or not. @access protected @link http://www.developer.nokia.com/Community/Wiki/User-Agent_headers_for_Nokia_devices @return boolean Returns true if the browser is a Nokia browser, false otherwise.
[ "Determine", "if", "the", "browser", "is", "a", "Nokia", "browser", "or", "not", "." ]
train
https://github.com/Wolfcast/BrowserDetection/blob/9350b2d69aa8dfd2d526000bc0fb52a0baf611d2/lib/BrowserDetection.php#L1084-L1100
Wolfcast/BrowserDetection
lib/BrowserDetection.php
BrowserDetection.checkBrowserOpera
protected function checkBrowserOpera() { if ($this->checkBrowserUAWithVersion('Opera Mobi', $this->_agent, self::BROWSER_OPERA_MOBILE, true)) { return true; } if ($this->checkSimpleBrowserUA('Opera Mini', $this->_agent, self::BROWSER_OPERA_MINI, true)) { return true; } $version = ''; $found = $this->checkBrowserUAWithVersion('Opera', $this->_agent, self::BROWSER_OPERA); if ($found && $this->getVersion() != self::VERSION_UNKNOWN) { $version = $this->getVersion(); } if (!$found || $version == '') { if ($this->checkSimpleBrowserUA('Opera', $this->_agent, self::BROWSER_OPERA)) { return true; } } if (!$found && $this->checkSimpleBrowserUA('Chrome', $this->_agent, self::BROWSER_CHROME) ) { if ($this->checkSimpleBrowserUA('OPR', $this->_agent, self::BROWSER_OPERA)) { return true; } } return $found; }
php
protected function checkBrowserOpera() { if ($this->checkBrowserUAWithVersion('Opera Mobi', $this->_agent, self::BROWSER_OPERA_MOBILE, true)) { return true; } if ($this->checkSimpleBrowserUA('Opera Mini', $this->_agent, self::BROWSER_OPERA_MINI, true)) { return true; } $version = ''; $found = $this->checkBrowserUAWithVersion('Opera', $this->_agent, self::BROWSER_OPERA); if ($found && $this->getVersion() != self::VERSION_UNKNOWN) { $version = $this->getVersion(); } if (!$found || $version == '') { if ($this->checkSimpleBrowserUA('Opera', $this->_agent, self::BROWSER_OPERA)) { return true; } } if (!$found && $this->checkSimpleBrowserUA('Chrome', $this->_agent, self::BROWSER_CHROME) ) { if ($this->checkSimpleBrowserUA('OPR', $this->_agent, self::BROWSER_OPERA)) { return true; } } return $found; }
[ "protected", "function", "checkBrowserOpera", "(", ")", "{", "if", "(", "$", "this", "->", "checkBrowserUAWithVersion", "(", "'Opera Mobi'", ",", "$", "this", "->", "_agent", ",", "self", "::", "BROWSER_OPERA_MOBILE", ",", "true", ")", ")", "{", "return", "t...
Determine if the browser is Opera or not. @access protected @link http://www.opera.com/ @link http://www.opera.com/mini/ @link http://www.opera.com/mobile/ @link http://my.opera.com/community/openweb/idopera/ @return boolean Returns true if the browser is Opera, false otherwise.
[ "Determine", "if", "the", "browser", "is", "Opera", "or", "not", "." ]
train
https://github.com/Wolfcast/BrowserDetection/blob/9350b2d69aa8dfd2d526000bc0fb52a0baf611d2/lib/BrowserDetection.php#L1111-L1140
Wolfcast/BrowserDetection
lib/BrowserDetection.php
BrowserDetection.checkBrowsers
protected function checkBrowsers() { //Changing the check order can break the class detection results! return /* Major browsers and browsers that need to be detected in a special order */ $this->checkBrowserCustom() || /* Customs rules are always checked first */ $this->checkBrowserMsnTv() || /* MSN TV is based on IE so we must check for MSN TV before IE */ $this->checkBrowserInternetExplorer() || $this->checkBrowserOpera() || /* Opera must be checked before Firefox, Netscape and Chrome to avoid conflicts */ $this->checkBrowserEdge() || /* Edge must be checked before Firefox, Safari and Chrome to avoid conflicts */ $this->checkBrowserSamsung() || /* Samsung Internet browser must be checked before Chrome and Safari to avoid conflicts */ $this->checkBrowserUC() || /* UC Browser must be checked before Chrome and Safari to avoid conflicts */ $this->checkBrowserChrome() || /* Chrome must be checked before Netscaoe and Mozilla to avoid conflicts */ $this->checkBrowserIcab() || /* Check iCab before Netscape since iCab have Mozilla UAs */ $this->checkBrowserNetscape() || /* Must be checked before Firefox since Netscape 8-9 are based on Firefox */ $this->checkBrowserIceCat() || /* Check IceCat and IceWeasel before Firefox since they are GNU builds of Firefox */ $this->checkBrowserIceWeasel() || $this->checkBrowserFirefox() || /* Current browsers that don't need to be detected in any special order */ $this->checkBrowserKonqueror() || $this->checkBrowserLynx() || /* Mobile */ $this->checkBrowserAndroid() || $this->checkBrowserBlackBerry() || $this->checkBrowserNokia() || /* Bots */ $this->checkBrowserGooglebot() || $this->checkBrowserBingbot() || $this->checkBrowserMsnBot() || $this->checkBrowserSlurp() || $this->checkBrowserYahooMultimedia() || $this->checkBrowserW3CValidator() || /* WebKit base check (after most other checks) */ $this->checkBrowserSafari() || /* Deprecated browsers that don't need to be detected in any special order */ $this->checkBrowserFirebird() || $this->checkBrowserPhoenix() || /* Mozilla is such an open standard that it must be checked last */ $this->checkBrowserMozilla(); }
php
protected function checkBrowsers() { //Changing the check order can break the class detection results! return /* Major browsers and browsers that need to be detected in a special order */ $this->checkBrowserCustom() || /* Customs rules are always checked first */ $this->checkBrowserMsnTv() || /* MSN TV is based on IE so we must check for MSN TV before IE */ $this->checkBrowserInternetExplorer() || $this->checkBrowserOpera() || /* Opera must be checked before Firefox, Netscape and Chrome to avoid conflicts */ $this->checkBrowserEdge() || /* Edge must be checked before Firefox, Safari and Chrome to avoid conflicts */ $this->checkBrowserSamsung() || /* Samsung Internet browser must be checked before Chrome and Safari to avoid conflicts */ $this->checkBrowserUC() || /* UC Browser must be checked before Chrome and Safari to avoid conflicts */ $this->checkBrowserChrome() || /* Chrome must be checked before Netscaoe and Mozilla to avoid conflicts */ $this->checkBrowserIcab() || /* Check iCab before Netscape since iCab have Mozilla UAs */ $this->checkBrowserNetscape() || /* Must be checked before Firefox since Netscape 8-9 are based on Firefox */ $this->checkBrowserIceCat() || /* Check IceCat and IceWeasel before Firefox since they are GNU builds of Firefox */ $this->checkBrowserIceWeasel() || $this->checkBrowserFirefox() || /* Current browsers that don't need to be detected in any special order */ $this->checkBrowserKonqueror() || $this->checkBrowserLynx() || /* Mobile */ $this->checkBrowserAndroid() || $this->checkBrowserBlackBerry() || $this->checkBrowserNokia() || /* Bots */ $this->checkBrowserGooglebot() || $this->checkBrowserBingbot() || $this->checkBrowserMsnBot() || $this->checkBrowserSlurp() || $this->checkBrowserYahooMultimedia() || $this->checkBrowserW3CValidator() || /* WebKit base check (after most other checks) */ $this->checkBrowserSafari() || /* Deprecated browsers that don't need to be detected in any special order */ $this->checkBrowserFirebird() || $this->checkBrowserPhoenix() || /* Mozilla is such an open standard that it must be checked last */ $this->checkBrowserMozilla(); }
[ "protected", "function", "checkBrowsers", "(", ")", "{", "//Changing the check order can break the class detection results!", "return", "/* Major browsers and browsers that need to be detected in a special order */", "$", "this", "->", "checkBrowserCustom", "(", ")", "||", "/* Custom...
Determine what is the browser used by the user. @access protected @return boolean Returns true if the browser has been identified, false otherwise.
[ "Determine", "what", "is", "the", "browser", "used", "by", "the", "user", "." ]
train
https://github.com/Wolfcast/BrowserDetection/blob/9350b2d69aa8dfd2d526000bc0fb52a0baf611d2/lib/BrowserDetection.php#L1157-L1196
Wolfcast/BrowserDetection
lib/BrowserDetection.php
BrowserDetection.checkBrowserSafari
protected function checkBrowserSafari() { $version = ''; //Check for current versions of Safari $found = $this->checkBrowserUAWithVersion(array('Safari', 'AppleWebKit'), $this->_agent, self::BROWSER_SAFARI); if ($found && $this->getVersion() != self::VERSION_UNKNOWN) { $version = $this->getVersion(); } //Safari 1-2 didn't had a "Version" string in the UA, only a WebKit build and/or Safari build, extract version from these... if (!$found || $version == '') { if (preg_match('/.*Safari[ (\/]*([a-z0-9.-]*)/i', $this->_agent, $matches)) { $version = $this->safariBuildToSafariVer($matches[1]); $found = true; } } if (!$found || $version == '') { if (preg_match('/.*AppleWebKit[ (\/]*([a-z0-9.-]*)/i', $this->_agent, $matches)) { $version = $this->webKitBuildToSafariVer($matches[1]); $found = true; } } if ($found) { $this->setBrowser(self::BROWSER_SAFARI); $this->setVersion($version); $this->setMobile(false); $this->setRobot(false); } return $found; }
php
protected function checkBrowserSafari() { $version = ''; //Check for current versions of Safari $found = $this->checkBrowserUAWithVersion(array('Safari', 'AppleWebKit'), $this->_agent, self::BROWSER_SAFARI); if ($found && $this->getVersion() != self::VERSION_UNKNOWN) { $version = $this->getVersion(); } //Safari 1-2 didn't had a "Version" string in the UA, only a WebKit build and/or Safari build, extract version from these... if (!$found || $version == '') { if (preg_match('/.*Safari[ (\/]*([a-z0-9.-]*)/i', $this->_agent, $matches)) { $version = $this->safariBuildToSafariVer($matches[1]); $found = true; } } if (!$found || $version == '') { if (preg_match('/.*AppleWebKit[ (\/]*([a-z0-9.-]*)/i', $this->_agent, $matches)) { $version = $this->webKitBuildToSafariVer($matches[1]); $found = true; } } if ($found) { $this->setBrowser(self::BROWSER_SAFARI); $this->setVersion($version); $this->setMobile(false); $this->setRobot(false); } return $found; }
[ "protected", "function", "checkBrowserSafari", "(", ")", "{", "$", "version", "=", "''", ";", "//Check for current versions of Safari", "$", "found", "=", "$", "this", "->", "checkBrowserUAWithVersion", "(", "array", "(", "'Safari'", ",", "'AppleWebKit'", ")", ","...
Determine if the browser is Safari or not. @access protected @link http://www.apple.com/safari/ @link http://web.archive.org/web/20080514173941/http://developer.apple.com/internet/safari/uamatrix.html @link http://en.wikipedia.org/wiki/Safari_version_history#Release_history @return boolean Returns true if the browser is Safari, false otherwise.
[ "Determine", "if", "the", "browser", "is", "Safari", "or", "not", "." ]
train
https://github.com/Wolfcast/BrowserDetection/blob/9350b2d69aa8dfd2d526000bc0fb52a0baf611d2/lib/BrowserDetection.php#L1206-L1238
Wolfcast/BrowserDetection
lib/BrowserDetection.php
BrowserDetection.checkBrowserUAWithVersion
protected function checkBrowserUAWithVersion($uaNameToLookFor, $userAgent, $browserName, $isMobile = false, $isRobot = false, $findWords = true) { if (!is_array($uaNameToLookFor)) { $uaNameToLookFor = array($uaNameToLookFor); } foreach ($uaNameToLookFor as $currUANameToLookFor) { if ($this->containString($userAgent, $currUANameToLookFor, true, $findWords)) { $version = ''; $verParts = explode('/', stristr($this->_agent, 'Version')); if (count($verParts) > 1) { $verParts = explode(' ', $verParts[1]); $version = $verParts[0]; } $this->setBrowser($browserName); $this->setVersion($version); $this->setMobile($isMobile); $this->setRobot($isRobot); return true; } } return false; }
php
protected function checkBrowserUAWithVersion($uaNameToLookFor, $userAgent, $browserName, $isMobile = false, $isRobot = false, $findWords = true) { if (!is_array($uaNameToLookFor)) { $uaNameToLookFor = array($uaNameToLookFor); } foreach ($uaNameToLookFor as $currUANameToLookFor) { if ($this->containString($userAgent, $currUANameToLookFor, true, $findWords)) { $version = ''; $verParts = explode('/', stristr($this->_agent, 'Version')); if (count($verParts) > 1) { $verParts = explode(' ', $verParts[1]); $version = $verParts[0]; } $this->setBrowser($browserName); $this->setVersion($version); $this->setMobile($isMobile); $this->setRobot($isRobot); return true; } } return false; }
[ "protected", "function", "checkBrowserUAWithVersion", "(", "$", "uaNameToLookFor", ",", "$", "userAgent", ",", "$", "browserName", ",", "$", "isMobile", "=", "false", ",", "$", "isRobot", "=", "false", ",", "$", "findWords", "=", "true", ")", "{", "if", "(...
Test the user agent for a specific browser that use a "Version" string (like Safari and Opera). The user agent should look like: "Version/1.0 Browser name/123.456" or "Browser name/123.456 Version/1.0". @access protected @param mixed $uaNameToLookFor The string (or array of strings) representing the browser name to find in the user agent. @param string $userAgent The user agent string to work with. @param string $browserName The literal browser name. Always use a class constant! @param boolean $isMobile (optional) Determines if the browser is from a mobile device. @param boolean $isRobot (optional) Determines if the browser is a robot or not. @param boolean $findWords (optional) Determines if the needle should match a word to be found. For example "Bar" would not be found in "FooBar" when true but would be found in "Foo Bar". When set to false, the needle can be found anywhere in the haystack. @return boolean Returns true if we found the browser we were looking for, false otherwise.
[ "Test", "the", "user", "agent", "for", "a", "specific", "browser", "that", "use", "a", "Version", "string", "(", "like", "Safari", "and", "Opera", ")", ".", "The", "user", "agent", "should", "look", "like", ":", "Version", "/", "1", ".", "0", "Browser"...
train
https://github.com/Wolfcast/BrowserDetection/blob/9350b2d69aa8dfd2d526000bc0fb52a0baf611d2/lib/BrowserDetection.php#L1275-L1301
Wolfcast/BrowserDetection
lib/BrowserDetection.php
BrowserDetection.checkBrowserW3CValidator
protected function checkBrowserW3CValidator() { //Since the W3C validates pages with different robots we will prefix our versions with the part validated on the page... //W3C Link Checker (prefixed with "Link-") if ($this->checkSimpleBrowserUA('W3C-checklink', $this->_agent, self::BROWSER_W3CVALIDATOR, false, true)) { if ($this->getVersion() != self::VERSION_UNKNOWN) { $this->setVersion('Link-' . $this->getVersion()); } return true; } //W3C CSS Validation Service (prefixed with "CSS-") if ($this->checkSimpleBrowserUA('Jigsaw', $this->_agent, self::BROWSER_W3CVALIDATOR, false, true)) { if ($this->getVersion() != self::VERSION_UNKNOWN) { $this->setVersion('CSS-' . $this->getVersion()); } return true; } //W3C mobileOK Checker (prefixed with "mobileOK-") if ($this->checkSimpleBrowserUA('W3C-mobileOK', $this->_agent, self::BROWSER_W3CVALIDATOR, false, true)) { if ($this->getVersion() != self::VERSION_UNKNOWN) { $this->setVersion('mobileOK-' . $this->getVersion()); } return true; } //W3C Markup Validation Service (no prefix) return $this->checkSimpleBrowserUA('W3C_Validator', $this->_agent, self::BROWSER_W3CVALIDATOR, false, true); }
php
protected function checkBrowserW3CValidator() { //Since the W3C validates pages with different robots we will prefix our versions with the part validated on the page... //W3C Link Checker (prefixed with "Link-") if ($this->checkSimpleBrowserUA('W3C-checklink', $this->_agent, self::BROWSER_W3CVALIDATOR, false, true)) { if ($this->getVersion() != self::VERSION_UNKNOWN) { $this->setVersion('Link-' . $this->getVersion()); } return true; } //W3C CSS Validation Service (prefixed with "CSS-") if ($this->checkSimpleBrowserUA('Jigsaw', $this->_agent, self::BROWSER_W3CVALIDATOR, false, true)) { if ($this->getVersion() != self::VERSION_UNKNOWN) { $this->setVersion('CSS-' . $this->getVersion()); } return true; } //W3C mobileOK Checker (prefixed with "mobileOK-") if ($this->checkSimpleBrowserUA('W3C-mobileOK', $this->_agent, self::BROWSER_W3CVALIDATOR, false, true)) { if ($this->getVersion() != self::VERSION_UNKNOWN) { $this->setVersion('mobileOK-' . $this->getVersion()); } return true; } //W3C Markup Validation Service (no prefix) return $this->checkSimpleBrowserUA('W3C_Validator', $this->_agent, self::BROWSER_W3CVALIDATOR, false, true); }
[ "protected", "function", "checkBrowserW3CValidator", "(", ")", "{", "//Since the W3C validates pages with different robots we will prefix our versions with the part validated on the page...", "//W3C Link Checker (prefixed with \"Link-\")", "if", "(", "$", "this", "->", "checkSimpleBrowserU...
Determine if the browser is the W3C Validator or not. @access protected @link http://validator.w3.org/ @return boolean Returns true if the browser is the W3C Validator, false otherwise.
[ "Determine", "if", "the", "browser", "is", "the", "W3C", "Validator", "or", "not", "." ]
train
https://github.com/Wolfcast/BrowserDetection/blob/9350b2d69aa8dfd2d526000bc0fb52a0baf611d2/lib/BrowserDetection.php#L1319-L1349
Wolfcast/BrowserDetection
lib/BrowserDetection.php
BrowserDetection.checkPlatform
protected function checkPlatform() { if (!$this->checkPlatformCustom()) { /* Customs rules are always checked first */ /* Mobile platforms */ if ($this->containString($this->_agent, array('Windows Phone', 'IEMobile'))) { /* Check Windows Phone (formerly Windows Mobile) before Windows */ $this->setPlatform(self::PLATFORM_WINDOWS_PHONE); $this->setMobile(true); } else if ($this->containString($this->_agent, 'Windows CE')) { /* Check Windows CE before Windows */ $this->setPlatform(self::PLATFORM_WINDOWS_CE); $this->setMobile(true); } else if ($this->containString($this->_agent, array('CPU OS', 'CPU iPhone OS', 'iPhone', 'iPad', 'iPod'))) { /* Check iOS (iPad/iPod/iPhone) before Macintosh */ $this->setPlatform(self::PLATFORM_IOS); $this->setMobile(true); } else if ($this->containString($this->_agent, 'Android')) { $this->setPlatform(self::PLATFORM_ANDROID); $this->setMobile(true); } else if ($this->containString($this->_agent, 'BlackBerry', true, false) || $this->containString($this->_agent, array('BB10', 'RIM Tablet OS'))) { $this->setPlatform(self::PLATFORM_BLACKBERRY); $this->setMobile(true); } else if ($this->containString($this->_agent, 'Nokia', true, false)) { $this->setPlatform(self::PLATFORM_NOKIA); $this->setMobile(true); /* Desktop platforms */ } else if ($this->containString($this->_agent, 'Windows')) { $this->setPlatform(self::PLATFORM_WINDOWS); } else if ($this->containString($this->_agent, 'Macintosh')) { $this->setPlatform(self::PLATFORM_MACINTOSH); } else if ($this->containString($this->_agent, 'Linux')) { $this->setPlatform(self::PLATFORM_LINUX); } else if ($this->containString($this->_agent, 'FreeBSD')) { $this->setPlatform(self::PLATFORM_FREEBSD); } else if ($this->containString($this->_agent, 'OpenBSD')) { $this->setPlatform(self::PLATFORM_OPENBSD); } else if ($this->containString($this->_agent, 'NetBSD')) { $this->setPlatform(self::PLATFORM_NETBSD); /* Discontinued */ } else if ($this->containString($this->_agent, array('Symbian', 'SymbianOS'))) { $this->setPlatform(self::PLATFORM_SYMBIAN); $this->setMobile(true); } else if ($this->containString($this->_agent, 'OpenSolaris')) { $this->setPlatform(self::PLATFORM_OPENSOLARIS); /* Generic */ } else if ($this->containString($this->_agent, 'Win', true, false)) { $this->setPlatform(self::PLATFORM_WINDOWS); } else if ($this->containString($this->_agent, 'Mac', true, false)) { $this->setPlatform(self::PLATFORM_MACINTOSH); } } //Check if it's a 64-bit platform if ($this->containString($this->_agent, array('WOW64', 'Win64', 'AMD64', 'x86_64', 'x86-64', 'ia64', 'IRIX64', 'ppc64', 'sparc64', 'x64;', 'x64_64'))) { $this->set64bit(true); } $this->checkPlatformVersion(); }
php
protected function checkPlatform() { if (!$this->checkPlatformCustom()) { /* Customs rules are always checked first */ /* Mobile platforms */ if ($this->containString($this->_agent, array('Windows Phone', 'IEMobile'))) { /* Check Windows Phone (formerly Windows Mobile) before Windows */ $this->setPlatform(self::PLATFORM_WINDOWS_PHONE); $this->setMobile(true); } else if ($this->containString($this->_agent, 'Windows CE')) { /* Check Windows CE before Windows */ $this->setPlatform(self::PLATFORM_WINDOWS_CE); $this->setMobile(true); } else if ($this->containString($this->_agent, array('CPU OS', 'CPU iPhone OS', 'iPhone', 'iPad', 'iPod'))) { /* Check iOS (iPad/iPod/iPhone) before Macintosh */ $this->setPlatform(self::PLATFORM_IOS); $this->setMobile(true); } else if ($this->containString($this->_agent, 'Android')) { $this->setPlatform(self::PLATFORM_ANDROID); $this->setMobile(true); } else if ($this->containString($this->_agent, 'BlackBerry', true, false) || $this->containString($this->_agent, array('BB10', 'RIM Tablet OS'))) { $this->setPlatform(self::PLATFORM_BLACKBERRY); $this->setMobile(true); } else if ($this->containString($this->_agent, 'Nokia', true, false)) { $this->setPlatform(self::PLATFORM_NOKIA); $this->setMobile(true); /* Desktop platforms */ } else if ($this->containString($this->_agent, 'Windows')) { $this->setPlatform(self::PLATFORM_WINDOWS); } else if ($this->containString($this->_agent, 'Macintosh')) { $this->setPlatform(self::PLATFORM_MACINTOSH); } else if ($this->containString($this->_agent, 'Linux')) { $this->setPlatform(self::PLATFORM_LINUX); } else if ($this->containString($this->_agent, 'FreeBSD')) { $this->setPlatform(self::PLATFORM_FREEBSD); } else if ($this->containString($this->_agent, 'OpenBSD')) { $this->setPlatform(self::PLATFORM_OPENBSD); } else if ($this->containString($this->_agent, 'NetBSD')) { $this->setPlatform(self::PLATFORM_NETBSD); /* Discontinued */ } else if ($this->containString($this->_agent, array('Symbian', 'SymbianOS'))) { $this->setPlatform(self::PLATFORM_SYMBIAN); $this->setMobile(true); } else if ($this->containString($this->_agent, 'OpenSolaris')) { $this->setPlatform(self::PLATFORM_OPENSOLARIS); /* Generic */ } else if ($this->containString($this->_agent, 'Win', true, false)) { $this->setPlatform(self::PLATFORM_WINDOWS); } else if ($this->containString($this->_agent, 'Mac', true, false)) { $this->setPlatform(self::PLATFORM_MACINTOSH); } } //Check if it's a 64-bit platform if ($this->containString($this->_agent, array('WOW64', 'Win64', 'AMD64', 'x86_64', 'x86-64', 'ia64', 'IRIX64', 'ppc64', 'sparc64', 'x64;', 'x64_64'))) { $this->set64bit(true); } $this->checkPlatformVersion(); }
[ "protected", "function", "checkPlatform", "(", ")", "{", "if", "(", "!", "$", "this", "->", "checkPlatformCustom", "(", ")", ")", "{", "/* Customs rules are always checked first */", "/* Mobile platforms */", "if", "(", "$", "this", "->", "containString", "(", "$"...
Determine the user's platform. @access protected
[ "Determine", "the", "user", "s", "platform", "." ]
train
https://github.com/Wolfcast/BrowserDetection/blob/9350b2d69aa8dfd2d526000bc0fb52a0baf611d2/lib/BrowserDetection.php#L1365-L1424
Wolfcast/BrowserDetection
lib/BrowserDetection.php
BrowserDetection.checkPlatformCustom
protected function checkPlatformCustom() { foreach ($this->_customPlatformDetection as $platformName => $customPlatform) { $platformNameToLookFor = $customPlatform['platformNameToLookFor']; $isMobile = $customPlatform['isMobile']; if ($this->containString($this->_agent, $platformNameToLookFor)) { $this->setPlatform($platformName); if ($isMobile) { $this->setMobile(true); } return true; } } return false; }
php
protected function checkPlatformCustom() { foreach ($this->_customPlatformDetection as $platformName => $customPlatform) { $platformNameToLookFor = $customPlatform['platformNameToLookFor']; $isMobile = $customPlatform['isMobile']; if ($this->containString($this->_agent, $platformNameToLookFor)) { $this->setPlatform($platformName); if ($isMobile) { $this->setMobile(true); } return true; } } return false; }
[ "protected", "function", "checkPlatformCustom", "(", ")", "{", "foreach", "(", "$", "this", "->", "_customPlatformDetection", "as", "$", "platformName", "=>", "$", "customPlatform", ")", "{", "$", "platformNameToLookFor", "=", "$", "customPlatform", "[", "'platfor...
Determine if the platform is among the custom platform rules or not. Rules are checked in the order they were added. @access protected @return boolean Returns true if we found the platform we were looking for in the custom rules, false otherwise.
[ "Determine", "if", "the", "platform", "is", "among", "the", "custom", "platform", "rules", "or", "not", ".", "Rules", "are", "checked", "in", "the", "order", "they", "were", "added", "." ]
train
https://github.com/Wolfcast/BrowserDetection/blob/9350b2d69aa8dfd2d526000bc0fb52a0baf611d2/lib/BrowserDetection.php#L1432-L1447
Wolfcast/BrowserDetection
lib/BrowserDetection.php
BrowserDetection.checkPlatformVersion
protected function checkPlatformVersion() { $result = ''; switch ($this->getPlatform()) { case self::PLATFORM_WINDOWS: if (preg_match('/Windows NT\s*(\d+(?:\.\d+)*)/i', $this->_agent, $foundVersion)) { $result = 'NT ' . $foundVersion[1]; } else { //https://support.microsoft.com/en-us/kb/158238 if ($this->containString($this->_agent, array('Windows XP', 'WinXP', 'Win XP'))) { $result = '5.1'; } else if ($this->containString($this->_agent, 'Windows 2000', 'Win 2000', 'Win2000')) { $result = '5.0'; } else if ($this->containString($this->_agent, array('Win 9x 4.90', 'Windows ME', 'WinME', 'Win ME'))) { $result = '4.90.3000'; //Windows Me version range from 4.90.3000 to 4.90.3000A } else if ($this->containString($this->_agent, array('Windows 98', 'Win98', 'Win 98'))) { $result = '4.10'; //Windows 98 version range from 4.10.1998 to 4.10.2222B } else if ($this->containString($this->_agent, array('Windows 95', 'Win95', 'Win 95'))) { $result = '4.00'; //Windows 95 version range from 4.00.950 to 4.03.1214 } else if (($foundAt = stripos($this->_agent, 'Windows 3')) !== false) { $result = '3'; if (preg_match('/\d+(?:\.\d+)*/', substr($this->_agent, $foundAt + strlen('Windows 3')), $foundVersion)) { $result .= '.' . $foundVersion[0]; } } else if ($this->containString($this->_agent, 'Win16')) { $result = '3.1'; } } break; case self::PLATFORM_MACINTOSH: if (preg_match('/Mac OS X\s*(\d+(?:_\d+)+)/i', $this->_agent, $foundVersion)) { $result = str_replace('_', '.', $this->cleanVersion($foundVersion[1])); } else if ($this->containString($this->_agent, 'Mac OS X')) { $result = '10'; } break; case self::PLATFORM_ANDROID: if (preg_match('/Android\s+([^\s;$]+)/i', $this->_agent, $foundVersion)) { $result = $this->cleanVersion($foundVersion[1]); } break; case self::PLATFORM_IOS: if (preg_match('/(?:CPU OS|iPhone OS|iOS)[\s_]*([\d_]+)/i', $this->_agent, $foundVersion)) { $result = str_replace('_', '.', $this->cleanVersion($foundVersion[1])); } break; } if (trim($result) == '') { $result = self::PLATFORM_VERSION_UNKNOWN; } $this->setPlatformVersion($result); }
php
protected function checkPlatformVersion() { $result = ''; switch ($this->getPlatform()) { case self::PLATFORM_WINDOWS: if (preg_match('/Windows NT\s*(\d+(?:\.\d+)*)/i', $this->_agent, $foundVersion)) { $result = 'NT ' . $foundVersion[1]; } else { //https://support.microsoft.com/en-us/kb/158238 if ($this->containString($this->_agent, array('Windows XP', 'WinXP', 'Win XP'))) { $result = '5.1'; } else if ($this->containString($this->_agent, 'Windows 2000', 'Win 2000', 'Win2000')) { $result = '5.0'; } else if ($this->containString($this->_agent, array('Win 9x 4.90', 'Windows ME', 'WinME', 'Win ME'))) { $result = '4.90.3000'; //Windows Me version range from 4.90.3000 to 4.90.3000A } else if ($this->containString($this->_agent, array('Windows 98', 'Win98', 'Win 98'))) { $result = '4.10'; //Windows 98 version range from 4.10.1998 to 4.10.2222B } else if ($this->containString($this->_agent, array('Windows 95', 'Win95', 'Win 95'))) { $result = '4.00'; //Windows 95 version range from 4.00.950 to 4.03.1214 } else if (($foundAt = stripos($this->_agent, 'Windows 3')) !== false) { $result = '3'; if (preg_match('/\d+(?:\.\d+)*/', substr($this->_agent, $foundAt + strlen('Windows 3')), $foundVersion)) { $result .= '.' . $foundVersion[0]; } } else if ($this->containString($this->_agent, 'Win16')) { $result = '3.1'; } } break; case self::PLATFORM_MACINTOSH: if (preg_match('/Mac OS X\s*(\d+(?:_\d+)+)/i', $this->_agent, $foundVersion)) { $result = str_replace('_', '.', $this->cleanVersion($foundVersion[1])); } else if ($this->containString($this->_agent, 'Mac OS X')) { $result = '10'; } break; case self::PLATFORM_ANDROID: if (preg_match('/Android\s+([^\s;$]+)/i', $this->_agent, $foundVersion)) { $result = $this->cleanVersion($foundVersion[1]); } break; case self::PLATFORM_IOS: if (preg_match('/(?:CPU OS|iPhone OS|iOS)[\s_]*([\d_]+)/i', $this->_agent, $foundVersion)) { $result = str_replace('_', '.', $this->cleanVersion($foundVersion[1])); } break; } if (trim($result) == '') { $result = self::PLATFORM_VERSION_UNKNOWN; } $this->setPlatformVersion($result); }
[ "protected", "function", "checkPlatformVersion", "(", ")", "{", "$", "result", "=", "''", ";", "switch", "(", "$", "this", "->", "getPlatform", "(", ")", ")", "{", "case", "self", "::", "PLATFORM_WINDOWS", ":", "if", "(", "preg_match", "(", "'/Windows NT\\...
Determine the user's platform version. @access protected
[ "Determine", "the", "user", "s", "platform", "version", "." ]
train
https://github.com/Wolfcast/BrowserDetection/blob/9350b2d69aa8dfd2d526000bc0fb52a0baf611d2/lib/BrowserDetection.php#L1453-L1509
Wolfcast/BrowserDetection
lib/BrowserDetection.php
BrowserDetection.checkSimpleBrowserUA
protected function checkSimpleBrowserUA($uaNameToLookFor, $userAgent, $browserName, $isMobile = false, $isRobot = false, $separator = '/', $uaNameFindWords = true) { if (!is_array($uaNameToLookFor)) { $uaNameToLookFor = array($uaNameToLookFor); } foreach ($uaNameToLookFor as $currUANameToLookFor) { if ($this->containString($userAgent, $currUANameToLookFor, true, $uaNameFindWords)) { //Many browsers don't use the standard "Browser/1.0" format, they uses "Browser 1.0;" instead if (stripos($userAgent, $currUANameToLookFor . $separator) === false) { $userAgent = str_ireplace($currUANameToLookFor . ' ', $currUANameToLookFor . $separator, $this->_agent); } $version = ''; $verParts = explode($separator, stristr($userAgent, $currUANameToLookFor)); if (count($verParts) > 1) { $verParts = explode(' ', $verParts[1]); $version = $verParts[0]; } $this->setBrowser($browserName); $this->setVersion($version); $this->setMobile($isMobile); $this->setRobot($isRobot); return true; } } return false; }
php
protected function checkSimpleBrowserUA($uaNameToLookFor, $userAgent, $browserName, $isMobile = false, $isRobot = false, $separator = '/', $uaNameFindWords = true) { if (!is_array($uaNameToLookFor)) { $uaNameToLookFor = array($uaNameToLookFor); } foreach ($uaNameToLookFor as $currUANameToLookFor) { if ($this->containString($userAgent, $currUANameToLookFor, true, $uaNameFindWords)) { //Many browsers don't use the standard "Browser/1.0" format, they uses "Browser 1.0;" instead if (stripos($userAgent, $currUANameToLookFor . $separator) === false) { $userAgent = str_ireplace($currUANameToLookFor . ' ', $currUANameToLookFor . $separator, $this->_agent); } $version = ''; $verParts = explode($separator, stristr($userAgent, $currUANameToLookFor)); if (count($verParts) > 1) { $verParts = explode(' ', $verParts[1]); $version = $verParts[0]; } $this->setBrowser($browserName); $this->setVersion($version); $this->setMobile($isMobile); $this->setRobot($isRobot); return true; } } return false; }
[ "protected", "function", "checkSimpleBrowserUA", "(", "$", "uaNameToLookFor", ",", "$", "userAgent", ",", "$", "browserName", ",", "$", "isMobile", "=", "false", ",", "$", "isRobot", "=", "false", ",", "$", "separator", "=", "'/'", ",", "$", "uaNameFindWords...
Test the user agent for a specific browser where the browser name is immediately followed by the version number. The user agent should look like: "Browser name/1.0" or "Browser 1.0;". @access protected @param mixed $uaNameToLookFor The string (or array of strings) representing the browser name to find in the user agent. @param string $userAgent The user agent string to work with. @param string $browserName The literal browser name. Always use a class constant! @param boolean $isMobile (optional) Determines if the browser is from a mobile device. @param boolean $isRobot (optional) Determines if the browser is a robot or not. @param string $separator (optional) The separator string used to split the browser name and the version number in the user agent. @param boolean $uaNameFindWords (optional) Determines if the browser name to find should match a word instead of a part of a word. For example "Bar" would not be found in "FooBar" when true but would be found in "Foo Bar". When set to false, the browser name can be found anywhere in the user agent string. @return boolean Returns true if we found the browser we were looking for, false otherwise.
[ "Test", "the", "user", "agent", "for", "a", "specific", "browser", "where", "the", "browser", "name", "is", "immediately", "followed", "by", "the", "version", "number", ".", "The", "user", "agent", "should", "look", "like", ":", "Browser", "name", "/", "1"...
train
https://github.com/Wolfcast/BrowserDetection/blob/9350b2d69aa8dfd2d526000bc0fb52a0baf611d2/lib/BrowserDetection.php#L1528-L1560
Wolfcast/BrowserDetection
lib/BrowserDetection.php
BrowserDetection.containString
protected function containString($haystack, $needle, $insensitive = true, $findWords = true) { if (!is_array($needle)) { $needle = array($needle); } foreach ($needle as $currNeedle) { if ($findWords) { $found = $this->wordPos($haystack, $currNeedle, $insensitive) !== false; } else { if ($insensitive) { $found = stripos($haystack, $currNeedle) !== false; } else { $found = strpos($haystack, $currNeedle) !== false; } } if ($found) { return true; } } return false; }
php
protected function containString($haystack, $needle, $insensitive = true, $findWords = true) { if (!is_array($needle)) { $needle = array($needle); } foreach ($needle as $currNeedle) { if ($findWords) { $found = $this->wordPos($haystack, $currNeedle, $insensitive) !== false; } else { if ($insensitive) { $found = stripos($haystack, $currNeedle) !== false; } else { $found = strpos($haystack, $currNeedle) !== false; } } if ($found) { return true; } } return false; }
[ "protected", "function", "containString", "(", "$", "haystack", ",", "$", "needle", ",", "$", "insensitive", "=", "true", ",", "$", "findWords", "=", "true", ")", "{", "if", "(", "!", "is_array", "(", "$", "needle", ")", ")", "{", "$", "needle", "=",...
Find if one or more substring is contained in a string. @access protected @param string $haystack The string to search in. @param mixed $needle The string to search for. Can be a string or an array of strings if multiples values are to be searched. @param boolean $insensitive (optional) Determines if we do a case-sensitive search (false) or a case-insensitive one (true). @param boolean $findWords (optional) Determines if the needle should match a word to be found. For example "Bar" would not be found in "FooBar" when true but would be found in "Foo Bar". When set to false, the needle can be found anywhere in the haystack. @return boolean Returns true if the needle (or one of the needles) has been found in the haystack, false otherwise.
[ "Find", "if", "one", "or", "more", "substring", "is", "contained", "in", "a", "string", "." ]
train
https://github.com/Wolfcast/BrowserDetection/blob/9350b2d69aa8dfd2d526000bc0fb52a0baf611d2/lib/BrowserDetection.php#L1576-L1599
Wolfcast/BrowserDetection
lib/BrowserDetection.php
BrowserDetection.cleanVersion
protected function cleanVersion($version) { //Clear anything that is in parentheses (and the parentheses themselves) - will clear started but unclosed ones too $cleanVer = preg_replace('/\([^)]+\)?/', '', $version); //Replace with a space any character which is NOT an alphanumeric, dot (.), hyphen (-), underscore (_) or space $cleanVer = preg_replace('/[^0-9.a-zA-Z_ -]/', ' ', $cleanVer); //Remove trailing and leading spaces $cleanVer = trim($cleanVer); //Remove trailing dot (.), hyphen (-), underscore (_) while (in_array(substr($cleanVer, -1), array('.', '-', '_'))) { $cleanVer = substr($cleanVer, 0, -1); } //Remove leading dot (.), hyphen (-), underscore (_) and character v while (in_array(substr($cleanVer, 0, 1), array('.', '-', '_', 'v', 'V'))) { $cleanVer = substr($cleanVer, 1); } //Remove double spaces if any while (strpos($cleanVer, ' ') !== false) { $cleanVer = str_replace(' ', ' ', $cleanVer); } return trim($cleanVer); }
php
protected function cleanVersion($version) { //Clear anything that is in parentheses (and the parentheses themselves) - will clear started but unclosed ones too $cleanVer = preg_replace('/\([^)]+\)?/', '', $version); //Replace with a space any character which is NOT an alphanumeric, dot (.), hyphen (-), underscore (_) or space $cleanVer = preg_replace('/[^0-9.a-zA-Z_ -]/', ' ', $cleanVer); //Remove trailing and leading spaces $cleanVer = trim($cleanVer); //Remove trailing dot (.), hyphen (-), underscore (_) while (in_array(substr($cleanVer, -1), array('.', '-', '_'))) { $cleanVer = substr($cleanVer, 0, -1); } //Remove leading dot (.), hyphen (-), underscore (_) and character v while (in_array(substr($cleanVer, 0, 1), array('.', '-', '_', 'v', 'V'))) { $cleanVer = substr($cleanVer, 1); } //Remove double spaces if any while (strpos($cleanVer, ' ') !== false) { $cleanVer = str_replace(' ', ' ', $cleanVer); } return trim($cleanVer); }
[ "protected", "function", "cleanVersion", "(", "$", "version", ")", "{", "//Clear anything that is in parentheses (and the parentheses themselves) - will clear started but unclosed ones too", "$", "cleanVer", "=", "preg_replace", "(", "'/\\([^)]+\\)?/'", ",", "''", ",", "$", "ve...
Clean a version string from unwanted characters. @access protected @param string $version The version string to clean. @return string Returns the cleaned version number string.
[ "Clean", "a", "version", "string", "from", "unwanted", "characters", "." ]
train
https://github.com/Wolfcast/BrowserDetection/blob/9350b2d69aa8dfd2d526000bc0fb52a0baf611d2/lib/BrowserDetection.php#L1617-L1642
Wolfcast/BrowserDetection
lib/BrowserDetection.php
BrowserDetection.macVerToStr
protected function macVerToStr($macVer) { //https://en.wikipedia.org/wiki/OS_X#Release_history if ($this->_platformVersion === '10') { return 'Mac OS X'; //Unspecified Mac OS X version } else if ($this->compareVersions($macVer, '10.14') >= 0 && $this->compareVersions($macVer, '10.15') < 0) { return 'macOS Mojave'; } else if ($this->compareVersions($macVer, '10.13') >= 0 && $this->compareVersions($macVer, '10.14') < 0) { return 'macOS High Sierra'; } else if ($this->compareVersions($macVer, '10.12') >= 0 && $this->compareVersions($macVer, '10.13') < 0) { return 'macOS Sierra'; } else if ($this->compareVersions($macVer, '10.11') >= 0 && $this->compareVersions($macVer, '10.12') < 0) { return 'OS X El Capitan'; } else if ($this->compareVersions($macVer, '10.10') >= 0 && $this->compareVersions($macVer, '10.11') < 0) { return 'OS X Yosemite'; } else if ($this->compareVersions($macVer, '10.9') >= 0 && $this->compareVersions($macVer, '10.10') < 0) { return 'OS X Mavericks'; } else if ($this->compareVersions($macVer, '10.8') >= 0 && $this->compareVersions($macVer, '10.9') < 0) { return 'OS X Mountain Lion'; } else if ($this->compareVersions($macVer, '10.7') >= 0 && $this->compareVersions($macVer, '10.8') < 0) { return 'Mac OS X Lion'; } else if ($this->compareVersions($macVer, '10.6') >= 0 && $this->compareVersions($macVer, '10.7') < 0) { return 'Mac OS X Snow Leopard'; } else if ($this->compareVersions($macVer, '10.5') >= 0 && $this->compareVersions($macVer, '10.6') < 0) { return 'Mac OS X Leopard'; } else if ($this->compareVersions($macVer, '10.4') >= 0 && $this->compareVersions($macVer, '10.5') < 0) { return 'Mac OS X Tiger'; } else if ($this->compareVersions($macVer, '10.3') >= 0 && $this->compareVersions($macVer, '10.4') < 0) { return 'Mac OS X Panther'; } else if ($this->compareVersions($macVer, '10.2') >= 0 && $this->compareVersions($macVer, '10.3') < 0) { return 'Mac OS X Jaguar'; } else if ($this->compareVersions($macVer, '10.1') >= 0 && $this->compareVersions($macVer, '10.2') < 0) { return 'Mac OS X Puma'; } else if ($this->compareVersions($macVer, '10.0') >= 0 && $this->compareVersions($macVer, '10.1') < 0) { return 'Mac OS X Cheetah'; } else { return self::PLATFORM_VERSION_UNKNOWN; //Unknown/unnamed Mac OS version } }
php
protected function macVerToStr($macVer) { //https://en.wikipedia.org/wiki/OS_X#Release_history if ($this->_platformVersion === '10') { return 'Mac OS X'; //Unspecified Mac OS X version } else if ($this->compareVersions($macVer, '10.14') >= 0 && $this->compareVersions($macVer, '10.15') < 0) { return 'macOS Mojave'; } else if ($this->compareVersions($macVer, '10.13') >= 0 && $this->compareVersions($macVer, '10.14') < 0) { return 'macOS High Sierra'; } else if ($this->compareVersions($macVer, '10.12') >= 0 && $this->compareVersions($macVer, '10.13') < 0) { return 'macOS Sierra'; } else if ($this->compareVersions($macVer, '10.11') >= 0 && $this->compareVersions($macVer, '10.12') < 0) { return 'OS X El Capitan'; } else if ($this->compareVersions($macVer, '10.10') >= 0 && $this->compareVersions($macVer, '10.11') < 0) { return 'OS X Yosemite'; } else if ($this->compareVersions($macVer, '10.9') >= 0 && $this->compareVersions($macVer, '10.10') < 0) { return 'OS X Mavericks'; } else if ($this->compareVersions($macVer, '10.8') >= 0 && $this->compareVersions($macVer, '10.9') < 0) { return 'OS X Mountain Lion'; } else if ($this->compareVersions($macVer, '10.7') >= 0 && $this->compareVersions($macVer, '10.8') < 0) { return 'Mac OS X Lion'; } else if ($this->compareVersions($macVer, '10.6') >= 0 && $this->compareVersions($macVer, '10.7') < 0) { return 'Mac OS X Snow Leopard'; } else if ($this->compareVersions($macVer, '10.5') >= 0 && $this->compareVersions($macVer, '10.6') < 0) { return 'Mac OS X Leopard'; } else if ($this->compareVersions($macVer, '10.4') >= 0 && $this->compareVersions($macVer, '10.5') < 0) { return 'Mac OS X Tiger'; } else if ($this->compareVersions($macVer, '10.3') >= 0 && $this->compareVersions($macVer, '10.4') < 0) { return 'Mac OS X Panther'; } else if ($this->compareVersions($macVer, '10.2') >= 0 && $this->compareVersions($macVer, '10.3') < 0) { return 'Mac OS X Jaguar'; } else if ($this->compareVersions($macVer, '10.1') >= 0 && $this->compareVersions($macVer, '10.2') < 0) { return 'Mac OS X Puma'; } else if ($this->compareVersions($macVer, '10.0') >= 0 && $this->compareVersions($macVer, '10.1') < 0) { return 'Mac OS X Cheetah'; } else { return self::PLATFORM_VERSION_UNKNOWN; //Unknown/unnamed Mac OS version } }
[ "protected", "function", "macVerToStr", "(", "$", "macVer", ")", "{", "//https://en.wikipedia.org/wiki/OS_X#Release_history", "if", "(", "$", "this", "->", "_platformVersion", "===", "'10'", ")", "{", "return", "'Mac OS X'", ";", "//Unspecified Mac OS X version", "}", ...
Convert the macOS version numbers to the operating system name. For instance '10.7' returns 'Mac OS X Lion'. @access protected @param string $macVer The macOS version numbers as a string. @return string The operating system name or the constant PLATFORM_VERSION_UNKNOWN if nothing match the version numbers.
[ "Convert", "the", "macOS", "version", "numbers", "to", "the", "operating", "system", "name", ".", "For", "instance", "10", ".", "7", "returns", "Mac", "OS", "X", "Lion", "." ]
train
https://github.com/Wolfcast/BrowserDetection/blob/9350b2d69aa8dfd2d526000bc0fb52a0baf611d2/lib/BrowserDetection.php#L1666-L1705
Wolfcast/BrowserDetection
lib/BrowserDetection.php
BrowserDetection.reset
protected function reset() { $this->_agent = ''; $this->_browserName = self::BROWSER_UNKNOWN; $this->_compatibilityViewName = ''; $this->_compatibilityViewVer = ''; $this->_is64bit = false; $this->_isMobile = false; $this->_isRobot = false; $this->_platform = self::PLATFORM_UNKNOWN; $this->_platformVersion = self::PLATFORM_VERSION_UNKNOWN; $this->_version = self::VERSION_UNKNOWN; }
php
protected function reset() { $this->_agent = ''; $this->_browserName = self::BROWSER_UNKNOWN; $this->_compatibilityViewName = ''; $this->_compatibilityViewVer = ''; $this->_is64bit = false; $this->_isMobile = false; $this->_isRobot = false; $this->_platform = self::PLATFORM_UNKNOWN; $this->_platformVersion = self::PLATFORM_VERSION_UNKNOWN; $this->_version = self::VERSION_UNKNOWN; }
[ "protected", "function", "reset", "(", ")", "{", "$", "this", "->", "_agent", "=", "''", ";", "$", "this", "->", "_browserName", "=", "self", "::", "BROWSER_UNKNOWN", ";", "$", "this", "->", "_compatibilityViewName", "=", "''", ";", "$", "this", "->", ...
Reset all the properties of the class. @access protected
[ "Reset", "all", "the", "properties", "of", "the", "class", "." ]
train
https://github.com/Wolfcast/BrowserDetection/blob/9350b2d69aa8dfd2d526000bc0fb52a0baf611d2/lib/BrowserDetection.php#L1722-L1734
Wolfcast/BrowserDetection
lib/BrowserDetection.php
BrowserDetection.safariBuildToSafariVer
protected function safariBuildToSafariVer($version) { $verParts = explode('.', $version); //We need a 3 parts version (version 2 will becomes 2.0.0) while (count($verParts) < 3) { $verParts[] = 0; } foreach ($verParts as $i => $currPart) { $verParts[$i] = $this->parseInt($currPart); } switch ($verParts[0]) { case 419: $result = '2.0.4'; break; case 417: $result = '2.0.3'; break; case 416: $result = '2.0.2'; break; case 412: if ($verParts[1] >= 5) { $result = '2.0.1'; } else { $result = '2.0'; } break; case 312: if ($verParts[1] >= 5) { $result = '1.3.2'; } else { if ($verParts[1] >= 3) { $result = '1.3.1'; } else { $result = '1.3'; } } break; case 125: if ($verParts[1] >= 11) { $result = '1.2.4'; } else { if ($verParts[1] >= 9) { $result = '1.2.3'; } else { if ($verParts[1] >= 7) { $result = '1.2.2'; } else { $result = '1.2'; } } } break; case 100: if ($verParts[1] >= 1) { $result = '1.1.1'; } else { $result = '1.1'; } break; case 85: if ($verParts[1] >= 8) { $result = '1.0.3'; } else { if ($verParts[1] >= 7) { $result = '1.0.2'; } else { $result = '1.0'; } } break; case 73: $result = '0.9'; break; case 51: $result = '0.8.1'; break; case 48: $result = '0.8'; break; default: $result = ''; } return $result; }
php
protected function safariBuildToSafariVer($version) { $verParts = explode('.', $version); //We need a 3 parts version (version 2 will becomes 2.0.0) while (count($verParts) < 3) { $verParts[] = 0; } foreach ($verParts as $i => $currPart) { $verParts[$i] = $this->parseInt($currPart); } switch ($verParts[0]) { case 419: $result = '2.0.4'; break; case 417: $result = '2.0.3'; break; case 416: $result = '2.0.2'; break; case 412: if ($verParts[1] >= 5) { $result = '2.0.1'; } else { $result = '2.0'; } break; case 312: if ($verParts[1] >= 5) { $result = '1.3.2'; } else { if ($verParts[1] >= 3) { $result = '1.3.1'; } else { $result = '1.3'; } } break; case 125: if ($verParts[1] >= 11) { $result = '1.2.4'; } else { if ($verParts[1] >= 9) { $result = '1.2.3'; } else { if ($verParts[1] >= 7) { $result = '1.2.2'; } else { $result = '1.2'; } } } break; case 100: if ($verParts[1] >= 1) { $result = '1.1.1'; } else { $result = '1.1'; } break; case 85: if ($verParts[1] >= 8) { $result = '1.0.3'; } else { if ($verParts[1] >= 7) { $result = '1.0.2'; } else { $result = '1.0'; } } break; case 73: $result = '0.9'; break; case 51: $result = '0.8.1'; break; case 48: $result = '0.8'; break; default: $result = ''; } return $result; }
[ "protected", "function", "safariBuildToSafariVer", "(", "$", "version", ")", "{", "$", "verParts", "=", "explode", "(", "'.'", ",", "$", "version", ")", ";", "//We need a 3 parts version (version 2 will becomes 2.0.0)", "while", "(", "count", "(", "$", "verParts", ...
Convert a Safari build number to a Safari version number. @access protected @param string $version A string representing the version number. @link http://web.archive.org/web/20080514173941/http://developer.apple.com/internet/safari/uamatrix.html @return string Returns the Safari version string. If the version can't be determined, an empty string is returned.
[ "Convert", "a", "Safari", "build", "number", "to", "a", "Safari", "version", "number", "." ]
train
https://github.com/Wolfcast/BrowserDetection/blob/9350b2d69aa8dfd2d526000bc0fb52a0baf611d2/lib/BrowserDetection.php#L1744-L1831
Wolfcast/BrowserDetection
lib/BrowserDetection.php
BrowserDetection.setVersion
protected function setVersion($version) { $cleanVer = $this->cleanVersion($version); if ($cleanVer == '') { $this->_version = self::VERSION_UNKNOWN; } else { $this->_version = $cleanVer; } }
php
protected function setVersion($version) { $cleanVer = $this->cleanVersion($version); if ($cleanVer == '') { $this->_version = self::VERSION_UNKNOWN; } else { $this->_version = $cleanVer; } }
[ "protected", "function", "setVersion", "(", "$", "version", ")", "{", "$", "cleanVer", "=", "$", "this", "->", "cleanVersion", "(", "$", "version", ")", ";", "if", "(", "$", "cleanVer", "==", "''", ")", "{", "$", "this", "->", "_version", "=", "self"...
Set the version of the browser. @access protected @param string $version The version of the browser.
[ "Set", "the", "version", "of", "the", "browser", "." ]
train
https://github.com/Wolfcast/BrowserDetection/blob/9350b2d69aa8dfd2d526000bc0fb52a0baf611d2/lib/BrowserDetection.php#L1898-L1907
Wolfcast/BrowserDetection
lib/BrowserDetection.php
BrowserDetection.webKitBuildToSafariVer
protected function webKitBuildToSafariVer($version) { $verParts = explode('.', $version); //We need a 3 parts version (version 2 will becomes 2.0.0) while (count($verParts) < 3) { $verParts[] = 0; } foreach ($verParts as $i => $currPart) { $verParts[$i] = $this->parseInt($currPart); } switch ($verParts[0]) { case 419: $result = '2.0.4'; break; case 418: if ($verParts[1] >= 8) { $result = '2.0.4'; } else { $result = '2.0.3'; } break; case 417: $result = '2.0.3'; break; case 416: $result = '2.0.2'; break; case 412: if ($verParts[1] >= 7) { $result = '2.0.1'; } else { $result = '2.0'; } break; case 312: if ($verParts[1] >= 8) { $result = '1.3.2'; } else { if ($verParts[1] >= 5) { $result = '1.3.1'; } else { $result = '1.3'; } } break; case 125: if ($this->compareVersions('5.4', $verParts[1] . '.' . $verParts[2]) == -1) { $result = '1.2.4'; //125.5.5+ } else { if ($verParts[1] >= 4) { $result = '1.2.3'; } else { if ($verParts[1] >= 2) { $result = '1.2.2'; } else { $result = '1.2'; } } } break; //WebKit 100 can be either Safari 1.1 (Safari build 100) or 1.1.1 (Safari build 100.1) //for this reason, check the Safari build before the WebKit build. case 100: $result = '1.1.1'; break; case 85: if ($verParts[1] >= 8) { $result = '1.0.3'; } else { if ($verParts[1] >= 7) { //WebKit 85.7 can be either Safari 1.0 (Safari build 85.5) or 1.0.2 (Safari build 85.7) //for this reason, check the Safari build before the WebKit build. $result = '1.0.2'; } else { $result = '1.0'; } } break; case 73: $result = '0.9'; break; case 51: $result = '0.8.1'; break; case 48: $result = '0.8'; break; default: $result = ''; } return $result; }
php
protected function webKitBuildToSafariVer($version) { $verParts = explode('.', $version); //We need a 3 parts version (version 2 will becomes 2.0.0) while (count($verParts) < 3) { $verParts[] = 0; } foreach ($verParts as $i => $currPart) { $verParts[$i] = $this->parseInt($currPart); } switch ($verParts[0]) { case 419: $result = '2.0.4'; break; case 418: if ($verParts[1] >= 8) { $result = '2.0.4'; } else { $result = '2.0.3'; } break; case 417: $result = '2.0.3'; break; case 416: $result = '2.0.2'; break; case 412: if ($verParts[1] >= 7) { $result = '2.0.1'; } else { $result = '2.0'; } break; case 312: if ($verParts[1] >= 8) { $result = '1.3.2'; } else { if ($verParts[1] >= 5) { $result = '1.3.1'; } else { $result = '1.3'; } } break; case 125: if ($this->compareVersions('5.4', $verParts[1] . '.' . $verParts[2]) == -1) { $result = '1.2.4'; //125.5.5+ } else { if ($verParts[1] >= 4) { $result = '1.2.3'; } else { if ($verParts[1] >= 2) { $result = '1.2.2'; } else { $result = '1.2'; } } } break; //WebKit 100 can be either Safari 1.1 (Safari build 100) or 1.1.1 (Safari build 100.1) //for this reason, check the Safari build before the WebKit build. case 100: $result = '1.1.1'; break; case 85: if ($verParts[1] >= 8) { $result = '1.0.3'; } else { if ($verParts[1] >= 7) { //WebKit 85.7 can be either Safari 1.0 (Safari build 85.5) or 1.0.2 (Safari build 85.7) //for this reason, check the Safari build before the WebKit build. $result = '1.0.2'; } else { $result = '1.0'; } } break; case 73: $result = '0.9'; break; case 51: $result = '0.8.1'; break; case 48: $result = '0.8'; break; default: $result = ''; } return $result; }
[ "protected", "function", "webKitBuildToSafariVer", "(", "$", "version", ")", "{", "$", "verParts", "=", "explode", "(", "'.'", ",", "$", "version", ")", ";", "//We need a 3 parts version (version 2 will becomes 2.0.0)", "while", "(", "count", "(", "$", "verParts", ...
Convert a WebKit build number to a Safari version number. @access protected @param string $version A string representing the version number. @link http://web.archive.org/web/20080514173941/http://developer.apple.com/internet/safari/uamatrix.html @return string Returns the Safari version string. If the version can't be determined, an empty string is returned.
[ "Convert", "a", "WebKit", "build", "number", "to", "a", "Safari", "version", "number", "." ]
train
https://github.com/Wolfcast/BrowserDetection/blob/9350b2d69aa8dfd2d526000bc0fb52a0baf611d2/lib/BrowserDetection.php#L1917-L2013
Wolfcast/BrowserDetection
lib/BrowserDetection.php
BrowserDetection.windowsNTVerToStr
protected function windowsNTVerToStr($winVer, $returnServerFlavor = false) { //https://en.wikipedia.org/wiki/List_of_Microsoft_Windows_versions $cleanWinVer = explode('.', $winVer); while (count($cleanWinVer) > 2) { array_pop($cleanWinVer); } $cleanWinVer = implode('.', $cleanWinVer); if ($this->compareVersions($cleanWinVer, '11') >= 0) { //Future versions of Windows return self::PLATFORM_WINDOWS . ' ' . $winVer; } else if ($this->compareVersions($cleanWinVer, '10') >= 0) { //Current version of Windows return $returnServerFlavor ? (self::PLATFORM_WINDOWS . ' Server 2016') : (self::PLATFORM_WINDOWS . ' 10'); } else if ($this->compareVersions($cleanWinVer, '7') < 0) { if ($this->compareVersions($cleanWinVer, '6.3') == 0) { return $returnServerFlavor ? (self::PLATFORM_WINDOWS . ' Server 2012 R2') : (self::PLATFORM_WINDOWS . ' 8.1'); } else if ($this->compareVersions($cleanWinVer, '6.2') == 0) { return $returnServerFlavor ? (self::PLATFORM_WINDOWS . ' Server 2012') : (self::PLATFORM_WINDOWS . ' 8'); } else if ($this->compareVersions($cleanWinVer, '6.1') == 0) { return $returnServerFlavor ? (self::PLATFORM_WINDOWS . ' Server 2008 R2') : (self::PLATFORM_WINDOWS . ' 7'); } else if ($this->compareVersions($cleanWinVer, '6') == 0) { return $returnServerFlavor ? (self::PLATFORM_WINDOWS . ' Server 2008') : (self::PLATFORM_WINDOWS . ' Vista'); } else if ($this->compareVersions($cleanWinVer, '5.2') == 0) { return $returnServerFlavor ? (self::PLATFORM_WINDOWS . ' Server 2003 / ' . self::PLATFORM_WINDOWS . ' Server 2003 R2') : (self::PLATFORM_WINDOWS . ' XP x64 Edition'); } else if ($this->compareVersions($cleanWinVer, '5.1') == 0) { return self::PLATFORM_WINDOWS . ' XP'; } else if ($this->compareVersions($cleanWinVer, '5') == 0) { return self::PLATFORM_WINDOWS . ' 2000'; } else if ($this->compareVersions($cleanWinVer, '5') < 0 && $this->compareVersions($cleanWinVer, '3') >= 0) { return self::PLATFORM_WINDOWS . ' NT ' . $winVer; } } return self::PLATFORM_VERSION_UNKNOWN; //Invalid Windows NT version }
php
protected function windowsNTVerToStr($winVer, $returnServerFlavor = false) { //https://en.wikipedia.org/wiki/List_of_Microsoft_Windows_versions $cleanWinVer = explode('.', $winVer); while (count($cleanWinVer) > 2) { array_pop($cleanWinVer); } $cleanWinVer = implode('.', $cleanWinVer); if ($this->compareVersions($cleanWinVer, '11') >= 0) { //Future versions of Windows return self::PLATFORM_WINDOWS . ' ' . $winVer; } else if ($this->compareVersions($cleanWinVer, '10') >= 0) { //Current version of Windows return $returnServerFlavor ? (self::PLATFORM_WINDOWS . ' Server 2016') : (self::PLATFORM_WINDOWS . ' 10'); } else if ($this->compareVersions($cleanWinVer, '7') < 0) { if ($this->compareVersions($cleanWinVer, '6.3') == 0) { return $returnServerFlavor ? (self::PLATFORM_WINDOWS . ' Server 2012 R2') : (self::PLATFORM_WINDOWS . ' 8.1'); } else if ($this->compareVersions($cleanWinVer, '6.2') == 0) { return $returnServerFlavor ? (self::PLATFORM_WINDOWS . ' Server 2012') : (self::PLATFORM_WINDOWS . ' 8'); } else if ($this->compareVersions($cleanWinVer, '6.1') == 0) { return $returnServerFlavor ? (self::PLATFORM_WINDOWS . ' Server 2008 R2') : (self::PLATFORM_WINDOWS . ' 7'); } else if ($this->compareVersions($cleanWinVer, '6') == 0) { return $returnServerFlavor ? (self::PLATFORM_WINDOWS . ' Server 2008') : (self::PLATFORM_WINDOWS . ' Vista'); } else if ($this->compareVersions($cleanWinVer, '5.2') == 0) { return $returnServerFlavor ? (self::PLATFORM_WINDOWS . ' Server 2003 / ' . self::PLATFORM_WINDOWS . ' Server 2003 R2') : (self::PLATFORM_WINDOWS . ' XP x64 Edition'); } else if ($this->compareVersions($cleanWinVer, '5.1') == 0) { return self::PLATFORM_WINDOWS . ' XP'; } else if ($this->compareVersions($cleanWinVer, '5') == 0) { return self::PLATFORM_WINDOWS . ' 2000'; } else if ($this->compareVersions($cleanWinVer, '5') < 0 && $this->compareVersions($cleanWinVer, '3') >= 0) { return self::PLATFORM_WINDOWS . ' NT ' . $winVer; } } return self::PLATFORM_VERSION_UNKNOWN; //Invalid Windows NT version }
[ "protected", "function", "windowsNTVerToStr", "(", "$", "winVer", ",", "$", "returnServerFlavor", "=", "false", ")", "{", "//https://en.wikipedia.org/wiki/List_of_Microsoft_Windows_versions", "$", "cleanWinVer", "=", "explode", "(", "'.'", ",", "$", "winVer", ")", ";"...
Convert the Windows NT family version numbers to the operating system name. For instance '5.1' returns 'Windows XP'. @access protected @param string $winVer The Windows NT family version numbers as a string. @param boolean $returnServerFlavor (optional) Since some Windows NT versions have the same values, this flag determines if the Server flavor is returned or not. For instance Windows 8.1 and Windows Server 2012 R2 both use version 6.3. @return string The operating system name or the constant PLATFORM_VERSION_UNKNOWN if nothing match the version numbers.
[ "Convert", "the", "Windows", "NT", "family", "version", "numbers", "to", "the", "operating", "system", "name", ".", "For", "instance", "5", ".", "1", "returns", "Windows", "XP", "." ]
train
https://github.com/Wolfcast/BrowserDetection/blob/9350b2d69aa8dfd2d526000bc0fb52a0baf611d2/lib/BrowserDetection.php#L2026-L2063
Wolfcast/BrowserDetection
lib/BrowserDetection.php
BrowserDetection.windowsVerToStr
protected function windowsVerToStr($winVer) { //https://support.microsoft.com/en-us/kb/158238 if ($this->compareVersions($winVer, '4.90') >= 0 && $this->compareVersions($winVer, '4.91') < 0) { return self::PLATFORM_WINDOWS . ' Me'; //Normally range from 4.90.3000 to 4.90.3000A } else if ($this->compareVersions($winVer, '4.10') >= 0 && $this->compareVersions($winVer, '4.11') < 0) { return self::PLATFORM_WINDOWS . ' 98'; //Normally range from 4.10.1998 to 4.10.2222B } else if ($this->compareVersions($winVer, '4') >= 0 && $this->compareVersions($winVer, '4.04') < 0) { return self::PLATFORM_WINDOWS . ' 95'; //Normally range from 4.00.950 to 4.03.1214 } else if ($this->compareVersions($winVer, '3.1') == 0 || $this->compareVersions($winVer, '3.11') == 0) { return self::PLATFORM_WINDOWS . ' ' . $winVer; } else if ($this->compareVersions($winVer, '3.10') == 0) { return self::PLATFORM_WINDOWS . ' 3.1'; } else { return self::PLATFORM_VERSION_UNKNOWN; //Invalid Windows version } }
php
protected function windowsVerToStr($winVer) { //https://support.microsoft.com/en-us/kb/158238 if ($this->compareVersions($winVer, '4.90') >= 0 && $this->compareVersions($winVer, '4.91') < 0) { return self::PLATFORM_WINDOWS . ' Me'; //Normally range from 4.90.3000 to 4.90.3000A } else if ($this->compareVersions($winVer, '4.10') >= 0 && $this->compareVersions($winVer, '4.11') < 0) { return self::PLATFORM_WINDOWS . ' 98'; //Normally range from 4.10.1998 to 4.10.2222B } else if ($this->compareVersions($winVer, '4') >= 0 && $this->compareVersions($winVer, '4.04') < 0) { return self::PLATFORM_WINDOWS . ' 95'; //Normally range from 4.00.950 to 4.03.1214 } else if ($this->compareVersions($winVer, '3.1') == 0 || $this->compareVersions($winVer, '3.11') == 0) { return self::PLATFORM_WINDOWS . ' ' . $winVer; } else if ($this->compareVersions($winVer, '3.10') == 0) { return self::PLATFORM_WINDOWS . ' 3.1'; } else { return self::PLATFORM_VERSION_UNKNOWN; //Invalid Windows version } }
[ "protected", "function", "windowsVerToStr", "(", "$", "winVer", ")", "{", "//https://support.microsoft.com/en-us/kb/158238", "if", "(", "$", "this", "->", "compareVersions", "(", "$", "winVer", ",", "'4.90'", ")", ">=", "0", "&&", "$", "this", "->", "compareVers...
Convert the Windows 3.x & 9x family version numbers to the operating system name. For instance '4.10.1998' returns 'Windows 98'. @access protected @param string $winVer The Windows 3.x or 9x family version numbers as a string. @return string The operating system name or the constant PLATFORM_VERSION_UNKNOWN if nothing match the version numbers.
[ "Convert", "the", "Windows", "3", ".", "x", "&", "9x", "family", "version", "numbers", "to", "the", "operating", "system", "name", ".", "For", "instance", "4", ".", "10", ".", "1998", "returns", "Windows", "98", "." ]
train
https://github.com/Wolfcast/BrowserDetection/blob/9350b2d69aa8dfd2d526000bc0fb52a0baf611d2/lib/BrowserDetection.php#L2073-L2090
Wolfcast/BrowserDetection
lib/BrowserDetection.php
BrowserDetection.wordPos
protected function wordPos($haystack, $needle, $insensitive = true, $offset = 0, &$foundString = NULL) { if ($offset != 0) { $haystack = substr($haystack, $offset); } $parts = explode(' ', $needle); foreach ($parts as $i => $currPart) { $parts[$i] = preg_quote($currPart, '/'); } $regex = '/(?<=\A|[\s\/\\.,;:_()-])' . implode('[\s\/\\.,;:_()-]', $parts) . '(?=[\s\/\\.,;:_()-]|$)/'; if ($insensitive) { $regex .= 'i'; } if (preg_match($regex, $haystack, $matches, PREG_OFFSET_CAPTURE)) { $foundString = $matches[0][0]; return (int)$matches[0][1]; } return false; }
php
protected function wordPos($haystack, $needle, $insensitive = true, $offset = 0, &$foundString = NULL) { if ($offset != 0) { $haystack = substr($haystack, $offset); } $parts = explode(' ', $needle); foreach ($parts as $i => $currPart) { $parts[$i] = preg_quote($currPart, '/'); } $regex = '/(?<=\A|[\s\/\\.,;:_()-])' . implode('[\s\/\\.,;:_()-]', $parts) . '(?=[\s\/\\.,;:_()-]|$)/'; if ($insensitive) { $regex .= 'i'; } if (preg_match($regex, $haystack, $matches, PREG_OFFSET_CAPTURE)) { $foundString = $matches[0][0]; return (int)$matches[0][1]; } return false; }
[ "protected", "function", "wordPos", "(", "$", "haystack", ",", "$", "needle", ",", "$", "insensitive", "=", "true", ",", "$", "offset", "=", "0", ",", "&", "$", "foundString", "=", "NULL", ")", "{", "if", "(", "$", "offset", "!=", "0", ")", "{", ...
Find the position of the first occurrence of a word in a string. @access protected @param string $haystack The string to search in. @param string $needle The string to search for. @param boolean $insensitive (optional) Determines if we do a case-sensitive search (false) or a case-insensitive one (true). @param int $offset If specified, search will start this number of characters counted from the beginning of the string. If the offset is negative, the search will start this number of characters counted from the end of the string. @param string $foundString String buffer that will contain the exact matching needle found. Set to NULL when return value of the function is false. @return mixed Returns the position of the needle (int) if found, false otherwise. Warning this function may return Boolean false, but may also return a non-Boolean value which evaluates to false.
[ "Find", "the", "position", "of", "the", "first", "occurrence", "of", "a", "word", "in", "a", "string", "." ]
train
https://github.com/Wolfcast/BrowserDetection/blob/9350b2d69aa8dfd2d526000bc0fb52a0baf611d2/lib/BrowserDetection.php#L2107-L2129
paragonie/anti-csrf
src/AntiCSRF.php
AntiCSRF.insertToken
public function insertToken(string $lockTo = '', bool $echo = true): string { $token_array = $this->getTokenArray($lockTo); $ret = \implode( \array_map( function(string $key, string $value): string { return "<!--\n-->". "<input type=\"hidden\"" . " name=\"" . $key . "\"" . " value=\"" . self::noHTML($value) . "\"" . " />"; }, \array_keys($token_array), $token_array ) ); if ($echo) { echo $ret; return ''; } return $ret; }
php
public function insertToken(string $lockTo = '', bool $echo = true): string { $token_array = $this->getTokenArray($lockTo); $ret = \implode( \array_map( function(string $key, string $value): string { return "<!--\n-->". "<input type=\"hidden\"" . " name=\"" . $key . "\"" . " value=\"" . self::noHTML($value) . "\"" . " />"; }, \array_keys($token_array), $token_array ) ); if ($echo) { echo $ret; return ''; } return $ret; }
[ "public", "function", "insertToken", "(", "string", "$", "lockTo", "=", "''", ",", "bool", "$", "echo", "=", "true", ")", ":", "string", "{", "$", "token_array", "=", "$", "this", "->", "getTokenArray", "(", "$", "lockTo", ")", ";", "$", "ret", "=", ...
Insert a CSRF token to a form @param string $lockTo This CSRF token is only valid for this HTTP request endpoint @param bool $echo if true, echo instead of returning @return string @throws \Exception @throws \TypeError
[ "Insert", "a", "CSRF", "token", "to", "a", "form" ]
train
https://github.com/paragonie/anti-csrf/blob/b1b861266b04b80108996729e34339444817ef59/src/AntiCSRF.php#L185-L206
paragonie/anti-csrf
src/AntiCSRF.php
AntiCSRF.getTokenArray
public function getTokenArray(string $lockTo = ''): array { if ($this->useNativeSession) { if (!isset($_SESSION[$this->sessionIndex])) { $_SESSION[$this->sessionIndex] = []; } } elseif (!isset($this->session[$this->sessionIndex])) { $this->session[$this->sessionIndex] = []; } if (empty($lockTo)) { /** @var string $lockTo */ $lockTo = isset($this->server['REQUEST_URI']) ? $this->server['REQUEST_URI'] : '/'; } if (\preg_match('#/$#', $lockTo)) { $lockTo = Binary::safeSubstr($lockTo, 0, Binary::safeStrlen($lockTo) - 1); } list($index, $token) = $this->generateToken($lockTo); if ($this->hmac_ip !== false) { // Use HMAC to only allow this particular IP to send this request $token = Base64UrlSafe::encode( \hash_hmac( $this->hashAlgo, isset($this->server['REMOTE_ADDR']) ? (string) $this->server['REMOTE_ADDR'] : '127.0.0.1', (string) Base64UrlSafe::decode($token), true ) ); } return [ $this->formIndex => $index, $this->formToken => $token, ]; }
php
public function getTokenArray(string $lockTo = ''): array { if ($this->useNativeSession) { if (!isset($_SESSION[$this->sessionIndex])) { $_SESSION[$this->sessionIndex] = []; } } elseif (!isset($this->session[$this->sessionIndex])) { $this->session[$this->sessionIndex] = []; } if (empty($lockTo)) { /** @var string $lockTo */ $lockTo = isset($this->server['REQUEST_URI']) ? $this->server['REQUEST_URI'] : '/'; } if (\preg_match('#/$#', $lockTo)) { $lockTo = Binary::safeSubstr($lockTo, 0, Binary::safeStrlen($lockTo) - 1); } list($index, $token) = $this->generateToken($lockTo); if ($this->hmac_ip !== false) { // Use HMAC to only allow this particular IP to send this request $token = Base64UrlSafe::encode( \hash_hmac( $this->hashAlgo, isset($this->server['REMOTE_ADDR']) ? (string) $this->server['REMOTE_ADDR'] : '127.0.0.1', (string) Base64UrlSafe::decode($token), true ) ); } return [ $this->formIndex => $index, $this->formToken => $token, ]; }
[ "public", "function", "getTokenArray", "(", "string", "$", "lockTo", "=", "''", ")", ":", "array", "{", "if", "(", "$", "this", "->", "useNativeSession", ")", "{", "if", "(", "!", "isset", "(", "$", "_SESSION", "[", "$", "this", "->", "sessionIndex", ...
Retrieve a token array for unit testing endpoints @param string $lockTo @return array @throws \Exception @throws \TypeError
[ "Retrieve", "a", "token", "array", "for", "unit", "testing", "endpoints" ]
train
https://github.com/paragonie/anti-csrf/blob/b1b861266b04b80108996729e34339444817ef59/src/AntiCSRF.php#L249-L290
paragonie/anti-csrf
src/AntiCSRF.php
AntiCSRF.validateRequest
public function validateRequest(): bool { if ($this->useNativeSession) { if (!isset($_SESSION[$this->sessionIndex])) { return false; } /** @var array<string, array<string, mixed>> $sess */ $sess =& $_SESSION[$this->sessionIndex]; } else { if (!isset($this->session[$this->sessionIndex])) { return false; } /** @var array<string, array<string, mixed>> $sess */ $sess =& $this->session[$this->sessionIndex]; } if ( empty($this->post[$this->formIndex]) || empty($this->post[$this->formToken]) ) { // User must transmit a complete index/token pair return false; } // Let's pull the POST data /** @var string $index */ $index = $this->post[$this->formIndex]; /** @var string $token */ $token = $this->post[$this->formToken]; if (!\is_string($index) || !\is_string($token)) { return false; } if (!isset($sess[$index])) { // CSRF Token not found return false; } if (!\is_string($index) || !\is_string($token)) { return false; } // Grab the value stored at $index /** @var array<string, mixed> $stored */ $stored = $sess[$index]; // We don't need this anymore if ($this->deleteToken($sess[$index])) { unset($sess[$index]); } // Which form action="" is this token locked to? /** @var string $lockTo */ $lockTo = $this->server[$this->lock_type]; if (\preg_match('#/$#', $lockTo)) { // Trailing slashes are to be ignored $lockTo = Binary::safeSubstr( $lockTo, 0, Binary::safeStrlen($lockTo) - 1 ); } if (!\hash_equals($lockTo, (string) $stored['lockTo'])) { // Form target did not match the request this token is locked to! return false; } // This is the expected token value if ($this->hmac_ip === false) { // We just stored it wholesale /** @var string $expected */ $expected = $stored['token']; } else { // We mixed in the client IP address to generate the output /** @var string $expected */ $expected = Base64UrlSafe::encode( \hash_hmac( $this->hashAlgo, isset($this->server['REMOTE_ADDR']) ? (string) $this->server['REMOTE_ADDR'] : '127.0.0.1', (string) Base64UrlSafe::decode((string) $stored['token']), true ) ); } return \hash_equals($token, $expected); }
php
public function validateRequest(): bool { if ($this->useNativeSession) { if (!isset($_SESSION[$this->sessionIndex])) { return false; } /** @var array<string, array<string, mixed>> $sess */ $sess =& $_SESSION[$this->sessionIndex]; } else { if (!isset($this->session[$this->sessionIndex])) { return false; } /** @var array<string, array<string, mixed>> $sess */ $sess =& $this->session[$this->sessionIndex]; } if ( empty($this->post[$this->formIndex]) || empty($this->post[$this->formToken]) ) { // User must transmit a complete index/token pair return false; } // Let's pull the POST data /** @var string $index */ $index = $this->post[$this->formIndex]; /** @var string $token */ $token = $this->post[$this->formToken]; if (!\is_string($index) || !\is_string($token)) { return false; } if (!isset($sess[$index])) { // CSRF Token not found return false; } if (!\is_string($index) || !\is_string($token)) { return false; } // Grab the value stored at $index /** @var array<string, mixed> $stored */ $stored = $sess[$index]; // We don't need this anymore if ($this->deleteToken($sess[$index])) { unset($sess[$index]); } // Which form action="" is this token locked to? /** @var string $lockTo */ $lockTo = $this->server[$this->lock_type]; if (\preg_match('#/$#', $lockTo)) { // Trailing slashes are to be ignored $lockTo = Binary::safeSubstr( $lockTo, 0, Binary::safeStrlen($lockTo) - 1 ); } if (!\hash_equals($lockTo, (string) $stored['lockTo'])) { // Form target did not match the request this token is locked to! return false; } // This is the expected token value if ($this->hmac_ip === false) { // We just stored it wholesale /** @var string $expected */ $expected = $stored['token']; } else { // We mixed in the client IP address to generate the output /** @var string $expected */ $expected = Base64UrlSafe::encode( \hash_hmac( $this->hashAlgo, isset($this->server['REMOTE_ADDR']) ? (string) $this->server['REMOTE_ADDR'] : '127.0.0.1', (string) Base64UrlSafe::decode((string) $stored['token']), true ) ); } return \hash_equals($token, $expected); }
[ "public", "function", "validateRequest", "(", ")", ":", "bool", "{", "if", "(", "$", "this", "->", "useNativeSession", ")", "{", "if", "(", "!", "isset", "(", "$", "_SESSION", "[", "$", "this", "->", "sessionIndex", "]", ")", ")", "{", "return", "fal...
Validate a request based on $this->session and $this->post data @return bool @throws \TypeError
[ "Validate", "a", "request", "based", "on", "$this", "-", ">", "session", "and", "$this", "-", ">", "post", "data" ]
train
https://github.com/paragonie/anti-csrf/blob/b1b861266b04b80108996729e34339444817ef59/src/AntiCSRF.php#L299-L387
paragonie/anti-csrf
src/AntiCSRF.php
AntiCSRF.reconfigure
public function reconfigure(array $options = []): self { /** @var string $opt */ /** @var string $val */ foreach ($options as $opt => $val) { switch ($opt) { case 'formIndex': case 'formToken': case 'sessionIndex': case 'useNativeSession': case 'recycle_after': case 'hmac_ip': case 'expire_old': /** @psalm-suppress MixedAssignment */ $this->$opt = $val; break; case 'hashAlgo': if (\in_array($val, \hash_algos(), true)) { $this->hashAlgo = (string) $val; } break; case 'lock_type': if (\in_array($val, array('REQUEST_URI','PATH_INFO'), true)) { $this->lock_type = (string) $val; } break; } } return $this; }
php
public function reconfigure(array $options = []): self { /** @var string $opt */ /** @var string $val */ foreach ($options as $opt => $val) { switch ($opt) { case 'formIndex': case 'formToken': case 'sessionIndex': case 'useNativeSession': case 'recycle_after': case 'hmac_ip': case 'expire_old': /** @psalm-suppress MixedAssignment */ $this->$opt = $val; break; case 'hashAlgo': if (\in_array($val, \hash_algos(), true)) { $this->hashAlgo = (string) $val; } break; case 'lock_type': if (\in_array($val, array('REQUEST_URI','PATH_INFO'), true)) { $this->lock_type = (string) $val; } break; } } return $this; }
[ "public", "function", "reconfigure", "(", "array", "$", "options", "=", "[", "]", ")", ":", "self", "{", "/** @var string $opt */", "/** @var string $val */", "foreach", "(", "$", "options", "as", "$", "opt", "=>", "$", "val", ")", "{", "switch", "(", "$",...
Use this to change the configuration settings. Only use this if you know what you are doing. @param array $options @return self
[ "Use", "this", "to", "change", "the", "configuration", "settings", ".", "Only", "use", "this", "if", "you", "know", "what", "you", "are", "doing", "." ]
train
https://github.com/paragonie/anti-csrf/blob/b1b861266b04b80108996729e34339444817ef59/src/AntiCSRF.php#L396-L425
paragonie/anti-csrf
src/AntiCSRF.php
AntiCSRF.generateToken
protected function generateToken(string $lockTo): array { $index = Base64UrlSafe::encode(\random_bytes(18)); $token = Base64UrlSafe::encode(\random_bytes(33)); $new = $this->buildBasicToken([ 'created' => \intval( \date('YmdHis') ), 'uri' => isset($this->server['REQUEST_URI']) ? $this->server['REQUEST_URI'] : $this->server['SCRIPT_NAME'], 'token' => $token ]); if (\preg_match('#/$#', $lockTo)) { $lockTo = Binary::safeSubstr( $lockTo, 0, Binary::safeStrlen($lockTo) - 1 ); } if ($this->useNativeSession) { /** @var array<string, array<string, string|int>> $sess */ $sess =& $_SESSION[$this->sessionIndex]; } else { /** @var array<string, array<string, string|int>> $sess */ $sess =& $this->session[$this->sessionIndex]; } $sess[$index] = $new; $sess[$index]['lockTo'] = $lockTo; $this->recycleTokens(); return [$index, $token]; }
php
protected function generateToken(string $lockTo): array { $index = Base64UrlSafe::encode(\random_bytes(18)); $token = Base64UrlSafe::encode(\random_bytes(33)); $new = $this->buildBasicToken([ 'created' => \intval( \date('YmdHis') ), 'uri' => isset($this->server['REQUEST_URI']) ? $this->server['REQUEST_URI'] : $this->server['SCRIPT_NAME'], 'token' => $token ]); if (\preg_match('#/$#', $lockTo)) { $lockTo = Binary::safeSubstr( $lockTo, 0, Binary::safeStrlen($lockTo) - 1 ); } if ($this->useNativeSession) { /** @var array<string, array<string, string|int>> $sess */ $sess =& $_SESSION[$this->sessionIndex]; } else { /** @var array<string, array<string, string|int>> $sess */ $sess =& $this->session[$this->sessionIndex]; } $sess[$index] = $new; $sess[$index]['lockTo'] = $lockTo; $this->recycleTokens(); return [$index, $token]; }
[ "protected", "function", "generateToken", "(", "string", "$", "lockTo", ")", ":", "array", "{", "$", "index", "=", "Base64UrlSafe", "::", "encode", "(", "\\", "random_bytes", "(", "18", ")", ")", ";", "$", "token", "=", "Base64UrlSafe", "::", "encode", "...
Generate, store, and return the index and token @param string $lockTo What URI endpoint this is valid for @return string[] @throws \TypeError @throws \Exception
[ "Generate", "store", "and", "return", "the", "index", "and", "token" ]
train
https://github.com/paragonie/anti-csrf/blob/b1b861266b04b80108996729e34339444817ef59/src/AntiCSRF.php#L435-L470
paragonie/anti-csrf
src/AntiCSRF.php
AntiCSRF.recycleTokens
protected function recycleTokens() { if (!$this->expire_old) { // This is turned off. return $this; } if ($this->useNativeSession) { /** @var array<string, array<string, string|int>> $sess */ $sess =& $_SESSION[$this->sessionIndex]; } else { /** @var array<string, array<string, string|int>> $sess */ $sess =& $this->session[$this->sessionIndex]; } // Sort by creation time \uasort( $sess, function (array $a, array $b): int { return (int) ($a['created'] <=> $b['created']); } ); while (\count($sess) > $this->recycle_after) { // Let's knock off the oldest one \array_shift($sess); } return $this; }
php
protected function recycleTokens() { if (!$this->expire_old) { // This is turned off. return $this; } if ($this->useNativeSession) { /** @var array<string, array<string, string|int>> $sess */ $sess =& $_SESSION[$this->sessionIndex]; } else { /** @var array<string, array<string, string|int>> $sess */ $sess =& $this->session[$this->sessionIndex]; } // Sort by creation time \uasort( $sess, function (array $a, array $b): int { return (int) ($a['created'] <=> $b['created']); } ); while (\count($sess) > $this->recycle_after) { // Let's knock off the oldest one \array_shift($sess); } return $this; }
[ "protected", "function", "recycleTokens", "(", ")", "{", "if", "(", "!", "$", "this", "->", "expire_old", ")", "{", "// This is turned off.", "return", "$", "this", ";", "}", "if", "(", "$", "this", "->", "useNativeSession", ")", "{", "/** @var array<string,...
Enforce an upper limit on the number of tokens stored in session state by removing the oldest tokens first. @return self
[ "Enforce", "an", "upper", "limit", "on", "the", "number", "of", "tokens", "stored", "in", "session", "state", "by", "removing", "the", "oldest", "tokens", "first", "." ]
train
https://github.com/paragonie/anti-csrf/blob/b1b861266b04b80108996729e34339444817ef59/src/AntiCSRF.php#L478-L504
paragonie/anti-csrf
src/Reusable.php
Reusable.reconfigure
public function reconfigure(array $options = []): AntiCSRF { /** @var string $opt */ /** @var \DateInterval $val */ foreach ($options as $opt => $val) { switch ($opt) { case 'tokenLifetime': if ($val instanceof \DateInterval) { $this->tokenLifetime = $val; } break; } } return parent::reconfigure($options); }
php
public function reconfigure(array $options = []): AntiCSRF { /** @var string $opt */ /** @var \DateInterval $val */ foreach ($options as $opt => $val) { switch ($opt) { case 'tokenLifetime': if ($val instanceof \DateInterval) { $this->tokenLifetime = $val; } break; } } return parent::reconfigure($options); }
[ "public", "function", "reconfigure", "(", "array", "$", "options", "=", "[", "]", ")", ":", "AntiCSRF", "{", "/** @var string $opt */", "/** @var \\DateInterval $val */", "foreach", "(", "$", "options", "as", "$", "opt", "=>", "$", "val", ")", "{", "switch", ...
Use this to change the configuration settings. Only use this if you know what you are doing. @param array $options @return AntiCSRF
[ "Use", "this", "to", "change", "the", "configuration", "settings", ".", "Only", "use", "this", "if", "you", "know", "what", "you", "are", "doing", "." ]
train
https://github.com/paragonie/anti-csrf/blob/b1b861266b04b80108996729e34339444817ef59/src/Reusable.php#L55-L69
ibericode/vat
src/Validator.php
Validator.validateIpAddress
public function validateIpAddress(string $ipAddress) : bool { if ($ipAddress === '') { return false; } return (bool) filter_var($ipAddress, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE); }
php
public function validateIpAddress(string $ipAddress) : bool { if ($ipAddress === '') { return false; } return (bool) filter_var($ipAddress, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE); }
[ "public", "function", "validateIpAddress", "(", "string", "$", "ipAddress", ")", ":", "bool", "{", "if", "(", "$", "ipAddress", "===", "''", ")", "{", "return", "false", ";", "}", "return", "(", "bool", ")", "filter_var", "(", "$", "ipAddress", ",", "F...
Checks whether the given string is a valid public IPv4 or IPv6 address @param string $ipAddress @return bool
[ "Checks", "whether", "the", "given", "string", "is", "a", "valid", "public", "IPv4", "or", "IPv6", "address" ]
train
https://github.com/ibericode/vat/blob/108ca932a35ff2c22807c727ed054f8bce9f6bea/src/Validator.php#L79-L86
ibericode/vat
src/Validator.php
Validator.validateVatNumberFormat
public function validateVatNumberFormat(string $vatNumber) : bool { if ($vatNumber === '') { return false; } $vatNumber = strtoupper($vatNumber); $country = substr($vatNumber, 0, 2); $number = substr($vatNumber, 2); if (! isset($this->patterns[$country]) ) { return false; } $matches = preg_match('/^' . $this->patterns[$country] . '$/', $number) > 0; return $matches; }
php
public function validateVatNumberFormat(string $vatNumber) : bool { if ($vatNumber === '') { return false; } $vatNumber = strtoupper($vatNumber); $country = substr($vatNumber, 0, 2); $number = substr($vatNumber, 2); if (! isset($this->patterns[$country]) ) { return false; } $matches = preg_match('/^' . $this->patterns[$country] . '$/', $number) > 0; return $matches; }
[ "public", "function", "validateVatNumberFormat", "(", "string", "$", "vatNumber", ")", ":", "bool", "{", "if", "(", "$", "vatNumber", "===", "''", ")", "{", "return", "false", ";", "}", "$", "vatNumber", "=", "strtoupper", "(", "$", "vatNumber", ")", ";"...
Validate a VAT number format. This does not check whether the VAT number was really issued. @param string $vatNumber @return boolean
[ "Validate", "a", "VAT", "number", "format", ".", "This", "does", "not", "check", "whether", "the", "VAT", "number", "was", "really", "issued", "." ]
train
https://github.com/ibericode/vat/blob/108ca932a35ff2c22807c727ed054f8bce9f6bea/src/Validator.php#L95-L111
ibericode/vat
src/Validator.php
Validator.validateVatNumber
public function validateVatNumber(string $vatNumber) : bool { return $this->validateVatNumberFormat($vatNumber) && $this->validateVatNumberExistence($vatNumber); }
php
public function validateVatNumber(string $vatNumber) : bool { return $this->validateVatNumberFormat($vatNumber) && $this->validateVatNumberExistence($vatNumber); }
[ "public", "function", "validateVatNumber", "(", "string", "$", "vatNumber", ")", ":", "bool", "{", "return", "$", "this", "->", "validateVatNumberFormat", "(", "$", "vatNumber", ")", "&&", "$", "this", "->", "validateVatNumberExistence", "(", "$", "vatNumber", ...
Validates a VAT number using format + existence check. @param string $vatNumber Either the full VAT number (incl. country) or just the part after the country code. @return boolean @throws Vies\ViesException
[ "Validates", "a", "VAT", "number", "using", "format", "+", "existence", "check", "." ]
train
https://github.com/ibericode/vat/blob/108ca932a35ff2c22807c727ed054f8bce9f6bea/src/Validator.php#L138-L141
ibericode/vat
src/Clients/JsonVatClient.php
JsonVatClient.fetch
public function fetch() : array { $url = 'https://jsonvat.com/'; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_TIMEOUT, 6); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); curl_setopt($ch, CURLOPT_MAXREDIRS, 2); $body = (string) curl_exec($ch); $status = (int) curl_getinfo($ch, CURLINFO_HTTP_CODE); curl_close($ch); if ($body === '' || $status >= 400) { throw new ClientException( "Error fetching rates from {$url}."); } return $this->parseResponse($body); }
php
public function fetch() : array { $url = 'https://jsonvat.com/'; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_TIMEOUT, 6); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); curl_setopt($ch, CURLOPT_MAXREDIRS, 2); $body = (string) curl_exec($ch); $status = (int) curl_getinfo($ch, CURLINFO_HTTP_CODE); curl_close($ch); if ($body === '' || $status >= 400) { throw new ClientException( "Error fetching rates from {$url}."); } return $this->parseResponse($body); }
[ "public", "function", "fetch", "(", ")", ":", "array", "{", "$", "url", "=", "'https://jsonvat.com/'", ";", "$", "ch", "=", "curl_init", "(", ")", ";", "curl_setopt", "(", "$", "ch", ",", "CURLOPT_URL", ",", "$", "url", ")", ";", "curl_setopt", "(", ...
@throws ClientException @return array
[ "@throws", "ClientException" ]
train
https://github.com/ibericode/vat/blob/108ca932a35ff2c22807c727ed054f8bce9f6bea/src/Clients/JsonVatClient.php#L16-L36
ibericode/vat
src/Vies/Client.php
Client.checkVat
public function checkVat(string $countryCode, string $vatNumber) : bool { try { $response = $this->getClient()->checkVat( array( 'countryCode' => $countryCode, 'vatNumber' => $vatNumber ) ); } catch( SoapFault $e ) { throw new ViesException( $e->getMessage(), $e->getCode() ); } return (bool) $response->valid; }
php
public function checkVat(string $countryCode, string $vatNumber) : bool { try { $response = $this->getClient()->checkVat( array( 'countryCode' => $countryCode, 'vatNumber' => $vatNumber ) ); } catch( SoapFault $e ) { throw new ViesException( $e->getMessage(), $e->getCode() ); } return (bool) $response->valid; }
[ "public", "function", "checkVat", "(", "string", "$", "countryCode", ",", "string", "$", "vatNumber", ")", ":", "bool", "{", "try", "{", "$", "response", "=", "$", "this", "->", "getClient", "(", ")", "->", "checkVat", "(", "array", "(", "'countryCode'",...
@param string $countryCode @param string $vatNumber @return bool @throws ViesException
[ "@param", "string", "$countryCode", "@param", "string", "$vatNumber" ]
train
https://github.com/ibericode/vat/blob/108ca932a35ff2c22807c727ed054f8bce9f6bea/src/Vies/Client.php#L44-L58
mpratt/Embera
Lib/Embera/Providers/Silk.php
Silk.fakeResponse
public function fakeResponse() { $url = preg_replace('~^https?://~i', '//', $this->url); $url = preg_replace('~\.silk\.co/(?:explore)/~i', '.silk.co/s/embed/', $url); $html = '<div style="display: inline-block; width: 100%; min-height: {height}px;">'; $html .= '<div style="position: relative; padding-bottom: 100%; padding-top:25px; height: 0;">'; $html .= '<iframe src="' . $url . '?oembed=" style="border:0;position: absolute; top:0; left:0; width: 100%;height:100%; min-height: {height}px;"></iframe>'; $html .= '</div></div>'; return array( 'type' => 'rich', 'provider_name' => 'Silk.co', 'provider_url' => 'https://silk.co', 'html' => $html, ); }
php
public function fakeResponse() { $url = preg_replace('~^https?://~i', '//', $this->url); $url = preg_replace('~\.silk\.co/(?:explore)/~i', '.silk.co/s/embed/', $url); $html = '<div style="display: inline-block; width: 100%; min-height: {height}px;">'; $html .= '<div style="position: relative; padding-bottom: 100%; padding-top:25px; height: 0;">'; $html .= '<iframe src="' . $url . '?oembed=" style="border:0;position: absolute; top:0; left:0; width: 100%;height:100%; min-height: {height}px;"></iframe>'; $html .= '</div></div>'; return array( 'type' => 'rich', 'provider_name' => 'Silk.co', 'provider_url' => 'https://silk.co', 'html' => $html, ); }
[ "public", "function", "fakeResponse", "(", ")", "{", "$", "url", "=", "preg_replace", "(", "'~^https?://~i'", ",", "'//'", ",", "$", "this", "->", "url", ")", ";", "$", "url", "=", "preg_replace", "(", "'~\\.silk\\.co/(?:explore)/~i'", ",", "'.silk.co/s/embed/...
inline {@inheritdoc}
[ "inline", "{" ]
train
https://github.com/mpratt/Embera/blob/84df7a11426c017f1aae493a5994babddffac571/Lib/Embera/Providers/Silk.php#L32-L48
mpratt/Embera
Lib/Embera/Providers/DailyMotion.php
DailyMotion.normalizeUrl
protected function normalizeUrl() { if (preg_match('~dailymotion\.com/(?:embed/)?(?:video|live)/([^/]+)/?~i', $this->url, $matches)) { $this->url = new \Embera\Url('http://www.dailymotion.com/video/' . $matches['1']); } else if (preg_match('~dai\.ly/([^/]+)/?~i', $this->url, $matches)) { $this->url = new \Embera\Url('http://www.dailymotion.com/video/' . $matches['1']); } }
php
protected function normalizeUrl() { if (preg_match('~dailymotion\.com/(?:embed/)?(?:video|live)/([^/]+)/?~i', $this->url, $matches)) { $this->url = new \Embera\Url('http://www.dailymotion.com/video/' . $matches['1']); } else if (preg_match('~dai\.ly/([^/]+)/?~i', $this->url, $matches)) { $this->url = new \Embera\Url('http://www.dailymotion.com/video/' . $matches['1']); } }
[ "protected", "function", "normalizeUrl", "(", ")", "{", "if", "(", "preg_match", "(", "'~dailymotion\\.com/(?:embed/)?(?:video|live)/([^/]+)/?~i'", ",", "$", "this", "->", "url", ",", "$", "matches", ")", ")", "{", "$", "this", "->", "url", "=", "new", "\\", ...
inline {@inheritdoc}
[ "inline", "{" ]
train
https://github.com/mpratt/Embera/blob/84df7a11426c017f1aae493a5994babddffac571/Lib/Embera/Providers/DailyMotion.php#L36-L43
mpratt/Embera
Lib/Embera/Providers/DailyMotion.php
DailyMotion.fakeResponse
public function fakeResponse() { preg_match('~/video/([^/]+)~i', $this->url, $matches); @list($videoId, $videoTitle) = explode('_', $matches['1'], 2); return array( 'type' => 'video', 'provider_name' => 'Dailymotion', 'provider_url' => 'http://www.dailymotion.com', 'title' => (!empty($videoTitle) ? str_replace(array('-', '_'), ' ', $videoTitle) : 'Unknown Title'), 'html' => '<iframe frameborder="0" width="{width}" height="{height}" src="http://www.dailymotion.com/embed/video/' . $videoId . '" allowfullscreen></iframe>' ); }
php
public function fakeResponse() { preg_match('~/video/([^/]+)~i', $this->url, $matches); @list($videoId, $videoTitle) = explode('_', $matches['1'], 2); return array( 'type' => 'video', 'provider_name' => 'Dailymotion', 'provider_url' => 'http://www.dailymotion.com', 'title' => (!empty($videoTitle) ? str_replace(array('-', '_'), ' ', $videoTitle) : 'Unknown Title'), 'html' => '<iframe frameborder="0" width="{width}" height="{height}" src="http://www.dailymotion.com/embed/video/' . $videoId . '" allowfullscreen></iframe>' ); }
[ "public", "function", "fakeResponse", "(", ")", "{", "preg_match", "(", "'~/video/([^/]+)~i'", ",", "$", "this", "->", "url", ",", "$", "matches", ")", ";", "@", "list", "(", "$", "videoId", ",", "$", "videoTitle", ")", "=", "explode", "(", "'_'", ",",...
inline {@inheritdoc}
[ "inline", "{" ]
train
https://github.com/mpratt/Embera/blob/84df7a11426c017f1aae493a5994babddffac571/Lib/Embera/Providers/DailyMotion.php#L46-L59
mpratt/Embera
Lib/Embera/HttpRequest.php
HttpRequest.fetch
public function fetch($url, array $params = array()) { $params = array_merge(array( 'curl' => array(), 'fopen' => array(), ), $params); if (function_exists('curl_init') && $this->config['prefer_curl']) { return $this->curl($url, $params['curl']); } return $this->fileGetContents($url, $params['fopen']); }
php
public function fetch($url, array $params = array()) { $params = array_merge(array( 'curl' => array(), 'fopen' => array(), ), $params); if (function_exists('curl_init') && $this->config['prefer_curl']) { return $this->curl($url, $params['curl']); } return $this->fileGetContents($url, $params['fopen']); }
[ "public", "function", "fetch", "(", "$", "url", ",", "array", "$", "params", "=", "array", "(", ")", ")", "{", "$", "params", "=", "array_merge", "(", "array", "(", "'curl'", "=>", "array", "(", ")", ",", "'fopen'", "=>", "array", "(", ")", ",", ...
Executes http requests @param string $url @param array $params Additional parameters for the respective part @return string @throws Exception when an error ocurred or if no way to do a request exists
[ "Executes", "http", "requests" ]
train
https://github.com/mpratt/Embera/blob/84df7a11426c017f1aae493a5994babddffac571/Lib/Embera/HttpRequest.php#L52-L64
mpratt/Embera
Lib/Embera/HttpRequest.php
HttpRequest.curl
protected function curl($url, array $params = array()) { // Not using array_merge here because that function reindexes numeric keys $options = $params + $this->config['curl'] + array( CURLOPT_USERAGENT => $this->userAgent, CURLOPT_ENCODING => '', CURLOPT_FOLLOWLOCATION => true, ); $options[CURLOPT_URL] = $url; $options[CURLOPT_HEADER] = true; $options[CURLOPT_RETURNTRANSFER] = 1; // CURLOPT_FOLLOWLOCATION doesnt play well with open_basedir/safe_mode if (ini_get('safe_mode') || ini_get('open_basedir')) { $options[CURLOPT_FOLLOWLOCATION] = false; $options[CURLOPT_TIMEOUT] = 15; $this->config['force_redirects'] = true; } $handler = curl_init(); curl_setopt_array($handler, $options); $response = curl_exec($handler); $status = curl_getinfo($handler, CURLINFO_HTTP_CODE); $headerSize = curl_getinfo($handler, CURLINFO_HEADER_SIZE); $header = substr($response, 0, $headerSize); $body = substr($response, $headerSize); curl_close($handler); if ($this->config['force_redirects'] && in_array($status, array('301', '302'))) { if (preg_match('~(?:location|uri): ?([^\n]+)~i', $header, $matches)) { $url = trim($matches['1']); // Relative redirections if (substr($url, 0, 1) == '/') { $parsed = parse_url($options[CURLOPT_URL]); $url = $parsed['scheme'] . '://' . rtrim($parsed['host'], '/') . $url; } return $this->curl($url, $options); } } if (empty($body) || !in_array($status, array('200'))) { throw new \Exception($status . ': Invalid response for ' . $url); } return $body; }
php
protected function curl($url, array $params = array()) { // Not using array_merge here because that function reindexes numeric keys $options = $params + $this->config['curl'] + array( CURLOPT_USERAGENT => $this->userAgent, CURLOPT_ENCODING => '', CURLOPT_FOLLOWLOCATION => true, ); $options[CURLOPT_URL] = $url; $options[CURLOPT_HEADER] = true; $options[CURLOPT_RETURNTRANSFER] = 1; // CURLOPT_FOLLOWLOCATION doesnt play well with open_basedir/safe_mode if (ini_get('safe_mode') || ini_get('open_basedir')) { $options[CURLOPT_FOLLOWLOCATION] = false; $options[CURLOPT_TIMEOUT] = 15; $this->config['force_redirects'] = true; } $handler = curl_init(); curl_setopt_array($handler, $options); $response = curl_exec($handler); $status = curl_getinfo($handler, CURLINFO_HTTP_CODE); $headerSize = curl_getinfo($handler, CURLINFO_HEADER_SIZE); $header = substr($response, 0, $headerSize); $body = substr($response, $headerSize); curl_close($handler); if ($this->config['force_redirects'] && in_array($status, array('301', '302'))) { if (preg_match('~(?:location|uri): ?([^\n]+)~i', $header, $matches)) { $url = trim($matches['1']); // Relative redirections if (substr($url, 0, 1) == '/') { $parsed = parse_url($options[CURLOPT_URL]); $url = $parsed['scheme'] . '://' . rtrim($parsed['host'], '/') . $url; } return $this->curl($url, $options); } } if (empty($body) || !in_array($status, array('200'))) { throw new \Exception($status . ': Invalid response for ' . $url); } return $body; }
[ "protected", "function", "curl", "(", "$", "url", ",", "array", "$", "params", "=", "array", "(", ")", ")", "{", "// Not using array_merge here because that function reindexes numeric keys", "$", "options", "=", "$", "params", "+", "$", "this", "->", "config", "...
Uses Curl to fetch data from an url @param string $url @param array $params Additional parameters for the respective part @return string @throws Exception when the returned status code is not 200 or no data was found
[ "Uses", "Curl", "to", "fetch", "data", "from", "an", "url" ]
train
https://github.com/mpratt/Embera/blob/84df7a11426c017f1aae493a5994babddffac571/Lib/Embera/HttpRequest.php#L75-L127
mpratt/Embera
Lib/Embera/HttpRequest.php
HttpRequest.fileGetContents
protected function fileGetContents($url, array $params = array()) { if (!ini_get('allow_url_fopen')) { throw new \Exception('Could not execute lookup, allow_url_fopen is disabled'); } if (!filter_var($url, FILTER_VALIDATE_URL)) { throw new \Exception('Invalid url ' . $url); } $defaultOptions = array( 'method' => 'GET', 'user_agent' => $this->userAgent, 'follow_location' => 1, 'max_redirects' => 20, 'timeout' => 40 ); $context = array('http' => array_merge($defaultOptions, $this->config['fopen'], $params)); if ($data = file_get_contents($url, false, stream_context_create($context))) { return $data; } throw new \Exception('Invalid Server Response from ' . $url); }
php
protected function fileGetContents($url, array $params = array()) { if (!ini_get('allow_url_fopen')) { throw new \Exception('Could not execute lookup, allow_url_fopen is disabled'); } if (!filter_var($url, FILTER_VALIDATE_URL)) { throw new \Exception('Invalid url ' . $url); } $defaultOptions = array( 'method' => 'GET', 'user_agent' => $this->userAgent, 'follow_location' => 1, 'max_redirects' => 20, 'timeout' => 40 ); $context = array('http' => array_merge($defaultOptions, $this->config['fopen'], $params)); if ($data = file_get_contents($url, false, stream_context_create($context))) { return $data; } throw new \Exception('Invalid Server Response from ' . $url); }
[ "protected", "function", "fileGetContents", "(", "$", "url", ",", "array", "$", "params", "=", "array", "(", ")", ")", "{", "if", "(", "!", "ini_get", "(", "'allow_url_fopen'", ")", ")", "{", "throw", "new", "\\", "Exception", "(", "'Could not execute look...
Uses file_get_contents to fetch data from an url @param string $url @param array $params Additional parameters for the respective part @return string @throws Exception when allow_url_fopen is disabled or when no data was returned
[ "Uses", "file_get_contents", "to", "fetch", "data", "from", "an", "url" ]
train
https://github.com/mpratt/Embera/blob/84df7a11426c017f1aae493a5994babddffac571/Lib/Embera/HttpRequest.php#L138-L162
mpratt/Embera
Lib/Embera/Embera.php
Embera.autoEmbed
public function autoEmbed($body = null) { if (!is_string($body)) { $this->errors[] = 'For auto-embedding purposes, the input must be a string'; } elseif ($data = $this->getUrlInfo($body)) { $table = array(); foreach ($data as $url => $service) { if (!empty($service['html'])) { $table[$url] = $service['html']; } } // Determine wether the body looks like HTML or just plain text. if (strpos($body, '>') !== false) { $processor = new \Embera\HtmlProcessor($this->config['ignore_tags'], $table); return $processor->process($body); } return strtr($body, $table); } return $body; }
php
public function autoEmbed($body = null) { if (!is_string($body)) { $this->errors[] = 'For auto-embedding purposes, the input must be a string'; } elseif ($data = $this->getUrlInfo($body)) { $table = array(); foreach ($data as $url => $service) { if (!empty($service['html'])) { $table[$url] = $service['html']; } } // Determine wether the body looks like HTML or just plain text. if (strpos($body, '>') !== false) { $processor = new \Embera\HtmlProcessor($this->config['ignore_tags'], $table); return $processor->process($body); } return strtr($body, $table); } return $body; }
[ "public", "function", "autoEmbed", "(", "$", "body", "=", "null", ")", "{", "if", "(", "!", "is_string", "(", "$", "body", ")", ")", "{", "$", "this", "->", "errors", "[", "]", "=", "'For auto-embedding purposes, the input must be a string'", ";", "}", "el...
Embeds known/available services into the given text. @param string $body @return string
[ "Embeds", "known", "/", "available", "services", "into", "the", "given", "text", "." ]
train
https://github.com/mpratt/Embera/blob/84df7a11426c017f1aae493a5994babddffac571/Lib/Embera/Embera.php#L100-L122
mpratt/Embera
Lib/Embera/Embera.php
Embera.getUrlInfo
public function getUrlInfo($body = null) { $results = array(); if ($providers = $this->getProviders($body)) { foreach ($providers as $url => $service) { $results[$url] = $service->getInfo(); $this->errors = array_merge($this->errors, $service->getErrors()); } } return array_filter($results); }
php
public function getUrlInfo($body = null) { $results = array(); if ($providers = $this->getProviders($body)) { foreach ($providers as $url => $service) { $results[$url] = $service->getInfo(); $this->errors = array_merge($this->errors, $service->getErrors()); } } return array_filter($results); }
[ "public", "function", "getUrlInfo", "(", "$", "body", "=", "null", ")", "{", "$", "results", "=", "array", "(", ")", ";", "if", "(", "$", "providers", "=", "$", "this", "->", "getProviders", "(", "$", "body", ")", ")", "{", "foreach", "(", "$", "...
Finds all the information about a url (or a collection of urls) @param string|array $body An array or string with urls @return array
[ "Finds", "all", "the", "information", "about", "a", "url", "(", "or", "a", "collection", "of", "urls", ")" ]
train
https://github.com/mpratt/Embera/blob/84df7a11426c017f1aae493a5994babddffac571/Lib/Embera/Embera.php#L130-L141
mpratt/Embera
Lib/Embera/Embera.php
Embera.getProviders
protected function getProviders($body = '') { $regex = ($this->config['use_embed_prefix'] === true ? $this->urlEmbedRegex : $this->urlRegex); if (is_array($body)) { $body = array_filter($body, function ($arr) use ($regex) { return preg_match($regex, $arr); }); $services = $this->providers->getAll($body); } elseif (preg_match_all($regex, $body, $matches)) { $services = $this->providers->getAll($matches['0']); } else { return array(); } return $this->clean($services); }
php
protected function getProviders($body = '') { $regex = ($this->config['use_embed_prefix'] === true ? $this->urlEmbedRegex : $this->urlRegex); if (is_array($body)) { $body = array_filter($body, function ($arr) use ($regex) { return preg_match($regex, $arr); }); $services = $this->providers->getAll($body); } elseif (preg_match_all($regex, $body, $matches)) { $services = $this->providers->getAll($matches['0']); } else { return array(); } return $this->clean($services); }
[ "protected", "function", "getProviders", "(", "$", "body", "=", "''", ")", "{", "$", "regex", "=", "(", "$", "this", "->", "config", "[", "'use_embed_prefix'", "]", "===", "true", "?", "$", "this", "->", "urlEmbedRegex", ":", "$", "this", "->", "urlReg...
Finds all the valid urls inside the given text, compares which are allowed and returns an array with the detected providers @param null|string|array $body An array or string with Urls @return array
[ "Finds", "all", "the", "valid", "urls", "inside", "the", "given", "text", "compares", "which", "are", "allowed", "and", "returns", "an", "array", "with", "the", "detected", "providers" ]
train
https://github.com/mpratt/Embera/blob/84df7a11426c017f1aae493a5994babddffac571/Lib/Embera/Embera.php#L151-L168
mpratt/Embera
Lib/Embera/Embera.php
Embera.clean
protected function clean(array $services = array()) { if (empty($services)) { return array(); } if (!empty($this->config['allow'])) { $allow = array_map('strtolower', (array) $this->config['allow']); $services = array_filter($services, function ($arr) use ($allow) { $serviceName = strtolower(basename(str_replace('\\', '/', get_class($arr)))); return (in_array($serviceName, $allow)); }); } if (!empty($services) && !empty($this->config['deny'])) { $deny = array_map('strtolower', (array) $this->config['deny']); $services = array_filter($services, function ($arr) use ($deny) { $serviceName = strtolower(basename(str_replace('\\', '/', get_class($arr)))); return (!in_array($serviceName, $deny)); }); } return (array) $services; }
php
protected function clean(array $services = array()) { if (empty($services)) { return array(); } if (!empty($this->config['allow'])) { $allow = array_map('strtolower', (array) $this->config['allow']); $services = array_filter($services, function ($arr) use ($allow) { $serviceName = strtolower(basename(str_replace('\\', '/', get_class($arr)))); return (in_array($serviceName, $allow)); }); } if (!empty($services) && !empty($this->config['deny'])) { $deny = array_map('strtolower', (array) $this->config['deny']); $services = array_filter($services, function ($arr) use ($deny) { $serviceName = strtolower(basename(str_replace('\\', '/', get_class($arr)))); return (!in_array($serviceName, $deny)); }); } return (array) $services; }
[ "protected", "function", "clean", "(", "array", "$", "services", "=", "array", "(", ")", ")", "{", "if", "(", "empty", "(", "$", "services", ")", ")", "{", "return", "array", "(", ")", ";", "}", "if", "(", "!", "empty", "(", "$", "this", "->", ...
Strips invalid providers from the list @param array $services @return array
[ "Strips", "invalid", "providers", "from", "the", "list" ]
train
https://github.com/mpratt/Embera/blob/84df7a11426c017f1aae493a5994babddffac571/Lib/Embera/Embera.php#L189-L212
mpratt/Embera
Lib/Embera/Providers/TheySaidSo.php
TheySaidSo.validateUrl
protected function validateUrl() { $this->url->stripQueryString(); $this->url->stripLastSlash(); $this->url->stripWWW(); $this->url->convertToHttps(); return (preg_match('~theysaidso\.com/(?:i|quote)/(?:[^/]+)$~i', $this->url)); }
php
protected function validateUrl() { $this->url->stripQueryString(); $this->url->stripLastSlash(); $this->url->stripWWW(); $this->url->convertToHttps(); return (preg_match('~theysaidso\.com/(?:i|quote)/(?:[^/]+)$~i', $this->url)); }
[ "protected", "function", "validateUrl", "(", ")", "{", "$", "this", "->", "url", "->", "stripQueryString", "(", ")", ";", "$", "this", "->", "url", "->", "stripLastSlash", "(", ")", ";", "$", "this", "->", "url", "->", "stripWWW", "(", ")", ";", "$",...
inline {@inheritdoc}
[ "inline", "{" ]
train
https://github.com/mpratt/Embera/blob/84df7a11426c017f1aae493a5994babddffac571/Lib/Embera/Providers/TheySaidSo.php#L25-L33
mpratt/Embera
Lib/Embera/Providers/TheySaidSo.php
TheySaidSo.modifyResponse
protected function modifyResponse(array $response = array()) { if (empty($response['html'])) { if ($response['type'] == 'photo') { $response['html'] = sprintf('<img src="%s" alt="" title="" class="embera-img-theysaidso" />', $response['url']); } else { $response['html'] = sprintf('<a href="%s" class="embera-link-theysaidso" title="">%s</a>', $response['url'], $response['url']); } } return $response; }
php
protected function modifyResponse(array $response = array()) { if (empty($response['html'])) { if ($response['type'] == 'photo') { $response['html'] = sprintf('<img src="%s" alt="" title="" class="embera-img-theysaidso" />', $response['url']); } else { $response['html'] = sprintf('<a href="%s" class="embera-link-theysaidso" title="">%s</a>', $response['url'], $response['url']); } } return $response; }
[ "protected", "function", "modifyResponse", "(", "array", "$", "response", "=", "array", "(", ")", ")", "{", "if", "(", "empty", "(", "$", "response", "[", "'html'", "]", ")", ")", "{", "if", "(", "$", "response", "[", "'type'", "]", "==", "'photo'", ...
inline {@inheritdoc}
[ "inline", "{" ]
train
https://github.com/mpratt/Embera/blob/84df7a11426c017f1aae493a5994babddffac571/Lib/Embera/Providers/TheySaidSo.php#L36-L47
mpratt/Embera
Lib/Embera/Providers/Didacte.php
Didacte.getInfo
public function getInfo() { preg_match('~//([^ ]+)\.didacte\.com/a/course/~i', $this->url, $m); $this->apiUrl = str_replace('{m}', $m['1'], $this->apiUrl); return parent::getInfo(); }
php
public function getInfo() { preg_match('~//([^ ]+)\.didacte\.com/a/course/~i', $this->url, $m); $this->apiUrl = str_replace('{m}', $m['1'], $this->apiUrl); return parent::getInfo(); }
[ "public", "function", "getInfo", "(", ")", "{", "preg_match", "(", "'~//([^ ]+)\\.didacte\\.com/a/course/~i'", ",", "$", "this", "->", "url", ",", "$", "m", ")", ";", "$", "this", "->", "apiUrl", "=", "str_replace", "(", "'{m}'", ",", "$", "m", "[", "'1'...
inline {@inheritdoc} Im overriding this method because the oembed endpoint depends on the subdomain of the oembed response.
[ "inline", "{", "@inheritdoc", "}" ]
train
https://github.com/mpratt/Embera/blob/84df7a11426c017f1aae493a5994babddffac571/Lib/Embera/Providers/Didacte.php#L36-L41
mpratt/Embera
Lib/Embera/FakeResponse.php
FakeResponse.buildResponse
public function buildResponse() { $return = array(); foreach ($this->response as $k => $v) { $return[$k] = str_replace(array_map(function ($name){ return '{' . $name . '}'; }, array_keys($this->config['fake'])), array_values($this->config['fake']), $v); } return $return; }
php
public function buildResponse() { $return = array(); foreach ($this->response as $k => $v) { $return[$k] = str_replace(array_map(function ($name){ return '{' . $name . '}'; }, array_keys($this->config['fake'])), array_values($this->config['fake']), $v); } return $return; }
[ "public", "function", "buildResponse", "(", ")", "{", "$", "return", "=", "array", "(", ")", ";", "foreach", "(", "$", "this", "->", "response", "as", "$", "k", "=>", "$", "v", ")", "{", "$", "return", "[", "$", "k", "]", "=", "str_replace", "(",...
Builds the fake response. This replaces placeholders that are present in $config['fake'] into the response array @return array
[ "Builds", "the", "fake", "response", ".", "This", "replaces", "placeholders", "that", "are", "present", "in", "$config", "[", "fake", "]", "into", "the", "response", "array" ]
train
https://github.com/mpratt/Embera/blob/84df7a11426c017f1aae493a5994babddffac571/Lib/Embera/FakeResponse.php#L69-L80
mpratt/Embera
Lib/Embera/Providers/PollDaddy.php
PollDaddy.validateUrl
protected function validateUrl() { $this->url->convertToHttp(); $this->url->stripWWW(); return (preg_match('~polldaddy\.com/(?:poll|s|ratings)/(?:[^/]+)/?$~i', $this->url)); }
php
protected function validateUrl() { $this->url->convertToHttp(); $this->url->stripWWW(); return (preg_match('~polldaddy\.com/(?:poll|s|ratings)/(?:[^/]+)/?$~i', $this->url)); }
[ "protected", "function", "validateUrl", "(", ")", "{", "$", "this", "->", "url", "->", "convertToHttp", "(", ")", ";", "$", "this", "->", "url", "->", "stripWWW", "(", ")", ";", "return", "(", "preg_match", "(", "'~polldaddy\\.com/(?:poll|s|ratings)/(?:[^/]+)/...
inline {@inheritdoc}
[ "inline", "{" ]
train
https://github.com/mpratt/Embera/blob/84df7a11426c017f1aae493a5994babddffac571/Lib/Embera/Providers/PollDaddy.php#L30-L36
mpratt/Embera
Lib/Embera/Adapters/Service.php
Service.getInfo
public function getInfo() { try { if ($res = $this->oembed->getResourceInfo($this->config['oembed'], $this->apiUrl, (string) $this->url, $this->config['params'])) { return $this->modifyResponse($res); } } catch (\Exception $e) { $this->errors[] = $e->getMessage(); } /** * Use fakeResponses when the oembed setting is null or false * If the oembed config is true, the user strictly wants real responses */ if (!$this->config['oembed'] && $response = $this->fakeResponse()) { $fakeResponse = new \Embera\FakeResponse($this->config, $response); return $this->modifyResponse($fakeResponse->buildResponse()); } return array(); }
php
public function getInfo() { try { if ($res = $this->oembed->getResourceInfo($this->config['oembed'], $this->apiUrl, (string) $this->url, $this->config['params'])) { return $this->modifyResponse($res); } } catch (\Exception $e) { $this->errors[] = $e->getMessage(); } /** * Use fakeResponses when the oembed setting is null or false * If the oembed config is true, the user strictly wants real responses */ if (!$this->config['oembed'] && $response = $this->fakeResponse()) { $fakeResponse = new \Embera\FakeResponse($this->config, $response); return $this->modifyResponse($fakeResponse->buildResponse()); } return array(); }
[ "public", "function", "getInfo", "(", ")", "{", "try", "{", "if", "(", "$", "res", "=", "$", "this", "->", "oembed", "->", "getResourceInfo", "(", "$", "this", "->", "config", "[", "'oembed'", "]", ",", "$", "this", "->", "apiUrl", ",", "(", "strin...
Gets the information from an Oembed provider when this fails, it tries to provide a fakeResponse. Returns an associative array with a (common) Oembed response. @return array
[ "Gets", "the", "information", "from", "an", "Oembed", "provider", "when", "this", "fails", "it", "tries", "to", "provide", "a", "fakeResponse", ".", "Returns", "an", "associative", "array", "with", "a", "(", "common", ")", "Oembed", "response", "." ]
train
https://github.com/mpratt/Embera/blob/84df7a11426c017f1aae493a5994babddffac571/Lib/Embera/Adapters/Service.php#L86-L108
mpratt/Embera
Lib/Embera/Providers/Spotify.php
Spotify.validateUrl
protected function validateUrl() { return ( preg_match('~spotify\.com/(?:track|album)/(?:[^/]+)(?:/[^/]*)?$~i', $this->url) || preg_match('~spotify\.com/user/(?:[^/]+)/playlist/(?:[^/]+)/?$~i', $this->url) || preg_match('~spoti\.fi/(?:[^/]+)$~i', $this->url) ); }
php
protected function validateUrl() { return ( preg_match('~spotify\.com/(?:track|album)/(?:[^/]+)(?:/[^/]*)?$~i', $this->url) || preg_match('~spotify\.com/user/(?:[^/]+)/playlist/(?:[^/]+)/?$~i', $this->url) || preg_match('~spoti\.fi/(?:[^/]+)$~i', $this->url) ); }
[ "protected", "function", "validateUrl", "(", ")", "{", "return", "(", "preg_match", "(", "'~spotify\\.com/(?:track|album)/(?:[^/]+)(?:/[^/]*)?$~i'", ",", "$", "this", "->", "url", ")", "||", "preg_match", "(", "'~spotify\\.com/user/(?:[^/]+)/playlist/(?:[^/]+)/?$~i'", ",", ...
inline {@inheritdoc}
[ "inline", "{" ]
train
https://github.com/mpratt/Embera/blob/84df7a11426c017f1aae493a5994babddffac571/Lib/Embera/Providers/Spotify.php#L24-L31
mpratt/Embera
Lib/Embera/Providers/Spotify.php
Spotify.normalizeUrl
protected function normalizeUrl() { $this->url->convertToHttps(); $this->url->stripQueryString(); $this->url->stripLastSlash(); if (preg_match('~spotify\.com/(track|album)/([^/]+)/(?:[^/]*)$~i', $this->url, $matches)) { $this->url = new \Embera\Url('https://play.spotify.com/' . $matches['1'] . '/' . $matches['2']); } }
php
protected function normalizeUrl() { $this->url->convertToHttps(); $this->url->stripQueryString(); $this->url->stripLastSlash(); if (preg_match('~spotify\.com/(track|album)/([^/]+)/(?:[^/]*)$~i', $this->url, $matches)) { $this->url = new \Embera\Url('https://play.spotify.com/' . $matches['1'] . '/' . $matches['2']); } }
[ "protected", "function", "normalizeUrl", "(", ")", "{", "$", "this", "->", "url", "->", "convertToHttps", "(", ")", ";", "$", "this", "->", "url", "->", "stripQueryString", "(", ")", ";", "$", "this", "->", "url", "->", "stripLastSlash", "(", ")", ";",...
inline {@inheritdoc}
[ "inline", "{" ]
train
https://github.com/mpratt/Embera/blob/84df7a11426c017f1aae493a5994babddffac571/Lib/Embera/Providers/Spotify.php#L34-L44
mpratt/Embera
Lib/Embera/Providers/Spotify.php
Spotify.fakeResponse
public function fakeResponse() { if (preg_match('~spoti\.fi~i', $this->url)) { return array(); } preg_match('~/(track|album|user)/.+~i', $this->url, $matches); $code = str_replace('/', ':', rtrim($matches['0'], '/ ')); return array( 'type' => 'rich', 'provider_name' => 'Spotify', 'provider_url' => 'https://www.spotify.com', 'title' => 'Unknown title', 'html' => '<iframe src="https://embed.spotify.com/?uri=spotify' . $code . '" width="{width}" height="{height}" frameborder="0" allowtransparency="true"></iframe>', ); }
php
public function fakeResponse() { if (preg_match('~spoti\.fi~i', $this->url)) { return array(); } preg_match('~/(track|album|user)/.+~i', $this->url, $matches); $code = str_replace('/', ':', rtrim($matches['0'], '/ ')); return array( 'type' => 'rich', 'provider_name' => 'Spotify', 'provider_url' => 'https://www.spotify.com', 'title' => 'Unknown title', 'html' => '<iframe src="https://embed.spotify.com/?uri=spotify' . $code . '" width="{width}" height="{height}" frameborder="0" allowtransparency="true"></iframe>', ); }
[ "public", "function", "fakeResponse", "(", ")", "{", "if", "(", "preg_match", "(", "'~spoti\\.fi~i'", ",", "$", "this", "->", "url", ")", ")", "{", "return", "array", "(", ")", ";", "}", "preg_match", "(", "'~/(track|album|user)/.+~i'", ",", "$", "this", ...
inline {@inheritdoc}
[ "inline", "{" ]
train
https://github.com/mpratt/Embera/blob/84df7a11426c017f1aae493a5994babddffac571/Lib/Embera/Providers/Spotify.php#L47-L63
mpratt/Embera
Lib/Embera/Providers/Issuu.php
Issuu.fakeResponse
public function fakeResponse() { $queryString = parse_url($this->url, PHP_URL_QUERY); parse_str($queryString, $q); if (isset($q['e']) && preg_match('~^(?:[a-z0-9\/]+)$~i', $q['e'])) { $html = '<div data-configid="' . $q['e'] . '" style="width: {width}px; height: {height}px" class="issuuembed"></div>'; $html .= '<script type="text/javascript" src="//e.issuu.com/embed.js" async="true"></script>'; return array( 'type' => 'rich', 'provider_name' => 'Issuu', 'provider_url' => 'https://issuu.com', 'html' => $html ); } }
php
public function fakeResponse() { $queryString = parse_url($this->url, PHP_URL_QUERY); parse_str($queryString, $q); if (isset($q['e']) && preg_match('~^(?:[a-z0-9\/]+)$~i', $q['e'])) { $html = '<div data-configid="' . $q['e'] . '" style="width: {width}px; height: {height}px" class="issuuembed"></div>'; $html .= '<script type="text/javascript" src="//e.issuu.com/embed.js" async="true"></script>'; return array( 'type' => 'rich', 'provider_name' => 'Issuu', 'provider_url' => 'https://issuu.com', 'html' => $html ); } }
[ "public", "function", "fakeResponse", "(", ")", "{", "$", "queryString", "=", "parse_url", "(", "$", "this", "->", "url", ",", "PHP_URL_QUERY", ")", ";", "parse_str", "(", "$", "queryString", ",", "$", "q", ")", ";", "if", "(", "isset", "(", "$", "q"...
inline {@inheritdoc}
[ "inline", "{" ]
train
https://github.com/mpratt/Embera/blob/84df7a11426c017f1aae493a5994babddffac571/Lib/Embera/Providers/Issuu.php#L30-L46
mpratt/Embera
Lib/Embera/Providers/NFB.php
NFB.modifyResponse
protected function modifyResponse(array $response = array()) { if (!empty($response['html'])) { // The html response comes "encoded" ... booooo :(, need to decode in order to work.. // Bad API, bad bad bad! $response['html'] = html_entity_decode($response['html'], ENT_QUOTES, 'UTF-8'); $response['html'] = preg_replace('~<p(.*)</p>~is', '', $response['html']); } return $response; }
php
protected function modifyResponse(array $response = array()) { if (!empty($response['html'])) { // The html response comes "encoded" ... booooo :(, need to decode in order to work.. // Bad API, bad bad bad! $response['html'] = html_entity_decode($response['html'], ENT_QUOTES, 'UTF-8'); $response['html'] = preg_replace('~<p(.*)</p>~is', '', $response['html']); } return $response; }
[ "protected", "function", "modifyResponse", "(", "array", "$", "response", "=", "array", "(", ")", ")", "{", "if", "(", "!", "empty", "(", "$", "response", "[", "'html'", "]", ")", ")", "{", "// The html response comes \"encoded\" ... booooo :(, need to decode in o...
inline {@inheritdoc}
[ "inline", "{" ]
train
https://github.com/mpratt/Embera/blob/84df7a11426c017f1aae493a5994babddffac571/Lib/Embera/Providers/NFB.php#L40-L51
mpratt/Embera
Lib/Embera/Oembed.php
Oembed.getResourceInfo
public function getResourceInfo($behaviour, $apiUrl, $url, array $params = array()) { if ($behaviour === false) { return array(); } return $this->lookup($this->constructUrl($apiUrl, array_merge($params, array('url' => $url)))); }
php
public function getResourceInfo($behaviour, $apiUrl, $url, array $params = array()) { if ($behaviour === false) { return array(); } return $this->lookup($this->constructUrl($apiUrl, array_merge($params, array('url' => $url)))); }
[ "public", "function", "getResourceInfo", "(", "$", "behaviour", ",", "$", "apiUrl", ",", "$", "url", ",", "array", "$", "params", "=", "array", "(", ")", ")", "{", "if", "(", "$", "behaviour", "===", "false", ")", "{", "return", "array", "(", ")", ...
Gets information about a resource @param bool $behaviour Wether or not to use fake responses only @param string $apiUrl The Url to the Oembed provider @param string $url The original url, we want information from @param array $params An associative array with parameters to be sent to the Oembed provider. @return array
[ "Gets", "information", "about", "a", "resource" ]
train
https://github.com/mpratt/Embera/blob/84df7a11426c017f1aae493a5994babddffac571/Lib/Embera/Oembed.php#L47-L54