id
int32
0
241k
repo
stringlengths
6
63
path
stringlengths
5
140
func_name
stringlengths
3
151
original_string
stringlengths
84
13k
language
stringclasses
1 value
code
stringlengths
84
13k
code_tokens
list
docstring
stringlengths
3
47.2k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
91
247
210,200
matomo-org/matomo
core/View.php
View.singleReport
public static function singleReport($title, $reportHtml) { $view = new View('@CoreHome/_singleReport'); $view->title = $title; $view->report = $reportHtml; return $view->render(); }
php
public static function singleReport($title, $reportHtml) { $view = new View('@CoreHome/_singleReport'); $view->title = $title; $view->report = $reportHtml; return $view->render(); }
[ "public", "static", "function", "singleReport", "(", "$", "title", ",", "$", "reportHtml", ")", "{", "$", "view", "=", "new", "View", "(", "'@CoreHome/_singleReport'", ")", ";", "$", "view", "->", "title", "=", "$", "title", ";", "$", "view", "->", "report", "=", "$", "reportHtml", ";", "return", "$", "view", "->", "render", "(", ")", ";", "}" ]
Creates a View for and then renders the single report template. Can be used for pages that display only one report to avoid having to create a new template. @param string $title The report title. @param string $reportHtml The report body HTML. @return string|void The report contents if `$fetch` is true.
[ "Creates", "a", "View", "for", "and", "then", "renders", "the", "single", "report", "template", "." ]
72df150735664275a60a7861e468c6ff3b152a14
https://github.com/matomo-org/matomo/blob/72df150735664275a60a7861e468c6ff3b152a14/core/View.php#L449-L455
210,201
matomo-org/matomo
libs/Zend/Mail/Storage/Mbox.php
Zend_Mail_Storage_Mbox._getPos
protected function _getPos($id) { if (!isset($this->_positions[$id - 1])) { /** * @see Zend_Mail_Storage_Exception */ // require_once 'Zend/Mail/Storage/Exception.php'; throw new Zend_Mail_Storage_Exception('id does not exist'); } return $this->_positions[$id - 1]; }
php
protected function _getPos($id) { if (!isset($this->_positions[$id - 1])) { /** * @see Zend_Mail_Storage_Exception */ // require_once 'Zend/Mail/Storage/Exception.php'; throw new Zend_Mail_Storage_Exception('id does not exist'); } return $this->_positions[$id - 1]; }
[ "protected", "function", "_getPos", "(", "$", "id", ")", "{", "if", "(", "!", "isset", "(", "$", "this", "->", "_positions", "[", "$", "id", "-", "1", "]", ")", ")", "{", "/**\n * @see Zend_Mail_Storage_Exception\n */", "// require_once 'Zend/Mail/Storage/Exception.php';", "throw", "new", "Zend_Mail_Storage_Exception", "(", "'id does not exist'", ")", ";", "}", "return", "$", "this", "->", "_positions", "[", "$", "id", "-", "1", "]", ";", "}" ]
Get positions for mail message or throw exeption if id is invalid @param int $id number of message @return array positions as in _positions @throws Zend_Mail_Storage_Exception
[ "Get", "positions", "for", "mail", "message", "or", "throw", "exeption", "if", "id", "is", "invalid" ]
72df150735664275a60a7861e468c6ff3b152a14
https://github.com/matomo-org/matomo/blob/72df150735664275a60a7861e468c6ff3b152a14/libs/Zend/Mail/Storage/Mbox.php#L121-L132
210,202
matomo-org/matomo
libs/Zend/Mail/Storage/Mbox.php
Zend_Mail_Storage_Mbox._isMboxFile
protected function _isMboxFile($file, $fileIsString = true) { if ($fileIsString) { $file = @fopen($file, 'r'); if (!$file) { return false; } } else { fseek($file, 0); } $result = false; $line = fgets($file); if (strpos($line, 'From ') === 0) { $result = true; } if ($fileIsString) { @fclose($file); } return $result; }
php
protected function _isMboxFile($file, $fileIsString = true) { if ($fileIsString) { $file = @fopen($file, 'r'); if (!$file) { return false; } } else { fseek($file, 0); } $result = false; $line = fgets($file); if (strpos($line, 'From ') === 0) { $result = true; } if ($fileIsString) { @fclose($file); } return $result; }
[ "protected", "function", "_isMboxFile", "(", "$", "file", ",", "$", "fileIsString", "=", "true", ")", "{", "if", "(", "$", "fileIsString", ")", "{", "$", "file", "=", "@", "fopen", "(", "$", "file", ",", "'r'", ")", ";", "if", "(", "!", "$", "file", ")", "{", "return", "false", ";", "}", "}", "else", "{", "fseek", "(", "$", "file", ",", "0", ")", ";", "}", "$", "result", "=", "false", ";", "$", "line", "=", "fgets", "(", "$", "file", ")", ";", "if", "(", "strpos", "(", "$", "line", ",", "'From '", ")", "===", "0", ")", "{", "$", "result", "=", "true", ";", "}", "if", "(", "$", "fileIsString", ")", "{", "@", "fclose", "(", "$", "file", ")", ";", "}", "return", "$", "result", ";", "}" ]
check if given file is a mbox file if $file is a resource its file pointer is moved after the first line @param resource|string $file stream resource of name of file @param bool $fileIsString file is string or resource @return bool file is mbox file
[ "check", "if", "given", "file", "is", "a", "mbox", "file" ]
72df150735664275a60a7861e468c6ff3b152a14
https://github.com/matomo-org/matomo/blob/72df150735664275a60a7861e468c6ff3b152a14/libs/Zend/Mail/Storage/Mbox.php#L250-L273
210,203
matomo-org/matomo
libs/Zend/Mail/Storage/Mbox.php
Zend_Mail_Storage_Mbox._openMboxFile
protected function _openMboxFile($filename) { if ($this->_fh) { $this->close(); } $this->_fh = @fopen($filename, 'r'); if (!$this->_fh) { /** * @see Zend_Mail_Storage_Exception */ // require_once 'Zend/Mail/Storage/Exception.php'; throw new Zend_Mail_Storage_Exception('cannot open mbox file'); } $this->_filename = $filename; $this->_filemtime = filemtime($this->_filename); if (!$this->_isMboxFile($this->_fh, false)) { @fclose($this->_fh); /** * @see Zend_Mail_Storage_Exception */ // require_once 'Zend/Mail/Storage/Exception.php'; throw new Zend_Mail_Storage_Exception('file is not a valid mbox format'); } $messagePos = array('start' => ftell($this->_fh), 'separator' => 0, 'end' => 0); while (($line = fgets($this->_fh)) !== false) { if (strpos($line, 'From ') === 0) { $messagePos['end'] = ftell($this->_fh) - strlen($line) - 2; // + newline if (!$messagePos['separator']) { $messagePos['separator'] = $messagePos['end']; } $this->_positions[] = $messagePos; $messagePos = array('start' => ftell($this->_fh), 'separator' => 0, 'end' => 0); } if (!$messagePos['separator'] && !trim($line)) { $messagePos['separator'] = ftell($this->_fh); } } $messagePos['end'] = ftell($this->_fh); if (!$messagePos['separator']) { $messagePos['separator'] = $messagePos['end']; } $this->_positions[] = $messagePos; }
php
protected function _openMboxFile($filename) { if ($this->_fh) { $this->close(); } $this->_fh = @fopen($filename, 'r'); if (!$this->_fh) { /** * @see Zend_Mail_Storage_Exception */ // require_once 'Zend/Mail/Storage/Exception.php'; throw new Zend_Mail_Storage_Exception('cannot open mbox file'); } $this->_filename = $filename; $this->_filemtime = filemtime($this->_filename); if (!$this->_isMboxFile($this->_fh, false)) { @fclose($this->_fh); /** * @see Zend_Mail_Storage_Exception */ // require_once 'Zend/Mail/Storage/Exception.php'; throw new Zend_Mail_Storage_Exception('file is not a valid mbox format'); } $messagePos = array('start' => ftell($this->_fh), 'separator' => 0, 'end' => 0); while (($line = fgets($this->_fh)) !== false) { if (strpos($line, 'From ') === 0) { $messagePos['end'] = ftell($this->_fh) - strlen($line) - 2; // + newline if (!$messagePos['separator']) { $messagePos['separator'] = $messagePos['end']; } $this->_positions[] = $messagePos; $messagePos = array('start' => ftell($this->_fh), 'separator' => 0, 'end' => 0); } if (!$messagePos['separator'] && !trim($line)) { $messagePos['separator'] = ftell($this->_fh); } } $messagePos['end'] = ftell($this->_fh); if (!$messagePos['separator']) { $messagePos['separator'] = $messagePos['end']; } $this->_positions[] = $messagePos; }
[ "protected", "function", "_openMboxFile", "(", "$", "filename", ")", "{", "if", "(", "$", "this", "->", "_fh", ")", "{", "$", "this", "->", "close", "(", ")", ";", "}", "$", "this", "->", "_fh", "=", "@", "fopen", "(", "$", "filename", ",", "'r'", ")", ";", "if", "(", "!", "$", "this", "->", "_fh", ")", "{", "/**\n * @see Zend_Mail_Storage_Exception\n */", "// require_once 'Zend/Mail/Storage/Exception.php';", "throw", "new", "Zend_Mail_Storage_Exception", "(", "'cannot open mbox file'", ")", ";", "}", "$", "this", "->", "_filename", "=", "$", "filename", ";", "$", "this", "->", "_filemtime", "=", "filemtime", "(", "$", "this", "->", "_filename", ")", ";", "if", "(", "!", "$", "this", "->", "_isMboxFile", "(", "$", "this", "->", "_fh", ",", "false", ")", ")", "{", "@", "fclose", "(", "$", "this", "->", "_fh", ")", ";", "/**\n * @see Zend_Mail_Storage_Exception\n */", "// require_once 'Zend/Mail/Storage/Exception.php';", "throw", "new", "Zend_Mail_Storage_Exception", "(", "'file is not a valid mbox format'", ")", ";", "}", "$", "messagePos", "=", "array", "(", "'start'", "=>", "ftell", "(", "$", "this", "->", "_fh", ")", ",", "'separator'", "=>", "0", ",", "'end'", "=>", "0", ")", ";", "while", "(", "(", "$", "line", "=", "fgets", "(", "$", "this", "->", "_fh", ")", ")", "!==", "false", ")", "{", "if", "(", "strpos", "(", "$", "line", ",", "'From '", ")", "===", "0", ")", "{", "$", "messagePos", "[", "'end'", "]", "=", "ftell", "(", "$", "this", "->", "_fh", ")", "-", "strlen", "(", "$", "line", ")", "-", "2", ";", "// + newline", "if", "(", "!", "$", "messagePos", "[", "'separator'", "]", ")", "{", "$", "messagePos", "[", "'separator'", "]", "=", "$", "messagePos", "[", "'end'", "]", ";", "}", "$", "this", "->", "_positions", "[", "]", "=", "$", "messagePos", ";", "$", "messagePos", "=", "array", "(", "'start'", "=>", "ftell", "(", "$", "this", "->", "_fh", ")", ",", "'separator'", "=>", "0", ",", "'end'", "=>", "0", ")", ";", "}", "if", "(", "!", "$", "messagePos", "[", "'separator'", "]", "&&", "!", "trim", "(", "$", "line", ")", ")", "{", "$", "messagePos", "[", "'separator'", "]", "=", "ftell", "(", "$", "this", "->", "_fh", ")", ";", "}", "}", "$", "messagePos", "[", "'end'", "]", "=", "ftell", "(", "$", "this", "->", "_fh", ")", ";", "if", "(", "!", "$", "messagePos", "[", "'separator'", "]", ")", "{", "$", "messagePos", "[", "'separator'", "]", "=", "$", "messagePos", "[", "'end'", "]", ";", "}", "$", "this", "->", "_positions", "[", "]", "=", "$", "messagePos", ";", "}" ]
open given file as current mbox file @param string $filename filename of mbox file @return null @throws Zend_Mail_Storage_Exception
[ "open", "given", "file", "as", "current", "mbox", "file" ]
72df150735664275a60a7861e468c6ff3b152a14
https://github.com/matomo-org/matomo/blob/72df150735664275a60a7861e468c6ff3b152a14/libs/Zend/Mail/Storage/Mbox.php#L282-L328
210,204
matomo-org/matomo
libs/HTML/QuickForm2/Element/Input.php
HTML_QuickForm2_Element_Input.getFrozenHtml
protected function getFrozenHtml() { $value = $this->getAttribute('value'); return (('' != $value)? htmlspecialchars($value, ENT_QUOTES, self::getOption('charset')): ' ') . $this->getPersistentContent(); }
php
protected function getFrozenHtml() { $value = $this->getAttribute('value'); return (('' != $value)? htmlspecialchars($value, ENT_QUOTES, self::getOption('charset')): ' ') . $this->getPersistentContent(); }
[ "protected", "function", "getFrozenHtml", "(", ")", "{", "$", "value", "=", "$", "this", "->", "getAttribute", "(", "'value'", ")", ";", "return", "(", "(", "''", "!=", "$", "value", ")", "?", "htmlspecialchars", "(", "$", "value", ",", "ENT_QUOTES", ",", "self", "::", "getOption", "(", "'charset'", ")", ")", ":", "' '", ")", ".", "$", "this", "->", "getPersistentContent", "(", ")", ";", "}" ]
Returns the field's value without HTML tags @return string
[ "Returns", "the", "field", "s", "value", "without", "HTML", "tags" ]
72df150735664275a60a7861e468c6ff3b152a14
https://github.com/matomo-org/matomo/blob/72df150735664275a60a7861e468c6ff3b152a14/libs/HTML/QuickForm2/Element/Input.php#L107-L112
210,205
matomo-org/matomo
core/Settings/Setting.php
Setting.getValue
public function getValue() { return $this->storage->getValue($this->name, $this->defaultValue, $this->type); }
php
public function getValue() { return $this->storage->getValue($this->name, $this->defaultValue, $this->type); }
[ "public", "function", "getValue", "(", ")", "{", "return", "$", "this", "->", "storage", "->", "getValue", "(", "$", "this", "->", "name", ",", "$", "this", "->", "defaultValue", ",", "$", "this", "->", "type", ")", ";", "}" ]
Returns the previously persisted setting value. If no value was set, the default value is returned. @return mixed
[ "Returns", "the", "previously", "persisted", "setting", "value", ".", "If", "no", "value", "was", "set", "the", "default", "value", "is", "returned", "." ]
72df150735664275a60a7861e468c6ff3b152a14
https://github.com/matomo-org/matomo/blob/72df150735664275a60a7861e468c6ff3b152a14/core/Settings/Setting.php#L202-L205
210,206
matomo-org/matomo
core/Settings/Setting.php
Setting.setValue
public function setValue($value) { $this->checkHasEnoughWritePermission(); $config = $this->configureField(); $this->validateValue($value); if ($config->transform && $config->transform instanceof \Closure) { $value = call_user_func($config->transform, $value, $this); } if (isset($this->type) && !is_null($value)) { settype($value, $this->type); } $this->storage->setValue($this->name, $value); }
php
public function setValue($value) { $this->checkHasEnoughWritePermission(); $config = $this->configureField(); $this->validateValue($value); if ($config->transform && $config->transform instanceof \Closure) { $value = call_user_func($config->transform, $value, $this); } if (isset($this->type) && !is_null($value)) { settype($value, $this->type); } $this->storage->setValue($this->name, $value); }
[ "public", "function", "setValue", "(", "$", "value", ")", "{", "$", "this", "->", "checkHasEnoughWritePermission", "(", ")", ";", "$", "config", "=", "$", "this", "->", "configureField", "(", ")", ";", "$", "this", "->", "validateValue", "(", "$", "value", ")", ";", "if", "(", "$", "config", "->", "transform", "&&", "$", "config", "->", "transform", "instanceof", "\\", "Closure", ")", "{", "$", "value", "=", "call_user_func", "(", "$", "config", "->", "transform", ",", "$", "value", ",", "$", "this", ")", ";", "}", "if", "(", "isset", "(", "$", "this", "->", "type", ")", "&&", "!", "is_null", "(", "$", "value", ")", ")", "{", "settype", "(", "$", "value", ",", "$", "this", "->", "type", ")", ";", "}", "$", "this", "->", "storage", "->", "setValue", "(", "$", "this", "->", "name", ",", "$", "value", ")", ";", "}" ]
Sets and persists this setting's value overwriting any existing value. Before a value is actually set it will be made sure the current user is allowed to change the value. The value will be first validated either via a system built-in validate method or via a set {@link FieldConfig::$validate} custom method. Afterwards the value will be transformed via a possibly specified {@link FieldConfig::$transform} method. Before storing the actual value, the value will be converted to the actually specified {@link $type}. @param mixed $value @throws \Exception If the current user is not allowed to change the value of this setting.
[ "Sets", "and", "persists", "this", "setting", "s", "value", "overwriting", "any", "existing", "value", "." ]
72df150735664275a60a7861e468c6ff3b152a14
https://github.com/matomo-org/matomo/blob/72df150735664275a60a7861e468c6ff3b152a14/core/Settings/Setting.php#L218-L235
210,207
matomo-org/matomo
libs/Zend/Validate/EmailAddress.php
Zend_Validate_EmailAddress._isReserved
private function _isReserved($host){ if (!preg_match('/^([0-9]{1,3}\.){3}[0-9]{1,3}$/', $host)) { $host = gethostbyname($host); } $octet = explode('.',$host); if ((int)$octet[0] >= 224) { return true; } else if (array_key_exists($octet[0], $this->_invalidIp)) { foreach ((array)$this->_invalidIp[$octet[0]] as $subnetData) { // we skip the first loop as we already know that octet matches for ($i = 1; $i < 4; $i++) { if (strpos($subnetData, $octet[$i]) !== $i * 4) { break; } } $host = explode("/", $subnetData); $binaryHost = ""; $tmp = explode(".", $host[0]); for ($i = 0; $i < 4 ; $i++) { $binaryHost .= str_pad(decbin($tmp[$i]), 8, "0", STR_PAD_LEFT); } $segmentData = array( 'network' => (int)$this->_toIp(str_pad(substr($binaryHost, 0, $host[1]), 32, 0)), 'broadcast' => (int)$this->_toIp(str_pad(substr($binaryHost, 0, $host[1]), 32, 1)) ); for ($j = $i; $j < 4; $j++) { if ((int)$octet[$j] < $segmentData['network'][$j] || (int)$octet[$j] > $segmentData['broadcast'][$j]) { return false; } } } return true; } else { return false; } }
php
private function _isReserved($host){ if (!preg_match('/^([0-9]{1,3}\.){3}[0-9]{1,3}$/', $host)) { $host = gethostbyname($host); } $octet = explode('.',$host); if ((int)$octet[0] >= 224) { return true; } else if (array_key_exists($octet[0], $this->_invalidIp)) { foreach ((array)$this->_invalidIp[$octet[0]] as $subnetData) { // we skip the first loop as we already know that octet matches for ($i = 1; $i < 4; $i++) { if (strpos($subnetData, $octet[$i]) !== $i * 4) { break; } } $host = explode("/", $subnetData); $binaryHost = ""; $tmp = explode(".", $host[0]); for ($i = 0; $i < 4 ; $i++) { $binaryHost .= str_pad(decbin($tmp[$i]), 8, "0", STR_PAD_LEFT); } $segmentData = array( 'network' => (int)$this->_toIp(str_pad(substr($binaryHost, 0, $host[1]), 32, 0)), 'broadcast' => (int)$this->_toIp(str_pad(substr($binaryHost, 0, $host[1]), 32, 1)) ); for ($j = $i; $j < 4; $j++) { if ((int)$octet[$j] < $segmentData['network'][$j] || (int)$octet[$j] > $segmentData['broadcast'][$j]) { return false; } } } return true; } else { return false; } }
[ "private", "function", "_isReserved", "(", "$", "host", ")", "{", "if", "(", "!", "preg_match", "(", "'/^([0-9]{1,3}\\.){3}[0-9]{1,3}$/'", ",", "$", "host", ")", ")", "{", "$", "host", "=", "gethostbyname", "(", "$", "host", ")", ";", "}", "$", "octet", "=", "explode", "(", "'.'", ",", "$", "host", ")", ";", "if", "(", "(", "int", ")", "$", "octet", "[", "0", "]", ">=", "224", ")", "{", "return", "true", ";", "}", "else", "if", "(", "array_key_exists", "(", "$", "octet", "[", "0", "]", ",", "$", "this", "->", "_invalidIp", ")", ")", "{", "foreach", "(", "(", "array", ")", "$", "this", "->", "_invalidIp", "[", "$", "octet", "[", "0", "]", "]", "as", "$", "subnetData", ")", "{", "// we skip the first loop as we already know that octet matches", "for", "(", "$", "i", "=", "1", ";", "$", "i", "<", "4", ";", "$", "i", "++", ")", "{", "if", "(", "strpos", "(", "$", "subnetData", ",", "$", "octet", "[", "$", "i", "]", ")", "!==", "$", "i", "*", "4", ")", "{", "break", ";", "}", "}", "$", "host", "=", "explode", "(", "\"/\"", ",", "$", "subnetData", ")", ";", "$", "binaryHost", "=", "\"\"", ";", "$", "tmp", "=", "explode", "(", "\".\"", ",", "$", "host", "[", "0", "]", ")", ";", "for", "(", "$", "i", "=", "0", ";", "$", "i", "<", "4", ";", "$", "i", "++", ")", "{", "$", "binaryHost", ".=", "str_pad", "(", "decbin", "(", "$", "tmp", "[", "$", "i", "]", ")", ",", "8", ",", "\"0\"", ",", "STR_PAD_LEFT", ")", ";", "}", "$", "segmentData", "=", "array", "(", "'network'", "=>", "(", "int", ")", "$", "this", "->", "_toIp", "(", "str_pad", "(", "substr", "(", "$", "binaryHost", ",", "0", ",", "$", "host", "[", "1", "]", ")", ",", "32", ",", "0", ")", ")", ",", "'broadcast'", "=>", "(", "int", ")", "$", "this", "->", "_toIp", "(", "str_pad", "(", "substr", "(", "$", "binaryHost", ",", "0", ",", "$", "host", "[", "1", "]", ")", ",", "32", ",", "1", ")", ")", ")", ";", "for", "(", "$", "j", "=", "$", "i", ";", "$", "j", "<", "4", ";", "$", "j", "++", ")", "{", "if", "(", "(", "int", ")", "$", "octet", "[", "$", "j", "]", "<", "$", "segmentData", "[", "'network'", "]", "[", "$", "j", "]", "||", "(", "int", ")", "$", "octet", "[", "$", "j", "]", ">", "$", "segmentData", "[", "'broadcast'", "]", "[", "$", "j", "]", ")", "{", "return", "false", ";", "}", "}", "}", "return", "true", ";", "}", "else", "{", "return", "false", ";", "}", "}" ]
Returns if the given host is reserved @param string $host @return boolean
[ "Returns", "if", "the", "given", "host", "is", "reserved" ]
72df150735664275a60a7861e468c6ff3b152a14
https://github.com/matomo-org/matomo/blob/72df150735664275a60a7861e468c6ff3b152a14/libs/Zend/Validate/EmailAddress.php#L340-L381
210,208
matomo-org/matomo
libs/Zend/Validate/EmailAddress.php
Zend_Validate_EmailAddress._toIp
private function _toIp($binary) { $ip = array(); $tmp = explode(".", chunk_split($binary, 8, ".")); for ($i = 0; $i < 4 ; $i++) { $ip[$i] = bindec($tmp[$i]); } return $ip; }
php
private function _toIp($binary) { $ip = array(); $tmp = explode(".", chunk_split($binary, 8, ".")); for ($i = 0; $i < 4 ; $i++) { $ip[$i] = bindec($tmp[$i]); } return $ip; }
[ "private", "function", "_toIp", "(", "$", "binary", ")", "{", "$", "ip", "=", "array", "(", ")", ";", "$", "tmp", "=", "explode", "(", "\".\"", ",", "chunk_split", "(", "$", "binary", ",", "8", ",", "\".\"", ")", ")", ";", "for", "(", "$", "i", "=", "0", ";", "$", "i", "<", "4", ";", "$", "i", "++", ")", "{", "$", "ip", "[", "$", "i", "]", "=", "bindec", "(", "$", "tmp", "[", "$", "i", "]", ")", ";", "}", "return", "$", "ip", ";", "}" ]
Converts a binary string to an IP address @param string $binary @return mixed
[ "Converts", "a", "binary", "string", "to", "an", "IP", "address" ]
72df150735664275a60a7861e468c6ff3b152a14
https://github.com/matomo-org/matomo/blob/72df150735664275a60a7861e468c6ff3b152a14/libs/Zend/Validate/EmailAddress.php#L389-L398
210,209
matomo-org/matomo
libs/Zend/Validate/EmailAddress.php
Zend_Validate_EmailAddress._validateLocalPart
private function _validateLocalPart() { // First try to match the local part on the common dot-atom format $result = false; // Dot-atom characters are: 1*atext *("." 1*atext) // atext: ALPHA / DIGIT / and "!", "#", "$", "%", "&", "'", "*", // "+", "-", "/", "=", "?", "^", "_", "`", "{", "|", "}", "~" $atext = 'a-zA-Z0-9\x21\x23\x24\x25\x26\x27\x2a\x2b\x2d\x2f\x3d\x3f\x5e\x5f\x60\x7b\x7c\x7d\x7e'; if (preg_match('/^[' . $atext . ']+(\x2e+[' . $atext . ']+)*$/', $this->_localPart)) { $result = true; } else { // Try quoted string format // Quoted-string characters are: DQUOTE *([FWS] qtext/quoted-pair) [FWS] DQUOTE // qtext: Non white space controls, and the rest of the US-ASCII characters not // including "\" or the quote character $noWsCtl = '\x01-\x08\x0b\x0c\x0e-\x1f\x7f'; $qtext = $noWsCtl . '\x21\x23-\x5b\x5d-\x7e'; $ws = '\x20\x09'; if (preg_match('/^\x22([' . $ws . $qtext . '])*[$ws]?\x22$/', $this->_localPart)) { $result = true; } else { $this->_error(self::DOT_ATOM); $this->_error(self::QUOTED_STRING); $this->_error(self::INVALID_LOCAL_PART); } } return $result; }
php
private function _validateLocalPart() { // First try to match the local part on the common dot-atom format $result = false; // Dot-atom characters are: 1*atext *("." 1*atext) // atext: ALPHA / DIGIT / and "!", "#", "$", "%", "&", "'", "*", // "+", "-", "/", "=", "?", "^", "_", "`", "{", "|", "}", "~" $atext = 'a-zA-Z0-9\x21\x23\x24\x25\x26\x27\x2a\x2b\x2d\x2f\x3d\x3f\x5e\x5f\x60\x7b\x7c\x7d\x7e'; if (preg_match('/^[' . $atext . ']+(\x2e+[' . $atext . ']+)*$/', $this->_localPart)) { $result = true; } else { // Try quoted string format // Quoted-string characters are: DQUOTE *([FWS] qtext/quoted-pair) [FWS] DQUOTE // qtext: Non white space controls, and the rest of the US-ASCII characters not // including "\" or the quote character $noWsCtl = '\x01-\x08\x0b\x0c\x0e-\x1f\x7f'; $qtext = $noWsCtl . '\x21\x23-\x5b\x5d-\x7e'; $ws = '\x20\x09'; if (preg_match('/^\x22([' . $ws . $qtext . '])*[$ws]?\x22$/', $this->_localPart)) { $result = true; } else { $this->_error(self::DOT_ATOM); $this->_error(self::QUOTED_STRING); $this->_error(self::INVALID_LOCAL_PART); } } return $result; }
[ "private", "function", "_validateLocalPart", "(", ")", "{", "// First try to match the local part on the common dot-atom format", "$", "result", "=", "false", ";", "// Dot-atom characters are: 1*atext *(\".\" 1*atext)", "// atext: ALPHA / DIGIT / and \"!\", \"#\", \"$\", \"%\", \"&\", \"'\", \"*\",", "// \"+\", \"-\", \"/\", \"=\", \"?\", \"^\", \"_\", \"`\", \"{\", \"|\", \"}\", \"~\"", "$", "atext", "=", "'a-zA-Z0-9\\x21\\x23\\x24\\x25\\x26\\x27\\x2a\\x2b\\x2d\\x2f\\x3d\\x3f\\x5e\\x5f\\x60\\x7b\\x7c\\x7d\\x7e'", ";", "if", "(", "preg_match", "(", "'/^['", ".", "$", "atext", ".", "']+(\\x2e+['", ".", "$", "atext", ".", "']+)*$/'", ",", "$", "this", "->", "_localPart", ")", ")", "{", "$", "result", "=", "true", ";", "}", "else", "{", "// Try quoted string format", "// Quoted-string characters are: DQUOTE *([FWS] qtext/quoted-pair) [FWS] DQUOTE", "// qtext: Non white space controls, and the rest of the US-ASCII characters not", "// including \"\\\" or the quote character", "$", "noWsCtl", "=", "'\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x7f'", ";", "$", "qtext", "=", "$", "noWsCtl", ".", "'\\x21\\x23-\\x5b\\x5d-\\x7e'", ";", "$", "ws", "=", "'\\x20\\x09'", ";", "if", "(", "preg_match", "(", "'/^\\x22(['", ".", "$", "ws", ".", "$", "qtext", ".", "'])*[$ws]?\\x22$/'", ",", "$", "this", "->", "_localPart", ")", ")", "{", "$", "result", "=", "true", ";", "}", "else", "{", "$", "this", "->", "_error", "(", "self", "::", "DOT_ATOM", ")", ";", "$", "this", "->", "_error", "(", "self", "::", "QUOTED_STRING", ")", ";", "$", "this", "->", "_error", "(", "self", "::", "INVALID_LOCAL_PART", ")", ";", "}", "}", "return", "$", "result", ";", "}" ]
Internal method to validate the local part of the email address @return boolean
[ "Internal", "method", "to", "validate", "the", "local", "part", "of", "the", "email", "address" ]
72df150735664275a60a7861e468c6ff3b152a14
https://github.com/matomo-org/matomo/blob/72df150735664275a60a7861e468c6ff3b152a14/libs/Zend/Validate/EmailAddress.php#L405-L435
210,210
matomo-org/matomo
libs/Zend/Validate/EmailAddress.php
Zend_Validate_EmailAddress._validateMXRecords
private function _validateMXRecords() { $mxHosts = array(); $result = getmxrr($this->_hostname, $mxHosts); if (!$result) { $this->_error(self::INVALID_MX_RECORD); } else if ($this->_options['deep'] && function_exists('checkdnsrr')) { $validAddress = false; $reserved = true; foreach ($mxHosts as $hostname) { $res = $this->_isReserved($hostname); if (!$res) { $reserved = false; } if (!$res && (checkdnsrr($hostname, "A") || checkdnsrr($hostname, "AAAA") || checkdnsrr($hostname, "A6"))) { $validAddress = true; break; } } if (!$validAddress) { $result = false; if ($reserved) { $this->_error(self::INVALID_SEGMENT); } else { $this->_error(self::INVALID_MX_RECORD); } } } return $result; }
php
private function _validateMXRecords() { $mxHosts = array(); $result = getmxrr($this->_hostname, $mxHosts); if (!$result) { $this->_error(self::INVALID_MX_RECORD); } else if ($this->_options['deep'] && function_exists('checkdnsrr')) { $validAddress = false; $reserved = true; foreach ($mxHosts as $hostname) { $res = $this->_isReserved($hostname); if (!$res) { $reserved = false; } if (!$res && (checkdnsrr($hostname, "A") || checkdnsrr($hostname, "AAAA") || checkdnsrr($hostname, "A6"))) { $validAddress = true; break; } } if (!$validAddress) { $result = false; if ($reserved) { $this->_error(self::INVALID_SEGMENT); } else { $this->_error(self::INVALID_MX_RECORD); } } } return $result; }
[ "private", "function", "_validateMXRecords", "(", ")", "{", "$", "mxHosts", "=", "array", "(", ")", ";", "$", "result", "=", "getmxrr", "(", "$", "this", "->", "_hostname", ",", "$", "mxHosts", ")", ";", "if", "(", "!", "$", "result", ")", "{", "$", "this", "->", "_error", "(", "self", "::", "INVALID_MX_RECORD", ")", ";", "}", "else", "if", "(", "$", "this", "->", "_options", "[", "'deep'", "]", "&&", "function_exists", "(", "'checkdnsrr'", ")", ")", "{", "$", "validAddress", "=", "false", ";", "$", "reserved", "=", "true", ";", "foreach", "(", "$", "mxHosts", "as", "$", "hostname", ")", "{", "$", "res", "=", "$", "this", "->", "_isReserved", "(", "$", "hostname", ")", ";", "if", "(", "!", "$", "res", ")", "{", "$", "reserved", "=", "false", ";", "}", "if", "(", "!", "$", "res", "&&", "(", "checkdnsrr", "(", "$", "hostname", ",", "\"A\"", ")", "||", "checkdnsrr", "(", "$", "hostname", ",", "\"AAAA\"", ")", "||", "checkdnsrr", "(", "$", "hostname", ",", "\"A6\"", ")", ")", ")", "{", "$", "validAddress", "=", "true", ";", "break", ";", "}", "}", "if", "(", "!", "$", "validAddress", ")", "{", "$", "result", "=", "false", ";", "if", "(", "$", "reserved", ")", "{", "$", "this", "->", "_error", "(", "self", "::", "INVALID_SEGMENT", ")", ";", "}", "else", "{", "$", "this", "->", "_error", "(", "self", "::", "INVALID_MX_RECORD", ")", ";", "}", "}", "}", "return", "$", "result", ";", "}" ]
Internal method to validate the servers MX records @return boolean
[ "Internal", "method", "to", "validate", "the", "servers", "MX", "records" ]
72df150735664275a60a7861e468c6ff3b152a14
https://github.com/matomo-org/matomo/blob/72df150735664275a60a7861e468c6ff3b152a14/libs/Zend/Validate/EmailAddress.php#L442-L477
210,211
matomo-org/matomo
libs/Zend/Validate/EmailAddress.php
Zend_Validate_EmailAddress._validateHostnamePart
private function _validateHostnamePart() { $hostname = $this->_options['hostname']->setTranslator($this->getTranslator()) ->isValid($this->_hostname); if (!$hostname) { $this->_error(self::INVALID_HOSTNAME); // Get messages and errors from hostnameValidator foreach ($this->_options['hostname']->getMessages() as $code => $message) { $this->_messages[$code] = $message; } foreach ($this->_options['hostname']->getErrors() as $error) { $this->_errors[] = $error; } } else if ($this->_options['mx']) { // MX check on hostname $hostname = $this->_validateMXRecords(); } return $hostname; }
php
private function _validateHostnamePart() { $hostname = $this->_options['hostname']->setTranslator($this->getTranslator()) ->isValid($this->_hostname); if (!$hostname) { $this->_error(self::INVALID_HOSTNAME); // Get messages and errors from hostnameValidator foreach ($this->_options['hostname']->getMessages() as $code => $message) { $this->_messages[$code] = $message; } foreach ($this->_options['hostname']->getErrors() as $error) { $this->_errors[] = $error; } } else if ($this->_options['mx']) { // MX check on hostname $hostname = $this->_validateMXRecords(); } return $hostname; }
[ "private", "function", "_validateHostnamePart", "(", ")", "{", "$", "hostname", "=", "$", "this", "->", "_options", "[", "'hostname'", "]", "->", "setTranslator", "(", "$", "this", "->", "getTranslator", "(", ")", ")", "->", "isValid", "(", "$", "this", "->", "_hostname", ")", ";", "if", "(", "!", "$", "hostname", ")", "{", "$", "this", "->", "_error", "(", "self", "::", "INVALID_HOSTNAME", ")", ";", "// Get messages and errors from hostnameValidator", "foreach", "(", "$", "this", "->", "_options", "[", "'hostname'", "]", "->", "getMessages", "(", ")", "as", "$", "code", "=>", "$", "message", ")", "{", "$", "this", "->", "_messages", "[", "$", "code", "]", "=", "$", "message", ";", "}", "foreach", "(", "$", "this", "->", "_options", "[", "'hostname'", "]", "->", "getErrors", "(", ")", "as", "$", "error", ")", "{", "$", "this", "->", "_errors", "[", "]", "=", "$", "error", ";", "}", "}", "else", "if", "(", "$", "this", "->", "_options", "[", "'mx'", "]", ")", "{", "// MX check on hostname", "$", "hostname", "=", "$", "this", "->", "_validateMXRecords", "(", ")", ";", "}", "return", "$", "hostname", ";", "}" ]
Internal method to validate the hostname part of the email address @return boolean
[ "Internal", "method", "to", "validate", "the", "hostname", "part", "of", "the", "email", "address" ]
72df150735664275a60a7861e468c6ff3b152a14
https://github.com/matomo-org/matomo/blob/72df150735664275a60a7861e468c6ff3b152a14/libs/Zend/Validate/EmailAddress.php#L484-L505
210,212
matomo-org/matomo
core/Menu/MenuTop.php
MenuTop.addHtml
public function addHtml($menuName, $data, $displayedForCurrentUser, $order, $tooltip) { if ($displayedForCurrentUser) { if (!isset($this->menu[$menuName])) { $this->menu[$menuName]['_name'] = $menuName; $this->menu[$menuName]['_html'] = $data; $this->menu[$menuName]['_order'] = $order; $this->menu[$menuName]['_url'] = null; $this->menu[$menuName]['_icon'] = ''; $this->menu[$menuName]['_hasSubmenu'] = false; $this->menu[$menuName]['_tooltip'] = $tooltip; } } }
php
public function addHtml($menuName, $data, $displayedForCurrentUser, $order, $tooltip) { if ($displayedForCurrentUser) { if (!isset($this->menu[$menuName])) { $this->menu[$menuName]['_name'] = $menuName; $this->menu[$menuName]['_html'] = $data; $this->menu[$menuName]['_order'] = $order; $this->menu[$menuName]['_url'] = null; $this->menu[$menuName]['_icon'] = ''; $this->menu[$menuName]['_hasSubmenu'] = false; $this->menu[$menuName]['_tooltip'] = $tooltip; } } }
[ "public", "function", "addHtml", "(", "$", "menuName", ",", "$", "data", ",", "$", "displayedForCurrentUser", ",", "$", "order", ",", "$", "tooltip", ")", "{", "if", "(", "$", "displayedForCurrentUser", ")", "{", "if", "(", "!", "isset", "(", "$", "this", "->", "menu", "[", "$", "menuName", "]", ")", ")", "{", "$", "this", "->", "menu", "[", "$", "menuName", "]", "[", "'_name'", "]", "=", "$", "menuName", ";", "$", "this", "->", "menu", "[", "$", "menuName", "]", "[", "'_html'", "]", "=", "$", "data", ";", "$", "this", "->", "menu", "[", "$", "menuName", "]", "[", "'_order'", "]", "=", "$", "order", ";", "$", "this", "->", "menu", "[", "$", "menuName", "]", "[", "'_url'", "]", "=", "null", ";", "$", "this", "->", "menu", "[", "$", "menuName", "]", "[", "'_icon'", "]", "=", "''", ";", "$", "this", "->", "menu", "[", "$", "menuName", "]", "[", "'_hasSubmenu'", "]", "=", "false", ";", "$", "this", "->", "menu", "[", "$", "menuName", "]", "[", "'_tooltip'", "]", "=", "$", "tooltip", ";", "}", "}", "}" ]
Directly adds a menu entry containing html. @param string $menuName @param string $data @param boolean $displayedForCurrentUser @param int $order @param string $tooltip Tooltip to display. @api
[ "Directly", "adds", "a", "menu", "entry", "containing", "html", "." ]
72df150735664275a60a7861e468c6ff3b152a14
https://github.com/matomo-org/matomo/blob/72df150735664275a60a7861e468c6ff3b152a14/core/Menu/MenuTop.php#L32-L45
210,213
matomo-org/matomo
core/Menu/MenuTop.php
MenuTop.getMenu
public function getMenu() { if (!$this->menu) { foreach ($this->getAllMenus() as $menu) { $menu->configureTopMenu($this); } } return parent::getMenu(); }
php
public function getMenu() { if (!$this->menu) { foreach ($this->getAllMenus() as $menu) { $menu->configureTopMenu($this); } } return parent::getMenu(); }
[ "public", "function", "getMenu", "(", ")", "{", "if", "(", "!", "$", "this", "->", "menu", ")", "{", "foreach", "(", "$", "this", "->", "getAllMenus", "(", ")", "as", "$", "menu", ")", "{", "$", "menu", "->", "configureTopMenu", "(", "$", "this", ")", ";", "}", "}", "return", "parent", "::", "getMenu", "(", ")", ";", "}" ]
Triggers the Menu.Top.addItems hook and returns the menu. @return Array
[ "Triggers", "the", "Menu", ".", "Top", ".", "addItems", "hook", "and", "returns", "the", "menu", "." ]
72df150735664275a60a7861e468c6ff3b152a14
https://github.com/matomo-org/matomo/blob/72df150735664275a60a7861e468c6ff3b152a14/core/Menu/MenuTop.php#L52-L62
210,214
matomo-org/matomo
plugins/LanguagesManager/API.php
API.isLanguageAvailable
public function isLanguageAvailable($languageCode) { return $languageCode !== false && Filesystem::isValidFilename($languageCode) && in_array($languageCode, $this->getAvailableLanguages()); }
php
public function isLanguageAvailable($languageCode) { return $languageCode !== false && Filesystem::isValidFilename($languageCode) && in_array($languageCode, $this->getAvailableLanguages()); }
[ "public", "function", "isLanguageAvailable", "(", "$", "languageCode", ")", "{", "return", "$", "languageCode", "!==", "false", "&&", "Filesystem", "::", "isValidFilename", "(", "$", "languageCode", ")", "&&", "in_array", "(", "$", "languageCode", ",", "$", "this", "->", "getAvailableLanguages", "(", ")", ")", ";", "}" ]
Returns true if specified language is available @param string $languageCode @return bool true if language available; false otherwise
[ "Returns", "true", "if", "specified", "language", "is", "available" ]
72df150735664275a60a7861e468c6ff3b152a14
https://github.com/matomo-org/matomo/blob/72df150735664275a60a7861e468c6ff3b152a14/plugins/LanguagesManager/API.php#L44-L49
210,215
matomo-org/matomo
plugins/LanguagesManager/API.php
API.getAvailableLanguages
public function getAvailableLanguages() { if (!is_null($this->languageNames)) { return $this->languageNames; } $path = PIWIK_INCLUDE_PATH . "/lang/"; $languagesPath = _glob($path . "*.json"); $pathLength = strlen($path); $languages = array(); if ($languagesPath) { foreach ($languagesPath as $language) { $languages[] = substr($language, $pathLength, -strlen('.json')); } } $this->enableDevelopmentLanguageInDevEnvironment($languages); /** * Hook called after loading available language files. * * Use this hook to customise the list of languagesPath available in Matomo. * * @param array */ Piwik::postEvent('LanguagesManager.getAvailableLanguages', array(&$languages)); /** * Hook called after loading available language files. * * @param array * * @deprecated since v3.9.0 use LanguagesManager.getAvailableLanguages instead. Will be removed in Matomo 4.0.0 */ Piwik::postEvent('LanguageManager.getAvailableLanguages', array(&$languages)); $this->languageNames = $languages; return $languages; }
php
public function getAvailableLanguages() { if (!is_null($this->languageNames)) { return $this->languageNames; } $path = PIWIK_INCLUDE_PATH . "/lang/"; $languagesPath = _glob($path . "*.json"); $pathLength = strlen($path); $languages = array(); if ($languagesPath) { foreach ($languagesPath as $language) { $languages[] = substr($language, $pathLength, -strlen('.json')); } } $this->enableDevelopmentLanguageInDevEnvironment($languages); /** * Hook called after loading available language files. * * Use this hook to customise the list of languagesPath available in Matomo. * * @param array */ Piwik::postEvent('LanguagesManager.getAvailableLanguages', array(&$languages)); /** * Hook called after loading available language files. * * @param array * * @deprecated since v3.9.0 use LanguagesManager.getAvailableLanguages instead. Will be removed in Matomo 4.0.0 */ Piwik::postEvent('LanguageManager.getAvailableLanguages', array(&$languages)); $this->languageNames = $languages; return $languages; }
[ "public", "function", "getAvailableLanguages", "(", ")", "{", "if", "(", "!", "is_null", "(", "$", "this", "->", "languageNames", ")", ")", "{", "return", "$", "this", "->", "languageNames", ";", "}", "$", "path", "=", "PIWIK_INCLUDE_PATH", ".", "\"/lang/\"", ";", "$", "languagesPath", "=", "_glob", "(", "$", "path", ".", "\"*.json\"", ")", ";", "$", "pathLength", "=", "strlen", "(", "$", "path", ")", ";", "$", "languages", "=", "array", "(", ")", ";", "if", "(", "$", "languagesPath", ")", "{", "foreach", "(", "$", "languagesPath", "as", "$", "language", ")", "{", "$", "languages", "[", "]", "=", "substr", "(", "$", "language", ",", "$", "pathLength", ",", "-", "strlen", "(", "'.json'", ")", ")", ";", "}", "}", "$", "this", "->", "enableDevelopmentLanguageInDevEnvironment", "(", "$", "languages", ")", ";", "/**\n * Hook called after loading available language files.\n *\n * Use this hook to customise the list of languagesPath available in Matomo.\n *\n * @param array\n */", "Piwik", "::", "postEvent", "(", "'LanguagesManager.getAvailableLanguages'", ",", "array", "(", "&", "$", "languages", ")", ")", ";", "/**\n * Hook called after loading available language files.\n *\n * @param array\n *\n * @deprecated since v3.9.0 use LanguagesManager.getAvailableLanguages instead. Will be removed in Matomo 4.0.0\n */", "Piwik", "::", "postEvent", "(", "'LanguageManager.getAvailableLanguages'", ",", "array", "(", "&", "$", "languages", ")", ")", ";", "$", "this", "->", "languageNames", "=", "$", "languages", ";", "return", "$", "languages", ";", "}" ]
Return array of available languages @return array Array of strings, each containing its ISO language code
[ "Return", "array", "of", "available", "languages" ]
72df150735664275a60a7861e468c6ff3b152a14
https://github.com/matomo-org/matomo/blob/72df150735664275a60a7861e468c6ff3b152a14/plugins/LanguagesManager/API.php#L56-L94
210,216
matomo-org/matomo
plugins/LanguagesManager/API.php
API.getTranslationsForLanguage
public function getTranslationsForLanguage($languageCode) { if (!$this->isLanguageAvailable($languageCode)) { return false; } $data = file_get_contents(PIWIK_INCLUDE_PATH . "/lang/$languageCode.json"); $translations = json_decode($data, true); $languageInfo = array(); foreach ($translations as $module => $keys) { foreach ($keys as $key => $value) { $languageInfo[] = array( 'label' => sprintf("%s_%s", $module, $key), 'value' => $value ); } } foreach (PluginManager::getInstance()->getLoadedPluginsName() as $pluginName) { $translations = $this->getPluginTranslationsForLanguage($pluginName, $languageCode); if (!empty($translations)) { foreach ($translations as $keys) { $languageInfo[] = $keys; } } } return $languageInfo; }
php
public function getTranslationsForLanguage($languageCode) { if (!$this->isLanguageAvailable($languageCode)) { return false; } $data = file_get_contents(PIWIK_INCLUDE_PATH . "/lang/$languageCode.json"); $translations = json_decode($data, true); $languageInfo = array(); foreach ($translations as $module => $keys) { foreach ($keys as $key => $value) { $languageInfo[] = array( 'label' => sprintf("%s_%s", $module, $key), 'value' => $value ); } } foreach (PluginManager::getInstance()->getLoadedPluginsName() as $pluginName) { $translations = $this->getPluginTranslationsForLanguage($pluginName, $languageCode); if (!empty($translations)) { foreach ($translations as $keys) { $languageInfo[] = $keys; } } } return $languageInfo; }
[ "public", "function", "getTranslationsForLanguage", "(", "$", "languageCode", ")", "{", "if", "(", "!", "$", "this", "->", "isLanguageAvailable", "(", "$", "languageCode", ")", ")", "{", "return", "false", ";", "}", "$", "data", "=", "file_get_contents", "(", "PIWIK_INCLUDE_PATH", ".", "\"/lang/$languageCode.json\"", ")", ";", "$", "translations", "=", "json_decode", "(", "$", "data", ",", "true", ")", ";", "$", "languageInfo", "=", "array", "(", ")", ";", "foreach", "(", "$", "translations", "as", "$", "module", "=>", "$", "keys", ")", "{", "foreach", "(", "$", "keys", "as", "$", "key", "=>", "$", "value", ")", "{", "$", "languageInfo", "[", "]", "=", "array", "(", "'label'", "=>", "sprintf", "(", "\"%s_%s\"", ",", "$", "module", ",", "$", "key", ")", ",", "'value'", "=>", "$", "value", ")", ";", "}", "}", "foreach", "(", "PluginManager", "::", "getInstance", "(", ")", "->", "getLoadedPluginsName", "(", ")", "as", "$", "pluginName", ")", "{", "$", "translations", "=", "$", "this", "->", "getPluginTranslationsForLanguage", "(", "$", "pluginName", ",", "$", "languageCode", ")", ";", "if", "(", "!", "empty", "(", "$", "translations", ")", ")", "{", "foreach", "(", "$", "translations", "as", "$", "keys", ")", "{", "$", "languageInfo", "[", "]", "=", "$", "keys", ";", "}", "}", "}", "return", "$", "languageInfo", ";", "}" ]
Returns translation strings by language @param string $languageCode ISO language code @return array|false Array of arrays, each containing 'label' (translation index) and 'value' (translated string); false if language unavailable
[ "Returns", "translation", "strings", "by", "language" ]
72df150735664275a60a7861e468c6ff3b152a14
https://github.com/matomo-org/matomo/blob/72df150735664275a60a7861e468c6ff3b152a14/plugins/LanguagesManager/API.php#L202-L230
210,217
matomo-org/matomo
plugins/LanguagesManager/API.php
API.getPluginTranslationsForLanguage
public function getPluginTranslationsForLanguage($pluginName, $languageCode) { if (!$this->isLanguageAvailable($languageCode)) { return false; } $languageFile = Manager::getPluginDirectory($pluginName) . "/lang/$languageCode.json"; if (!file_exists($languageFile)) { return false; } $data = file_get_contents($languageFile); $translations = json_decode($data, true); $languageInfo = array(); foreach ($translations as $module => $keys) { foreach ($keys as $key => $value) { $languageInfo[] = array( 'label' => sprintf("%s_%s", $module, $key), 'value' => $value ); } } return $languageInfo; }
php
public function getPluginTranslationsForLanguage($pluginName, $languageCode) { if (!$this->isLanguageAvailable($languageCode)) { return false; } $languageFile = Manager::getPluginDirectory($pluginName) . "/lang/$languageCode.json"; if (!file_exists($languageFile)) { return false; } $data = file_get_contents($languageFile); $translations = json_decode($data, true); $languageInfo = array(); foreach ($translations as $module => $keys) { foreach ($keys as $key => $value) { $languageInfo[] = array( 'label' => sprintf("%s_%s", $module, $key), 'value' => $value ); } } return $languageInfo; }
[ "public", "function", "getPluginTranslationsForLanguage", "(", "$", "pluginName", ",", "$", "languageCode", ")", "{", "if", "(", "!", "$", "this", "->", "isLanguageAvailable", "(", "$", "languageCode", ")", ")", "{", "return", "false", ";", "}", "$", "languageFile", "=", "Manager", "::", "getPluginDirectory", "(", "$", "pluginName", ")", ".", "\"/lang/$languageCode.json\"", ";", "if", "(", "!", "file_exists", "(", "$", "languageFile", ")", ")", "{", "return", "false", ";", "}", "$", "data", "=", "file_get_contents", "(", "$", "languageFile", ")", ";", "$", "translations", "=", "json_decode", "(", "$", "data", ",", "true", ")", ";", "$", "languageInfo", "=", "array", "(", ")", ";", "foreach", "(", "$", "translations", "as", "$", "module", "=>", "$", "keys", ")", "{", "foreach", "(", "$", "keys", "as", "$", "key", "=>", "$", "value", ")", "{", "$", "languageInfo", "[", "]", "=", "array", "(", "'label'", "=>", "sprintf", "(", "\"%s_%s\"", ",", "$", "module", ",", "$", "key", ")", ",", "'value'", "=>", "$", "value", ")", ";", "}", "}", "return", "$", "languageInfo", ";", "}" ]
Returns translation strings by language for given plugin @param string $pluginName name of plugin @param string $languageCode ISO language code @return array|false Array of arrays, each containing 'label' (translation index) and 'value' (translated string); false if language unavailable @ignore
[ "Returns", "translation", "strings", "by", "language", "for", "given", "plugin" ]
72df150735664275a60a7861e468c6ff3b152a14
https://github.com/matomo-org/matomo/blob/72df150735664275a60a7861e468c6ff3b152a14/plugins/LanguagesManager/API.php#L241-L265
210,218
matomo-org/matomo
plugins/LanguagesManager/API.php
API.getLanguageForUser
public function getLanguageForUser($login) { if ($login == 'anonymous') { return false; } Piwik::checkUserHasSuperUserAccessOrIsTheUser($login); $lang = $this->getModel()->getLanguageForUser($login); return $lang; }
php
public function getLanguageForUser($login) { if ($login == 'anonymous') { return false; } Piwik::checkUserHasSuperUserAccessOrIsTheUser($login); $lang = $this->getModel()->getLanguageForUser($login); return $lang; }
[ "public", "function", "getLanguageForUser", "(", "$", "login", ")", "{", "if", "(", "$", "login", "==", "'anonymous'", ")", "{", "return", "false", ";", "}", "Piwik", "::", "checkUserHasSuperUserAccessOrIsTheUser", "(", "$", "login", ")", ";", "$", "lang", "=", "$", "this", "->", "getModel", "(", ")", "->", "getLanguageForUser", "(", "$", "login", ")", ";", "return", "$", "lang", ";", "}" ]
Returns the language for the user @param string $login @return string
[ "Returns", "the", "language", "for", "the", "user" ]
72df150735664275a60a7861e468c6ff3b152a14
https://github.com/matomo-org/matomo/blob/72df150735664275a60a7861e468c6ff3b152a14/plugins/LanguagesManager/API.php#L273-L284
210,219
matomo-org/matomo
plugins/UserCountry/LocationProvider.php
LocationProvider.getAllProviders
public static function getAllProviders() { if (is_null(self::$providers)) { self::$providers = array(); $plugins = PluginManager::getInstance()->getPluginsLoadedAndActivated(); foreach ($plugins as $plugin) { foreach (self::getLocationProviders($plugin) as $instance) { self::$providers[] = $instance; } } } return self::$providers; }
php
public static function getAllProviders() { if (is_null(self::$providers)) { self::$providers = array(); $plugins = PluginManager::getInstance()->getPluginsLoadedAndActivated(); foreach ($plugins as $plugin) { foreach (self::getLocationProviders($plugin) as $instance) { self::$providers[] = $instance; } } } return self::$providers; }
[ "public", "static", "function", "getAllProviders", "(", ")", "{", "if", "(", "is_null", "(", "self", "::", "$", "providers", ")", ")", "{", "self", "::", "$", "providers", "=", "array", "(", ")", ";", "$", "plugins", "=", "PluginManager", "::", "getInstance", "(", ")", "->", "getPluginsLoadedAndActivated", "(", ")", ";", "foreach", "(", "$", "plugins", "as", "$", "plugin", ")", "{", "foreach", "(", "self", "::", "getLocationProviders", "(", "$", "plugin", ")", "as", "$", "instance", ")", "{", "self", "::", "$", "providers", "[", "]", "=", "$", "instance", ";", "}", "}", "}", "return", "self", "::", "$", "providers", ";", "}" ]
Returns every available provider instance. @return LocationProvider[]
[ "Returns", "every", "available", "provider", "instance", "." ]
72df150735664275a60a7861e468c6ff3b152a14
https://github.com/matomo-org/matomo/blob/72df150735664275a60a7861e468c6ff3b152a14/plugins/UserCountry/LocationProvider.php#L166-L179
210,220
matomo-org/matomo
plugins/UserCountry/LocationProvider.php
LocationProvider.getLocationProviders
protected static function getLocationProviders(Plugin $plugin) { $locationProviders = $plugin->findMultipleComponents('LocationProvider', 'Piwik\\Plugins\\UserCountry\\LocationProvider'); $instances = []; foreach ($locationProviders as $locationProvider) { $instances[] = new $locationProvider(); } return $instances; }
php
protected static function getLocationProviders(Plugin $plugin) { $locationProviders = $plugin->findMultipleComponents('LocationProvider', 'Piwik\\Plugins\\UserCountry\\LocationProvider'); $instances = []; foreach ($locationProviders as $locationProvider) { $instances[] = new $locationProvider(); } return $instances; }
[ "protected", "static", "function", "getLocationProviders", "(", "Plugin", "$", "plugin", ")", "{", "$", "locationProviders", "=", "$", "plugin", "->", "findMultipleComponents", "(", "'LocationProvider'", ",", "'Piwik\\\\Plugins\\\\UserCountry\\\\LocationProvider'", ")", ";", "$", "instances", "=", "[", "]", ";", "foreach", "(", "$", "locationProviders", "as", "$", "locationProvider", ")", "{", "$", "instances", "[", "]", "=", "new", "$", "locationProvider", "(", ")", ";", "}", "return", "$", "instances", ";", "}" ]
Get all lo that are defined by the given plugin. @param Plugin $plugin @return LocationProvider[]
[ "Get", "all", "lo", "that", "are", "defined", "by", "the", "given", "plugin", "." ]
72df150735664275a60a7861e468c6ff3b152a14
https://github.com/matomo-org/matomo/blob/72df150735664275a60a7861e468c6ff3b152a14/plugins/UserCountry/LocationProvider.php#L187-L197
210,221
matomo-org/matomo
plugins/UserCountry/LocationProvider.php
LocationProvider.getAvailableProviders
public static function getAvailableProviders() { $result = array(); foreach (self::getAllProviders() as $provider) { if ($provider->isAvailable()) { $result[] = $provider; } } return $result; }
php
public static function getAvailableProviders() { $result = array(); foreach (self::getAllProviders() as $provider) { if ($provider->isAvailable()) { $result[] = $provider; } } return $result; }
[ "public", "static", "function", "getAvailableProviders", "(", ")", "{", "$", "result", "=", "array", "(", ")", ";", "foreach", "(", "self", "::", "getAllProviders", "(", ")", "as", "$", "provider", ")", "{", "if", "(", "$", "provider", "->", "isAvailable", "(", ")", ")", "{", "$", "result", "[", "]", "=", "$", "provider", ";", "}", "}", "return", "$", "result", ";", "}" ]
Returns all provider instances that are 'available'. An 'available' provider is one that is available for use. They may not necessarily be working. @return array
[ "Returns", "all", "provider", "instances", "that", "are", "available", ".", "An", "available", "provider", "is", "one", "that", "is", "available", "for", "use", ".", "They", "may", "not", "necessarily", "be", "working", "." ]
72df150735664275a60a7861e468c6ff3b152a14
https://github.com/matomo-org/matomo/blob/72df150735664275a60a7861e468c6ff3b152a14/plugins/UserCountry/LocationProvider.php#L205-L214
210,222
matomo-org/matomo
plugins/UserCountry/LocationProvider.php
LocationProvider.getCurrentProviderId
public static function getCurrentProviderId() { try { $optionValue = Option::get(self::CURRENT_PROVIDER_OPTION_NAME); } catch (\Exception $e) { $optionValue = false; } return $optionValue === false ? DefaultProvider::ID : $optionValue; }
php
public static function getCurrentProviderId() { try { $optionValue = Option::get(self::CURRENT_PROVIDER_OPTION_NAME); } catch (\Exception $e) { $optionValue = false; } return $optionValue === false ? DefaultProvider::ID : $optionValue; }
[ "public", "static", "function", "getCurrentProviderId", "(", ")", "{", "try", "{", "$", "optionValue", "=", "Option", "::", "get", "(", "self", "::", "CURRENT_PROVIDER_OPTION_NAME", ")", ";", "}", "catch", "(", "\\", "Exception", "$", "e", ")", "{", "$", "optionValue", "=", "false", ";", "}", "return", "$", "optionValue", "===", "false", "?", "DefaultProvider", "::", "ID", ":", "$", "optionValue", ";", "}" ]
Returns the ID of the currently used location provider. The used provider is stored in the 'usercountry.location_provider' option. This function should not be called by the Tracker. @return string
[ "Returns", "the", "ID", "of", "the", "currently", "used", "location", "provider", "." ]
72df150735664275a60a7861e468c6ff3b152a14
https://github.com/matomo-org/matomo/blob/72df150735664275a60a7861e468c6ff3b152a14/plugins/UserCountry/LocationProvider.php#L304-L312
210,223
matomo-org/matomo
plugins/UserCountry/LocationProvider.php
LocationProvider.setCurrentProvider
public static function setCurrentProvider($providerId) { $provider = self::getProviderById($providerId); if (empty($provider)) { throw new Exception( "Invalid provider ID '$providerId'. The provider either does not exist or is not available"); } $provider->activate(); Option::set(self::CURRENT_PROVIDER_OPTION_NAME, $providerId); Cache::clearCacheGeneral(); return $provider; }
php
public static function setCurrentProvider($providerId) { $provider = self::getProviderById($providerId); if (empty($provider)) { throw new Exception( "Invalid provider ID '$providerId'. The provider either does not exist or is not available"); } $provider->activate(); Option::set(self::CURRENT_PROVIDER_OPTION_NAME, $providerId); Cache::clearCacheGeneral(); return $provider; }
[ "public", "static", "function", "setCurrentProvider", "(", "$", "providerId", ")", "{", "$", "provider", "=", "self", "::", "getProviderById", "(", "$", "providerId", ")", ";", "if", "(", "empty", "(", "$", "provider", ")", ")", "{", "throw", "new", "Exception", "(", "\"Invalid provider ID '$providerId'. The provider either does not exist or is not available\"", ")", ";", "}", "$", "provider", "->", "activate", "(", ")", ";", "Option", "::", "set", "(", "self", "::", "CURRENT_PROVIDER_OPTION_NAME", ",", "$", "providerId", ")", ";", "Cache", "::", "clearCacheGeneral", "(", ")", ";", "return", "$", "provider", ";", "}" ]
Sets the provider to use when tracking. @param string $providerId The ID of the provider to use. @return \Piwik\Plugins\UserCountry\LocationProvider The new current provider. @throws Exception If the provider ID is invalid.
[ "Sets", "the", "provider", "to", "use", "when", "tracking", "." ]
72df150735664275a60a7861e468c6ff3b152a14
https://github.com/matomo-org/matomo/blob/72df150735664275a60a7861e468c6ff3b152a14/plugins/UserCountry/LocationProvider.php#L333-L346
210,224
matomo-org/matomo
plugins/UserCountry/LocationProvider.php
LocationProvider.getProviderById
public static function getProviderById($providerId) { foreach (self::getAllProviders() as $provider) { if ($provider->getId() == $providerId && $provider->isAvailable()) { return $provider; } } return null; }
php
public static function getProviderById($providerId) { foreach (self::getAllProviders() as $provider) { if ($provider->getId() == $providerId && $provider->isAvailable()) { return $provider; } } return null; }
[ "public", "static", "function", "getProviderById", "(", "$", "providerId", ")", "{", "foreach", "(", "self", "::", "getAllProviders", "(", ")", "as", "$", "provider", ")", "{", "if", "(", "$", "provider", "->", "getId", "(", ")", "==", "$", "providerId", "&&", "$", "provider", "->", "isAvailable", "(", ")", ")", "{", "return", "$", "provider", ";", "}", "}", "return", "null", ";", "}" ]
Returns a provider instance by ID or false if the ID is invalid or unavailable. @param string $providerId @return \Piwik\Plugins\UserCountry\LocationProvider|null
[ "Returns", "a", "provider", "instance", "by", "ID", "or", "false", "if", "the", "ID", "is", "invalid", "or", "unavailable", "." ]
72df150735664275a60a7861e468c6ff3b152a14
https://github.com/matomo-org/matomo/blob/72df150735664275a60a7861e468c6ff3b152a14/plugins/UserCountry/LocationProvider.php#L354-L363
210,225
matomo-org/matomo
plugins/UserCountry/LocationProvider.php
LocationProvider.completeLocationResult
public function completeLocationResult(&$location) { // fill in continent code if country code is present if (empty($location[self::CONTINENT_CODE_KEY]) && !empty($location[self::COUNTRY_CODE_KEY]) ) { $countryCode = strtolower($location[self::COUNTRY_CODE_KEY]); $location[self::CONTINENT_CODE_KEY] = Common::getContinent($countryCode); } // fill in continent name if continent code is present if (empty($location[self::CONTINENT_NAME_KEY]) && !empty($location[self::CONTINENT_CODE_KEY]) ) { $continentCode = strtolower($location[self::CONTINENT_CODE_KEY]); $location[self::CONTINENT_NAME_KEY] = continentTranslate($continentCode); } // fill in country name if country code is present if (empty($location[self::COUNTRY_NAME_KEY]) && !empty($location[self::COUNTRY_CODE_KEY]) ) { $countryCode = strtolower($location[self::COUNTRY_CODE_KEY]); $location[self::COUNTRY_NAME_KEY] = countryTranslate($countryCode); } // deal w/ improper latitude/longitude & round proper values if (!empty($location[self::LATITUDE_KEY])) { if (is_numeric($location[self::LATITUDE_KEY])) { $location[self::LATITUDE_KEY] = round($location[self::LATITUDE_KEY], self::GEOGRAPHIC_COORD_PRECISION); } else { unset($location[self::LATITUDE_KEY]); } } if (!empty($location[self::LONGITUDE_KEY])) { if (is_numeric($location[self::LONGITUDE_KEY])) { $location[self::LONGITUDE_KEY] = round($location[self::LONGITUDE_KEY], self::GEOGRAPHIC_COORD_PRECISION); } else { unset($location[self::LONGITUDE_KEY]); } } }
php
public function completeLocationResult(&$location) { // fill in continent code if country code is present if (empty($location[self::CONTINENT_CODE_KEY]) && !empty($location[self::COUNTRY_CODE_KEY]) ) { $countryCode = strtolower($location[self::COUNTRY_CODE_KEY]); $location[self::CONTINENT_CODE_KEY] = Common::getContinent($countryCode); } // fill in continent name if continent code is present if (empty($location[self::CONTINENT_NAME_KEY]) && !empty($location[self::CONTINENT_CODE_KEY]) ) { $continentCode = strtolower($location[self::CONTINENT_CODE_KEY]); $location[self::CONTINENT_NAME_KEY] = continentTranslate($continentCode); } // fill in country name if country code is present if (empty($location[self::COUNTRY_NAME_KEY]) && !empty($location[self::COUNTRY_CODE_KEY]) ) { $countryCode = strtolower($location[self::COUNTRY_CODE_KEY]); $location[self::COUNTRY_NAME_KEY] = countryTranslate($countryCode); } // deal w/ improper latitude/longitude & round proper values if (!empty($location[self::LATITUDE_KEY])) { if (is_numeric($location[self::LATITUDE_KEY])) { $location[self::LATITUDE_KEY] = round($location[self::LATITUDE_KEY], self::GEOGRAPHIC_COORD_PRECISION); } else { unset($location[self::LATITUDE_KEY]); } } if (!empty($location[self::LONGITUDE_KEY])) { if (is_numeric($location[self::LONGITUDE_KEY])) { $location[self::LONGITUDE_KEY] = round($location[self::LONGITUDE_KEY], self::GEOGRAPHIC_COORD_PRECISION); } else { unset($location[self::LONGITUDE_KEY]); } } }
[ "public", "function", "completeLocationResult", "(", "&", "$", "location", ")", "{", "// fill in continent code if country code is present", "if", "(", "empty", "(", "$", "location", "[", "self", "::", "CONTINENT_CODE_KEY", "]", ")", "&&", "!", "empty", "(", "$", "location", "[", "self", "::", "COUNTRY_CODE_KEY", "]", ")", ")", "{", "$", "countryCode", "=", "strtolower", "(", "$", "location", "[", "self", "::", "COUNTRY_CODE_KEY", "]", ")", ";", "$", "location", "[", "self", "::", "CONTINENT_CODE_KEY", "]", "=", "Common", "::", "getContinent", "(", "$", "countryCode", ")", ";", "}", "// fill in continent name if continent code is present", "if", "(", "empty", "(", "$", "location", "[", "self", "::", "CONTINENT_NAME_KEY", "]", ")", "&&", "!", "empty", "(", "$", "location", "[", "self", "::", "CONTINENT_CODE_KEY", "]", ")", ")", "{", "$", "continentCode", "=", "strtolower", "(", "$", "location", "[", "self", "::", "CONTINENT_CODE_KEY", "]", ")", ";", "$", "location", "[", "self", "::", "CONTINENT_NAME_KEY", "]", "=", "continentTranslate", "(", "$", "continentCode", ")", ";", "}", "// fill in country name if country code is present", "if", "(", "empty", "(", "$", "location", "[", "self", "::", "COUNTRY_NAME_KEY", "]", ")", "&&", "!", "empty", "(", "$", "location", "[", "self", "::", "COUNTRY_CODE_KEY", "]", ")", ")", "{", "$", "countryCode", "=", "strtolower", "(", "$", "location", "[", "self", "::", "COUNTRY_CODE_KEY", "]", ")", ";", "$", "location", "[", "self", "::", "COUNTRY_NAME_KEY", "]", "=", "countryTranslate", "(", "$", "countryCode", ")", ";", "}", "// deal w/ improper latitude/longitude & round proper values", "if", "(", "!", "empty", "(", "$", "location", "[", "self", "::", "LATITUDE_KEY", "]", ")", ")", "{", "if", "(", "is_numeric", "(", "$", "location", "[", "self", "::", "LATITUDE_KEY", "]", ")", ")", "{", "$", "location", "[", "self", "::", "LATITUDE_KEY", "]", "=", "round", "(", "$", "location", "[", "self", "::", "LATITUDE_KEY", "]", ",", "self", "::", "GEOGRAPHIC_COORD_PRECISION", ")", ";", "}", "else", "{", "unset", "(", "$", "location", "[", "self", "::", "LATITUDE_KEY", "]", ")", ";", "}", "}", "if", "(", "!", "empty", "(", "$", "location", "[", "self", "::", "LONGITUDE_KEY", "]", ")", ")", "{", "if", "(", "is_numeric", "(", "$", "location", "[", "self", "::", "LONGITUDE_KEY", "]", ")", ")", "{", "$", "location", "[", "self", "::", "LONGITUDE_KEY", "]", "=", "round", "(", "$", "location", "[", "self", "::", "LONGITUDE_KEY", "]", ",", "self", "::", "GEOGRAPHIC_COORD_PRECISION", ")", ";", "}", "else", "{", "unset", "(", "$", "location", "[", "self", "::", "LONGITUDE_KEY", "]", ")", ";", "}", "}", "}" ]
Tries to fill in any missing information in a location result. This method will try to set the continent code, continent name and country code using other information. Note: This function must always be called by location providers in getLocation. @param array $location The location information to modify.
[ "Tries", "to", "fill", "in", "any", "missing", "information", "in", "a", "location", "result", "." ]
72df150735664275a60a7861e468c6ff3b152a14
https://github.com/matomo-org/matomo/blob/72df150735664275a60a7861e468c6ff3b152a14/plugins/UserCountry/LocationProvider.php#L382-L424
210,226
matomo-org/matomo
plugins/UserCountry/LocationProvider.php
LocationProvider.prettyFormatLocation
public static function prettyFormatLocation($locationInfo, $newline = "\n", $includeExtra = false) { if ($locationInfo === false) { return Piwik::translate('General_Unknown'); } // add latitude/longitude line $lines = array(); if (!empty($locationInfo[self::LATITUDE_KEY]) && !empty($locationInfo[self::LONGITUDE_KEY]) ) { $lines[] = '(' . $locationInfo[self::LATITUDE_KEY] . ', ' . $locationInfo[self::LONGITUDE_KEY] . ')'; } // add city/state line $cityState = array(); if (!empty($locationInfo[self::CITY_NAME_KEY])) { $cityState[] = $locationInfo[self::CITY_NAME_KEY]; } if (!empty($locationInfo[self::REGION_CODE_KEY])) { $cityState[] = $locationInfo[self::REGION_CODE_KEY]; } else if (!empty($locationInfo[self::REGION_NAME_KEY])) { $cityState[] = $locationInfo[self::REGION_NAME_KEY]; } if (!empty($cityState)) { $lines[] = implode(', ', $cityState); } // add postal code line if (!empty($locationInfo[self::POSTAL_CODE_KEY])) { $lines[] = $locationInfo[self::POSTAL_CODE_KEY]; } // add country line if (!empty($locationInfo[self::COUNTRY_NAME_KEY])) { $lines[] = $locationInfo[self::COUNTRY_NAME_KEY]; } else if (!empty($locationInfo[self::COUNTRY_CODE_KEY])) { $lines[] = $locationInfo[self::COUNTRY_CODE_KEY]; } // add extra information (ISP/Organization) if ($includeExtra) { $lines[] = ''; $unknown = Piwik::translate('General_Unknown'); $org = !empty($locationInfo[self::ORG_KEY]) ? $locationInfo[self::ORG_KEY] : $unknown; $lines[] = "Org: $org"; $isp = !empty($locationInfo[self::ISP_KEY]) ? $locationInfo[self::ISP_KEY] : $unknown; $lines[] = "ISP: $isp"; } return implode($newline, $lines); }
php
public static function prettyFormatLocation($locationInfo, $newline = "\n", $includeExtra = false) { if ($locationInfo === false) { return Piwik::translate('General_Unknown'); } // add latitude/longitude line $lines = array(); if (!empty($locationInfo[self::LATITUDE_KEY]) && !empty($locationInfo[self::LONGITUDE_KEY]) ) { $lines[] = '(' . $locationInfo[self::LATITUDE_KEY] . ', ' . $locationInfo[self::LONGITUDE_KEY] . ')'; } // add city/state line $cityState = array(); if (!empty($locationInfo[self::CITY_NAME_KEY])) { $cityState[] = $locationInfo[self::CITY_NAME_KEY]; } if (!empty($locationInfo[self::REGION_CODE_KEY])) { $cityState[] = $locationInfo[self::REGION_CODE_KEY]; } else if (!empty($locationInfo[self::REGION_NAME_KEY])) { $cityState[] = $locationInfo[self::REGION_NAME_KEY]; } if (!empty($cityState)) { $lines[] = implode(', ', $cityState); } // add postal code line if (!empty($locationInfo[self::POSTAL_CODE_KEY])) { $lines[] = $locationInfo[self::POSTAL_CODE_KEY]; } // add country line if (!empty($locationInfo[self::COUNTRY_NAME_KEY])) { $lines[] = $locationInfo[self::COUNTRY_NAME_KEY]; } else if (!empty($locationInfo[self::COUNTRY_CODE_KEY])) { $lines[] = $locationInfo[self::COUNTRY_CODE_KEY]; } // add extra information (ISP/Organization) if ($includeExtra) { $lines[] = ''; $unknown = Piwik::translate('General_Unknown'); $org = !empty($locationInfo[self::ORG_KEY]) ? $locationInfo[self::ORG_KEY] : $unknown; $lines[] = "Org: $org"; $isp = !empty($locationInfo[self::ISP_KEY]) ? $locationInfo[self::ISP_KEY] : $unknown; $lines[] = "ISP: $isp"; } return implode($newline, $lines); }
[ "public", "static", "function", "prettyFormatLocation", "(", "$", "locationInfo", ",", "$", "newline", "=", "\"\\n\"", ",", "$", "includeExtra", "=", "false", ")", "{", "if", "(", "$", "locationInfo", "===", "false", ")", "{", "return", "Piwik", "::", "translate", "(", "'General_Unknown'", ")", ";", "}", "// add latitude/longitude line", "$", "lines", "=", "array", "(", ")", ";", "if", "(", "!", "empty", "(", "$", "locationInfo", "[", "self", "::", "LATITUDE_KEY", "]", ")", "&&", "!", "empty", "(", "$", "locationInfo", "[", "self", "::", "LONGITUDE_KEY", "]", ")", ")", "{", "$", "lines", "[", "]", "=", "'('", ".", "$", "locationInfo", "[", "self", "::", "LATITUDE_KEY", "]", ".", "', '", ".", "$", "locationInfo", "[", "self", "::", "LONGITUDE_KEY", "]", ".", "')'", ";", "}", "// add city/state line", "$", "cityState", "=", "array", "(", ")", ";", "if", "(", "!", "empty", "(", "$", "locationInfo", "[", "self", "::", "CITY_NAME_KEY", "]", ")", ")", "{", "$", "cityState", "[", "]", "=", "$", "locationInfo", "[", "self", "::", "CITY_NAME_KEY", "]", ";", "}", "if", "(", "!", "empty", "(", "$", "locationInfo", "[", "self", "::", "REGION_CODE_KEY", "]", ")", ")", "{", "$", "cityState", "[", "]", "=", "$", "locationInfo", "[", "self", "::", "REGION_CODE_KEY", "]", ";", "}", "else", "if", "(", "!", "empty", "(", "$", "locationInfo", "[", "self", "::", "REGION_NAME_KEY", "]", ")", ")", "{", "$", "cityState", "[", "]", "=", "$", "locationInfo", "[", "self", "::", "REGION_NAME_KEY", "]", ";", "}", "if", "(", "!", "empty", "(", "$", "cityState", ")", ")", "{", "$", "lines", "[", "]", "=", "implode", "(", "', '", ",", "$", "cityState", ")", ";", "}", "// add postal code line", "if", "(", "!", "empty", "(", "$", "locationInfo", "[", "self", "::", "POSTAL_CODE_KEY", "]", ")", ")", "{", "$", "lines", "[", "]", "=", "$", "locationInfo", "[", "self", "::", "POSTAL_CODE_KEY", "]", ";", "}", "// add country line", "if", "(", "!", "empty", "(", "$", "locationInfo", "[", "self", "::", "COUNTRY_NAME_KEY", "]", ")", ")", "{", "$", "lines", "[", "]", "=", "$", "locationInfo", "[", "self", "::", "COUNTRY_NAME_KEY", "]", ";", "}", "else", "if", "(", "!", "empty", "(", "$", "locationInfo", "[", "self", "::", "COUNTRY_CODE_KEY", "]", ")", ")", "{", "$", "lines", "[", "]", "=", "$", "locationInfo", "[", "self", "::", "COUNTRY_CODE_KEY", "]", ";", "}", "// add extra information (ISP/Organization)", "if", "(", "$", "includeExtra", ")", "{", "$", "lines", "[", "]", "=", "''", ";", "$", "unknown", "=", "Piwik", "::", "translate", "(", "'General_Unknown'", ")", ";", "$", "org", "=", "!", "empty", "(", "$", "locationInfo", "[", "self", "::", "ORG_KEY", "]", ")", "?", "$", "locationInfo", "[", "self", "::", "ORG_KEY", "]", ":", "$", "unknown", ";", "$", "lines", "[", "]", "=", "\"Org: $org\"", ";", "$", "isp", "=", "!", "empty", "(", "$", "locationInfo", "[", "self", "::", "ISP_KEY", "]", ")", "?", "$", "locationInfo", "[", "self", "::", "ISP_KEY", "]", ":", "$", "unknown", ";", "$", "lines", "[", "]", "=", "\"ISP: $isp\"", ";", "}", "return", "implode", "(", "$", "newline", ",", "$", "lines", ")", ";", "}" ]
Returns a prettified location result. @param array|false $locationInfo @param string $newline The line separator (ie, \n or <br/>). @param bool $includeExtra Whether to include ISP/Organization info. @return string
[ "Returns", "a", "prettified", "location", "result", "." ]
72df150735664275a60a7861e468c6ff3b152a14
https://github.com/matomo-org/matomo/blob/72df150735664275a60a7861e468c6ff3b152a14/plugins/UserCountry/LocationProvider.php#L434-L490
210,227
matomo-org/matomo
core/Tracker/IgnoreCookie.php
IgnoreCookie.getTrackingCookie
private static function getTrackingCookie() { $cookie_name = @Config::getInstance()->Tracker['cookie_name']; $cookie_path = @Config::getInstance()->Tracker['cookie_path']; return new Cookie($cookie_name, null, $cookie_path); }
php
private static function getTrackingCookie() { $cookie_name = @Config::getInstance()->Tracker['cookie_name']; $cookie_path = @Config::getInstance()->Tracker['cookie_path']; return new Cookie($cookie_name, null, $cookie_path); }
[ "private", "static", "function", "getTrackingCookie", "(", ")", "{", "$", "cookie_name", "=", "@", "Config", "::", "getInstance", "(", ")", "->", "Tracker", "[", "'cookie_name'", "]", ";", "$", "cookie_path", "=", "@", "Config", "::", "getInstance", "(", ")", "->", "Tracker", "[", "'cookie_path'", "]", ";", "return", "new", "Cookie", "(", "$", "cookie_name", ",", "null", ",", "$", "cookie_path", ")", ";", "}" ]
Get tracking cookie @return Cookie
[ "Get", "tracking", "cookie" ]
72df150735664275a60a7861e468c6ff3b152a14
https://github.com/matomo-org/matomo/blob/72df150735664275a60a7861e468c6ff3b152a14/core/Tracker/IgnoreCookie.php#L25-L31
210,228
matomo-org/matomo
libs/Zend/Db/Statement/Db2.php
Zend_Db_Statement_Db2._prepare
public function _prepare($sql) { $connection = $this->_adapter->getConnection(); // db2_prepare on i5 emits errors, these need to be // suppressed so that proper exceptions can be thrown $this->_stmt = @db2_prepare($connection, $sql); if (!$this->_stmt) { /** * @see Zend_Db_Statement_Db2_Exception */ // require_once 'Zend/Db/Statement/Db2/Exception.php'; throw new Zend_Db_Statement_Db2_Exception( db2_stmt_errormsg(), db2_stmt_error() ); } }
php
public function _prepare($sql) { $connection = $this->_adapter->getConnection(); // db2_prepare on i5 emits errors, these need to be // suppressed so that proper exceptions can be thrown $this->_stmt = @db2_prepare($connection, $sql); if (!$this->_stmt) { /** * @see Zend_Db_Statement_Db2_Exception */ // require_once 'Zend/Db/Statement/Db2/Exception.php'; throw new Zend_Db_Statement_Db2_Exception( db2_stmt_errormsg(), db2_stmt_error() ); } }
[ "public", "function", "_prepare", "(", "$", "sql", ")", "{", "$", "connection", "=", "$", "this", "->", "_adapter", "->", "getConnection", "(", ")", ";", "// db2_prepare on i5 emits errors, these need to be", "// suppressed so that proper exceptions can be thrown", "$", "this", "->", "_stmt", "=", "@", "db2_prepare", "(", "$", "connection", ",", "$", "sql", ")", ";", "if", "(", "!", "$", "this", "->", "_stmt", ")", "{", "/**\n * @see Zend_Db_Statement_Db2_Exception\n */", "// require_once 'Zend/Db/Statement/Db2/Exception.php';", "throw", "new", "Zend_Db_Statement_Db2_Exception", "(", "db2_stmt_errormsg", "(", ")", ",", "db2_stmt_error", "(", ")", ")", ";", "}", "}" ]
Prepare a statement handle. @param string $sql @return void @throws Zend_Db_Statement_Db2_Exception
[ "Prepare", "a", "statement", "handle", "." ]
72df150735664275a60a7861e468c6ff3b152a14
https://github.com/matomo-org/matomo/blob/72df150735664275a60a7861e468c6ff3b152a14/libs/Zend/Db/Statement/Db2.php#L56-L74
210,229
matomo-org/matomo
core/DataTable/Filter/ColumnCallbackDeleteRow.php
ColumnCallbackDeleteRow.filter
public function filter($table) { foreach ($table->getRows() as $key => $row) { $params = array(); foreach ($this->columnsToFilter as $column) { $params[] = $row->getColumn($column); } $params = array_merge($params, $this->functionParams); if (call_user_func_array($this->function, $params) === true) { $table->deleteRow($key); } $this->filterSubTable($row); } }
php
public function filter($table) { foreach ($table->getRows() as $key => $row) { $params = array(); foreach ($this->columnsToFilter as $column) { $params[] = $row->getColumn($column); } $params = array_merge($params, $this->functionParams); if (call_user_func_array($this->function, $params) === true) { $table->deleteRow($key); } $this->filterSubTable($row); } }
[ "public", "function", "filter", "(", "$", "table", ")", "{", "foreach", "(", "$", "table", "->", "getRows", "(", ")", "as", "$", "key", "=>", "$", "row", ")", "{", "$", "params", "=", "array", "(", ")", ";", "foreach", "(", "$", "this", "->", "columnsToFilter", "as", "$", "column", ")", "{", "$", "params", "[", "]", "=", "$", "row", "->", "getColumn", "(", "$", "column", ")", ";", "}", "$", "params", "=", "array_merge", "(", "$", "params", ",", "$", "this", "->", "functionParams", ")", ";", "if", "(", "call_user_func_array", "(", "$", "this", "->", "function", ",", "$", "params", ")", "===", "true", ")", "{", "$", "table", "->", "deleteRow", "(", "$", "key", ")", ";", "}", "$", "this", "->", "filterSubTable", "(", "$", "row", ")", ";", "}", "}" ]
Filters the given data table @param DataTable $table
[ "Filters", "the", "given", "data", "table" ]
72df150735664275a60a7861e468c6ff3b152a14
https://github.com/matomo-org/matomo/blob/72df150735664275a60a7861e468c6ff3b152a14/core/DataTable/Filter/ColumnCallbackDeleteRow.php#L64-L79
210,230
matomo-org/matomo
core/Scheduler/Timetable.php
Timetable.shouldExecuteTask
public function shouldExecuteTask($taskName) { $forceTaskExecution = (defined('DEBUG_FORCE_SCHEDULED_TASKS') && DEBUG_FORCE_SCHEDULED_TASKS); if ($forceTaskExecution) { return true; } return $this->taskHasBeenScheduledOnce($taskName) && time() >= $this->timetable[$taskName]; }
php
public function shouldExecuteTask($taskName) { $forceTaskExecution = (defined('DEBUG_FORCE_SCHEDULED_TASKS') && DEBUG_FORCE_SCHEDULED_TASKS); if ($forceTaskExecution) { return true; } return $this->taskHasBeenScheduledOnce($taskName) && time() >= $this->timetable[$taskName]; }
[ "public", "function", "shouldExecuteTask", "(", "$", "taskName", ")", "{", "$", "forceTaskExecution", "=", "(", "defined", "(", "'DEBUG_FORCE_SCHEDULED_TASKS'", ")", "&&", "DEBUG_FORCE_SCHEDULED_TASKS", ")", ";", "if", "(", "$", "forceTaskExecution", ")", "{", "return", "true", ";", "}", "return", "$", "this", "->", "taskHasBeenScheduledOnce", "(", "$", "taskName", ")", "&&", "time", "(", ")", ">=", "$", "this", "->", "timetable", "[", "$", "taskName", "]", ";", "}" ]
Checks if the task should be executed Task has to be executed if : - the task has already been scheduled once and the current system time is greater than the scheduled time. - execution is forced, see $forceTaskExecution @param string $taskName @return boolean
[ "Checks", "if", "the", "task", "should", "be", "executed" ]
72df150735664275a60a7861e468c6ff3b152a14
https://github.com/matomo-org/matomo/blob/72df150735664275a60a7861e468c6ff3b152a14/core/Scheduler/Timetable.php#L81-L90
210,231
matomo-org/matomo
core/Validators/BaseValidator.php
BaseValidator.check
public static function check($name, $value, $validators) { foreach ($validators as $validator) { try { $validator->validate($value); } catch (\Exception $e) { throw new Exception(strip_tags($name) . ': ' . $e->getMessage(), $e->getCode()); } } }
php
public static function check($name, $value, $validators) { foreach ($validators as $validator) { try { $validator->validate($value); } catch (\Exception $e) { throw new Exception(strip_tags($name) . ': ' . $e->getMessage(), $e->getCode()); } } }
[ "public", "static", "function", "check", "(", "$", "name", ",", "$", "value", ",", "$", "validators", ")", "{", "foreach", "(", "$", "validators", "as", "$", "validator", ")", "{", "try", "{", "$", "validator", "->", "validate", "(", "$", "value", ")", ";", "}", "catch", "(", "\\", "Exception", "$", "e", ")", "{", "throw", "new", "Exception", "(", "strip_tags", "(", "$", "name", ")", ".", "': '", ".", "$", "e", "->", "getMessage", "(", ")", ",", "$", "e", "->", "getCode", "(", ")", ")", ";", "}", "}", "}" ]
Lets you easily check a value against multiple validators. @param string $name The name/description of the field you want to validate the value for. The name will be prefixed in case there is any error. @param mixed $value The value which needs to be tested @param BaseValidator[] $validators
[ "Lets", "you", "easily", "check", "a", "value", "against", "multiple", "validators", "." ]
72df150735664275a60a7861e468c6ff3b152a14
https://github.com/matomo-org/matomo/blob/72df150735664275a60a7861e468c6ff3b152a14/core/Validators/BaseValidator.php#L38-L47
210,232
matomo-org/matomo
core/View/OneClickDone.php
OneClickDone.render
public function render() { // set response headers @Common::stripHeader('Pragma'); @Common::stripHeader('Expires'); @Common::sendHeader('Content-Type: text/html; charset=UTF-8'); @Common::sendHeader('Cache-Control: must-revalidate'); @Common::sendHeader('X-Frame-Options: deny'); $error = htmlspecialchars($this->error, ENT_QUOTES, 'UTF-8'); $messages = htmlspecialchars(serialize($this->feedbackMessages), ENT_QUOTES, 'UTF-8'); $tokenAuth = $this->tokenAuth; $httpsFail = (int) $this->httpsFail; // use a heredoc instead of an external file echo <<<END_OF_TEMPLATE <!DOCTYPE html> <html> <head> <meta name="robots" content="noindex,nofollow"> <meta charset="utf-8"> <title></title> </head> <body> <form name="myform" method="post" action="?module=CoreUpdater&amp;action=oneClickResults"> <input type="hidden" name="token_auth" value="$tokenAuth" /> <input type="hidden" name="error" value="$error" /> <input type="hidden" name="messages" value="$messages" /> <input type="hidden" name="httpsFail" value="$httpsFail" /> <noscript> <button type="submit">Continue</button> </noscript> </form> <script type="text/javascript"> document.myform.submit(); </script> </body> </html> END_OF_TEMPLATE; }
php
public function render() { // set response headers @Common::stripHeader('Pragma'); @Common::stripHeader('Expires'); @Common::sendHeader('Content-Type: text/html; charset=UTF-8'); @Common::sendHeader('Cache-Control: must-revalidate'); @Common::sendHeader('X-Frame-Options: deny'); $error = htmlspecialchars($this->error, ENT_QUOTES, 'UTF-8'); $messages = htmlspecialchars(serialize($this->feedbackMessages), ENT_QUOTES, 'UTF-8'); $tokenAuth = $this->tokenAuth; $httpsFail = (int) $this->httpsFail; // use a heredoc instead of an external file echo <<<END_OF_TEMPLATE <!DOCTYPE html> <html> <head> <meta name="robots" content="noindex,nofollow"> <meta charset="utf-8"> <title></title> </head> <body> <form name="myform" method="post" action="?module=CoreUpdater&amp;action=oneClickResults"> <input type="hidden" name="token_auth" value="$tokenAuth" /> <input type="hidden" name="error" value="$error" /> <input type="hidden" name="messages" value="$messages" /> <input type="hidden" name="httpsFail" value="$httpsFail" /> <noscript> <button type="submit">Continue</button> </noscript> </form> <script type="text/javascript"> document.myform.submit(); </script> </body> </html> END_OF_TEMPLATE; }
[ "public", "function", "render", "(", ")", "{", "// set response headers", "@", "Common", "::", "stripHeader", "(", "'Pragma'", ")", ";", "@", "Common", "::", "stripHeader", "(", "'Expires'", ")", ";", "@", "Common", "::", "sendHeader", "(", "'Content-Type: text/html; charset=UTF-8'", ")", ";", "@", "Common", "::", "sendHeader", "(", "'Cache-Control: must-revalidate'", ")", ";", "@", "Common", "::", "sendHeader", "(", "'X-Frame-Options: deny'", ")", ";", "$", "error", "=", "htmlspecialchars", "(", "$", "this", "->", "error", ",", "ENT_QUOTES", ",", "'UTF-8'", ")", ";", "$", "messages", "=", "htmlspecialchars", "(", "serialize", "(", "$", "this", "->", "feedbackMessages", ")", ",", "ENT_QUOTES", ",", "'UTF-8'", ")", ";", "$", "tokenAuth", "=", "$", "this", "->", "tokenAuth", ";", "$", "httpsFail", "=", "(", "int", ")", "$", "this", "->", "httpsFail", ";", "// use a heredoc instead of an external file", "echo", " <<<END_OF_TEMPLATE\n<!DOCTYPE html>\n<html>\n <head>\n <meta name=\"robots\" content=\"noindex,nofollow\">\n <meta charset=\"utf-8\">\n <title></title>\n </head>\n <body>\n <form name=\"myform\" method=\"post\" action=\"?module=CoreUpdater&amp;action=oneClickResults\">\n <input type=\"hidden\" name=\"token_auth\" value=\"$tokenAuth\" />\n <input type=\"hidden\" name=\"error\" value=\"$error\" />\n <input type=\"hidden\" name=\"messages\" value=\"$messages\" />\n <input type=\"hidden\" name=\"httpsFail\" value=\"$httpsFail\" />\n <noscript>\n <button type=\"submit\">Continue</button>\n </noscript>\n </form>\n <script type=\"text/javascript\">\n document.myform.submit();\n </script>\n </body>\n</html>\nEND_OF_TEMPLATE", ";", "}" ]
Outputs the data. @return string html
[ "Outputs", "the", "data", "." ]
72df150735664275a60a7861e468c6ff3b152a14
https://github.com/matomo-org/matomo/blob/72df150735664275a60a7861e468c6ff3b152a14/core/View/OneClickDone.php#L59-L98
210,233
matomo-org/matomo
core/BaseFactory.php
BaseFactory.factory
public static function factory($classId) { $className = static::getClassNameFromClassId($classId); if (!class_exists($className)) { self::sendPlainHeader(); throw new Exception(static::getInvalidClassIdExceptionMessage($classId)); } return new $className; }
php
public static function factory($classId) { $className = static::getClassNameFromClassId($classId); if (!class_exists($className)) { self::sendPlainHeader(); throw new Exception(static::getInvalidClassIdExceptionMessage($classId)); } return new $className; }
[ "public", "static", "function", "factory", "(", "$", "classId", ")", "{", "$", "className", "=", "static", "::", "getClassNameFromClassId", "(", "$", "classId", ")", ";", "if", "(", "!", "class_exists", "(", "$", "className", ")", ")", "{", "self", "::", "sendPlainHeader", "(", ")", ";", "throw", "new", "Exception", "(", "static", "::", "getInvalidClassIdExceptionMessage", "(", "$", "classId", ")", ")", ";", "}", "return", "new", "$", "className", ";", "}" ]
Creates a new instance of a class using a string ID. @param string $classId The ID of the class. @return \Piwik\DataTable\Renderer @throws Exception if $classId is invalid.
[ "Creates", "a", "new", "instance", "of", "a", "class", "using", "a", "string", "ID", "." ]
72df150735664275a60a7861e468c6ff3b152a14
https://github.com/matomo-org/matomo/blob/72df150735664275a60a7861e468c6ff3b152a14/core/BaseFactory.php#L32-L42
210,234
matomo-org/matomo
plugins/LanguagesManager/Controller.php
Controller.saveLanguage
public function saveLanguage() { $language = Common::getRequestVar('language'); // Prevent CSRF only when piwik is not installed yet (During install user can change language) if (DbHelper::isInstalled()) { $this->checkTokenInUrl(); } LanguagesManager::setLanguageForSession($language); Url::redirectToReferrer(); }
php
public function saveLanguage() { $language = Common::getRequestVar('language'); // Prevent CSRF only when piwik is not installed yet (During install user can change language) if (DbHelper::isInstalled()) { $this->checkTokenInUrl(); } LanguagesManager::setLanguageForSession($language); Url::redirectToReferrer(); }
[ "public", "function", "saveLanguage", "(", ")", "{", "$", "language", "=", "Common", "::", "getRequestVar", "(", "'language'", ")", ";", "// Prevent CSRF only when piwik is not installed yet (During install user can change language)", "if", "(", "DbHelper", "::", "isInstalled", "(", ")", ")", "{", "$", "this", "->", "checkTokenInUrl", "(", ")", ";", "}", "LanguagesManager", "::", "setLanguageForSession", "(", "$", "language", ")", ";", "Url", "::", "redirectToReferrer", "(", ")", ";", "}" ]
anonymous = in the session authenticated user = in the session
[ "anonymous", "=", "in", "the", "session", "authenticated", "user", "=", "in", "the", "session" ]
72df150735664275a60a7861e468c6ff3b152a14
https://github.com/matomo-org/matomo/blob/72df150735664275a60a7861e468c6ff3b152a14/plugins/LanguagesManager/Controller.php#L26-L37
210,235
matomo-org/matomo
core/IP.php
IP.getIpFromHeader
public static function getIpFromHeader() { $general = Config::getInstance()->General; $clientHeaders = @$general['proxy_client_headers']; if (!is_array($clientHeaders)) { $clientHeaders = array(); } $default = '0.0.0.0'; if (isset($_SERVER['REMOTE_ADDR'])) { $default = $_SERVER['REMOTE_ADDR']; } $ipString = self::getNonProxyIpFromHeader($default, $clientHeaders); return IPUtils::sanitizeIp($ipString); }
php
public static function getIpFromHeader() { $general = Config::getInstance()->General; $clientHeaders = @$general['proxy_client_headers']; if (!is_array($clientHeaders)) { $clientHeaders = array(); } $default = '0.0.0.0'; if (isset($_SERVER['REMOTE_ADDR'])) { $default = $_SERVER['REMOTE_ADDR']; } $ipString = self::getNonProxyIpFromHeader($default, $clientHeaders); return IPUtils::sanitizeIp($ipString); }
[ "public", "static", "function", "getIpFromHeader", "(", ")", "{", "$", "general", "=", "Config", "::", "getInstance", "(", ")", "->", "General", ";", "$", "clientHeaders", "=", "@", "$", "general", "[", "'proxy_client_headers'", "]", ";", "if", "(", "!", "is_array", "(", "$", "clientHeaders", ")", ")", "{", "$", "clientHeaders", "=", "array", "(", ")", ";", "}", "$", "default", "=", "'0.0.0.0'", ";", "if", "(", "isset", "(", "$", "_SERVER", "[", "'REMOTE_ADDR'", "]", ")", ")", "{", "$", "default", "=", "$", "_SERVER", "[", "'REMOTE_ADDR'", "]", ";", "}", "$", "ipString", "=", "self", "::", "getNonProxyIpFromHeader", "(", "$", "default", ",", "$", "clientHeaders", ")", ";", "return", "IPUtils", "::", "sanitizeIp", "(", "$", "ipString", ")", ";", "}" ]
Returns the most accurate IP address available for the current user, in IPv4 format. This could be the proxy client's IP address. @return string IP address in presentation format.
[ "Returns", "the", "most", "accurate", "IP", "address", "available", "for", "the", "current", "user", "in", "IPv4", "format", ".", "This", "could", "be", "the", "proxy", "client", "s", "IP", "address", "." ]
72df150735664275a60a7861e468c6ff3b152a14
https://github.com/matomo-org/matomo/blob/72df150735664275a60a7861e468c6ff3b152a14/core/IP.php#L46-L61
210,236
matomo-org/matomo
core/IP.php
IP.getNonProxyIpFromHeader
public static function getNonProxyIpFromHeader($default, $proxyHeaders) { $proxyIps = array(); $config = Config::getInstance()->General; if (isset($config['proxy_ips'])) { $proxyIps = $config['proxy_ips']; } if (!is_array($proxyIps)) { $proxyIps = array(); } $proxyIps[] = $default; // examine proxy headers foreach ($proxyHeaders as $proxyHeader) { if (!empty($_SERVER[$proxyHeader])) { // this may be buggy if someone has proxy IPs and proxy host headers configured as // `$_SERVER[$proxyHeader]` could be eg $_SERVER['HTTP_X_FORWARDED_HOST'] and // include an actual host name, not an IP $proxyIp = self::getFirstIpFromList($_SERVER[$proxyHeader], $proxyIps); if (strlen($proxyIp) && stripos($proxyIp, 'unknown') === false) { return $proxyIp; } } } return $default; }
php
public static function getNonProxyIpFromHeader($default, $proxyHeaders) { $proxyIps = array(); $config = Config::getInstance()->General; if (isset($config['proxy_ips'])) { $proxyIps = $config['proxy_ips']; } if (!is_array($proxyIps)) { $proxyIps = array(); } $proxyIps[] = $default; // examine proxy headers foreach ($proxyHeaders as $proxyHeader) { if (!empty($_SERVER[$proxyHeader])) { // this may be buggy if someone has proxy IPs and proxy host headers configured as // `$_SERVER[$proxyHeader]` could be eg $_SERVER['HTTP_X_FORWARDED_HOST'] and // include an actual host name, not an IP $proxyIp = self::getFirstIpFromList($_SERVER[$proxyHeader], $proxyIps); if (strlen($proxyIp) && stripos($proxyIp, 'unknown') === false) { return $proxyIp; } } } return $default; }
[ "public", "static", "function", "getNonProxyIpFromHeader", "(", "$", "default", ",", "$", "proxyHeaders", ")", "{", "$", "proxyIps", "=", "array", "(", ")", ";", "$", "config", "=", "Config", "::", "getInstance", "(", ")", "->", "General", ";", "if", "(", "isset", "(", "$", "config", "[", "'proxy_ips'", "]", ")", ")", "{", "$", "proxyIps", "=", "$", "config", "[", "'proxy_ips'", "]", ";", "}", "if", "(", "!", "is_array", "(", "$", "proxyIps", ")", ")", "{", "$", "proxyIps", "=", "array", "(", ")", ";", "}", "$", "proxyIps", "[", "]", "=", "$", "default", ";", "// examine proxy headers", "foreach", "(", "$", "proxyHeaders", "as", "$", "proxyHeader", ")", "{", "if", "(", "!", "empty", "(", "$", "_SERVER", "[", "$", "proxyHeader", "]", ")", ")", "{", "// this may be buggy if someone has proxy IPs and proxy host headers configured as", "// `$_SERVER[$proxyHeader]` could be eg $_SERVER['HTTP_X_FORWARDED_HOST'] and", "// include an actual host name, not an IP", "$", "proxyIp", "=", "self", "::", "getFirstIpFromList", "(", "$", "_SERVER", "[", "$", "proxyHeader", "]", ",", "$", "proxyIps", ")", ";", "if", "(", "strlen", "(", "$", "proxyIp", ")", "&&", "stripos", "(", "$", "proxyIp", ",", "'unknown'", ")", "===", "false", ")", "{", "return", "$", "proxyIp", ";", "}", "}", "}", "return", "$", "default", ";", "}" ]
Returns a non-proxy IP address from header. @param string $default Default value to return if there no matching proxy header. @param array $proxyHeaders List of proxy headers. @return string
[ "Returns", "a", "non", "-", "proxy", "IP", "address", "from", "header", "." ]
72df150735664275a60a7861e468c6ff3b152a14
https://github.com/matomo-org/matomo/blob/72df150735664275a60a7861e468c6ff3b152a14/core/IP.php#L70-L97
210,237
matomo-org/matomo
core/IP.php
IP.getFirstIpFromList
public static function getFirstIpFromList($csv, $excludedIps = null) { $p = strrpos($csv, ','); if ($p !== false) { $elements = explode(',', $csv); foreach ($elements as $ipString) { $element = trim(Common::sanitizeInputValue($ipString)); if(empty($element)) { continue; } $ip = \Piwik\Network\IP::fromStringIP(IPUtils::sanitizeIp($element)); if (empty($excludedIps) || (!in_array($element, $excludedIps) && !$ip->isInRanges($excludedIps))) { return $element; } } return ''; } return trim(Common::sanitizeInputValue($csv)); }
php
public static function getFirstIpFromList($csv, $excludedIps = null) { $p = strrpos($csv, ','); if ($p !== false) { $elements = explode(',', $csv); foreach ($elements as $ipString) { $element = trim(Common::sanitizeInputValue($ipString)); if(empty($element)) { continue; } $ip = \Piwik\Network\IP::fromStringIP(IPUtils::sanitizeIp($element)); if (empty($excludedIps) || (!in_array($element, $excludedIps) && !$ip->isInRanges($excludedIps))) { return $element; } } return ''; } return trim(Common::sanitizeInputValue($csv)); }
[ "public", "static", "function", "getFirstIpFromList", "(", "$", "csv", ",", "$", "excludedIps", "=", "null", ")", "{", "$", "p", "=", "strrpos", "(", "$", "csv", ",", "','", ")", ";", "if", "(", "$", "p", "!==", "false", ")", "{", "$", "elements", "=", "explode", "(", "','", ",", "$", "csv", ")", ";", "foreach", "(", "$", "elements", "as", "$", "ipString", ")", "{", "$", "element", "=", "trim", "(", "Common", "::", "sanitizeInputValue", "(", "$", "ipString", ")", ")", ";", "if", "(", "empty", "(", "$", "element", ")", ")", "{", "continue", ";", "}", "$", "ip", "=", "\\", "Piwik", "\\", "Network", "\\", "IP", "::", "fromStringIP", "(", "IPUtils", "::", "sanitizeIp", "(", "$", "element", ")", ")", ";", "if", "(", "empty", "(", "$", "excludedIps", ")", "||", "(", "!", "in_array", "(", "$", "element", ",", "$", "excludedIps", ")", "&&", "!", "$", "ip", "->", "isInRanges", "(", "$", "excludedIps", ")", ")", ")", "{", "return", "$", "element", ";", "}", "}", "return", "''", ";", "}", "return", "trim", "(", "Common", "::", "sanitizeInputValue", "(", "$", "csv", ")", ")", ";", "}" ]
Returns the last IP address in a comma separated list, subject to an optional exclusion list. @param string $csv Comma separated list of elements. @param array $excludedIps Optional list of excluded IP addresses (or IP address ranges). @return string Last (non-excluded) IP address in the list or an empty string if all given IPs are excluded.
[ "Returns", "the", "last", "IP", "address", "in", "a", "comma", "separated", "list", "subject", "to", "an", "optional", "exclusion", "list", "." ]
72df150735664275a60a7861e468c6ff3b152a14
https://github.com/matomo-org/matomo/blob/72df150735664275a60a7861e468c6ff3b152a14/core/IP.php#L106-L125
210,238
matomo-org/matomo
libs/Zend/Mail/Storage/Imap.php
Zend_Mail_Storage_Imap.removeMessage
public function removeMessage($id) { if (!$this->_protocol->store(array(Zend_Mail_Storage::FLAG_DELETED), $id, null, '+')) { /** * @see Zend_Mail_Storage_Exception */ // require_once 'Zend/Mail/Storage/Exception.php'; throw new Zend_Mail_Storage_Exception('cannot set deleted flag'); } // TODO: expunge here or at close? we can handle an error here better and are more fail safe if (!$this->_protocol->expunge()) { /** * @see Zend_Mail_Storage_Exception */ // require_once 'Zend/Mail/Storage/Exception.php'; throw new Zend_Mail_Storage_Exception('message marked as deleted, but could not expunge'); } }
php
public function removeMessage($id) { if (!$this->_protocol->store(array(Zend_Mail_Storage::FLAG_DELETED), $id, null, '+')) { /** * @see Zend_Mail_Storage_Exception */ // require_once 'Zend/Mail/Storage/Exception.php'; throw new Zend_Mail_Storage_Exception('cannot set deleted flag'); } // TODO: expunge here or at close? we can handle an error here better and are more fail safe if (!$this->_protocol->expunge()) { /** * @see Zend_Mail_Storage_Exception */ // require_once 'Zend/Mail/Storage/Exception.php'; throw new Zend_Mail_Storage_Exception('message marked as deleted, but could not expunge'); } }
[ "public", "function", "removeMessage", "(", "$", "id", ")", "{", "if", "(", "!", "$", "this", "->", "_protocol", "->", "store", "(", "array", "(", "Zend_Mail_Storage", "::", "FLAG_DELETED", ")", ",", "$", "id", ",", "null", ",", "'+'", ")", ")", "{", "/**\n * @see Zend_Mail_Storage_Exception\n */", "// require_once 'Zend/Mail/Storage/Exception.php';", "throw", "new", "Zend_Mail_Storage_Exception", "(", "'cannot set deleted flag'", ")", ";", "}", "// TODO: expunge here or at close? we can handle an error here better and are more fail safe", "if", "(", "!", "$", "this", "->", "_protocol", "->", "expunge", "(", ")", ")", "{", "/**\n * @see Zend_Mail_Storage_Exception\n */", "// require_once 'Zend/Mail/Storage/Exception.php';", "throw", "new", "Zend_Mail_Storage_Exception", "(", "'message marked as deleted, but could not expunge'", ")", ";", "}", "}" ]
Remove a message from server. If you're doing that from a web enviroment you should be careful and use a uniqueid as parameter if possible to identify the message. @param int $id number of message @return null @throws Zend_Mail_Storage_Exception
[ "Remove", "a", "message", "from", "server", ".", "If", "you", "re", "doing", "that", "from", "a", "web", "enviroment", "you", "should", "be", "careful", "and", "use", "a", "uniqueid", "as", "parameter", "if", "possible", "to", "identify", "the", "message", "." ]
72df150735664275a60a7861e468c6ff3b152a14
https://github.com/matomo-org/matomo/blob/72df150735664275a60a7861e468c6ff3b152a14/libs/Zend/Mail/Storage/Imap.php#L322-L339
210,239
matomo-org/matomo
plugins/UserCountry/Reports/Base.php
Base.checkIfNoDataForGeoIpReport
protected function checkIfNoDataForGeoIpReport(ViewDataTable $view) { $view->config->filters[] = function ($dataTable) use ($view) { // if there's only one row whose label is 'Unknown', display a message saying there's no data if ($dataTable->getRowsCount() == 1 && $dataTable->getFirstRow()->getColumn('label') == Piwik::translate('General_Unknown') ) { $footerMessage = Piwik::translate('UserCountry_NoDataForGeoIPReport1'); $userCountry = new UserCountry(); // if GeoIP is working, don't display this part of the message if (!$userCountry->isGeoIPWorking()) { $params = array('module' => 'UserCountry', 'action' => 'adminIndex'); $footerMessage .= ' ' . Piwik::translate('UserCountry_NoDataForGeoIPReport2', array('<a target="_blank" href="' . Url::getCurrentQueryStringWithParametersModified($params) . '">', '</a>', '<a rel="noreferrer noopener" target="_blank" href="http://dev.maxmind.com/geoip/geolite?rId=piwik">', '</a>')); } else { $footerMessage .= ' ' . Piwik::translate('UserCountry_ToGeolocateOldVisits', array('<a rel="noreferrer noopener" target="_blank" href="https://matomo.org/faq/how-to/#faq_167">', '</a>')); } $view->config->show_footer_message = $footerMessage; } }; }
php
protected function checkIfNoDataForGeoIpReport(ViewDataTable $view) { $view->config->filters[] = function ($dataTable) use ($view) { // if there's only one row whose label is 'Unknown', display a message saying there's no data if ($dataTable->getRowsCount() == 1 && $dataTable->getFirstRow()->getColumn('label') == Piwik::translate('General_Unknown') ) { $footerMessage = Piwik::translate('UserCountry_NoDataForGeoIPReport1'); $userCountry = new UserCountry(); // if GeoIP is working, don't display this part of the message if (!$userCountry->isGeoIPWorking()) { $params = array('module' => 'UserCountry', 'action' => 'adminIndex'); $footerMessage .= ' ' . Piwik::translate('UserCountry_NoDataForGeoIPReport2', array('<a target="_blank" href="' . Url::getCurrentQueryStringWithParametersModified($params) . '">', '</a>', '<a rel="noreferrer noopener" target="_blank" href="http://dev.maxmind.com/geoip/geolite?rId=piwik">', '</a>')); } else { $footerMessage .= ' ' . Piwik::translate('UserCountry_ToGeolocateOldVisits', array('<a rel="noreferrer noopener" target="_blank" href="https://matomo.org/faq/how-to/#faq_167">', '</a>')); } $view->config->show_footer_message = $footerMessage; } }; }
[ "protected", "function", "checkIfNoDataForGeoIpReport", "(", "ViewDataTable", "$", "view", ")", "{", "$", "view", "->", "config", "->", "filters", "[", "]", "=", "function", "(", "$", "dataTable", ")", "use", "(", "$", "view", ")", "{", "// if there's only one row whose label is 'Unknown', display a message saying there's no data", "if", "(", "$", "dataTable", "->", "getRowsCount", "(", ")", "==", "1", "&&", "$", "dataTable", "->", "getFirstRow", "(", ")", "->", "getColumn", "(", "'label'", ")", "==", "Piwik", "::", "translate", "(", "'General_Unknown'", ")", ")", "{", "$", "footerMessage", "=", "Piwik", "::", "translate", "(", "'UserCountry_NoDataForGeoIPReport1'", ")", ";", "$", "userCountry", "=", "new", "UserCountry", "(", ")", ";", "// if GeoIP is working, don't display this part of the message", "if", "(", "!", "$", "userCountry", "->", "isGeoIPWorking", "(", ")", ")", "{", "$", "params", "=", "array", "(", "'module'", "=>", "'UserCountry'", ",", "'action'", "=>", "'adminIndex'", ")", ";", "$", "footerMessage", ".=", "' '", ".", "Piwik", "::", "translate", "(", "'UserCountry_NoDataForGeoIPReport2'", ",", "array", "(", "'<a target=\"_blank\" href=\"'", ".", "Url", "::", "getCurrentQueryStringWithParametersModified", "(", "$", "params", ")", ".", "'\">'", ",", "'</a>'", ",", "'<a rel=\"noreferrer noopener\" target=\"_blank\" href=\"http://dev.maxmind.com/geoip/geolite?rId=piwik\">'", ",", "'</a>'", ")", ")", ";", "}", "else", "{", "$", "footerMessage", ".=", "' '", ".", "Piwik", "::", "translate", "(", "'UserCountry_ToGeolocateOldVisits'", ",", "array", "(", "'<a rel=\"noreferrer noopener\" target=\"_blank\" href=\"https://matomo.org/faq/how-to/#faq_167\">'", ",", "'</a>'", ")", ")", ";", "}", "$", "view", "->", "config", "->", "show_footer_message", "=", "$", "footerMessage", ";", "}", "}", ";", "}" ]
Checks if a datatable for a view is empty and if so, displays a message in the footer telling users to configure GeoIP.
[ "Checks", "if", "a", "datatable", "for", "a", "view", "is", "empty", "and", "if", "so", "displays", "a", "message", "in", "the", "footer", "telling", "users", "to", "configure", "GeoIP", "." ]
72df150735664275a60a7861e468c6ff3b152a14
https://github.com/matomo-org/matomo/blob/72df150735664275a60a7861e468c6ff3b152a14/plugins/UserCountry/Reports/Base.php#L37-L63
210,240
matomo-org/matomo
plugins/PrivacyManager/ReportsPurger.php
ReportsPurger.getArchiveTablesToPurge
private function getArchiveTablesToPurge() { // get month for which reports as old or older than, should be deleted // reports whose creation date <= this month will be deleted // (NOTE: we ignore how far we are in the current month) $toRemoveDate = Date::factory('today')->subMonth(1 + $this->deleteReportsOlderThan); // find all archive tables that are older than N months $oldNumericTables = array(); $oldBlobTables = array(); foreach (DbHelper::getTablesInstalled() as $table) { $type = ArchiveTableCreator::getTypeFromTableName($table); if ($type === false) { continue; } $date = ArchiveTableCreator::getDateFromTableName($table); list($year, $month) = explode('_', $date); if (self::shouldReportBePurged($year, $month, $toRemoveDate)) { if ($type == ArchiveTableCreator::NUMERIC_TABLE) { $oldNumericTables[] = $table; } else { $oldBlobTables[] = $table; } } } return array($oldNumericTables, $oldBlobTables); }
php
private function getArchiveTablesToPurge() { // get month for which reports as old or older than, should be deleted // reports whose creation date <= this month will be deleted // (NOTE: we ignore how far we are in the current month) $toRemoveDate = Date::factory('today')->subMonth(1 + $this->deleteReportsOlderThan); // find all archive tables that are older than N months $oldNumericTables = array(); $oldBlobTables = array(); foreach (DbHelper::getTablesInstalled() as $table) { $type = ArchiveTableCreator::getTypeFromTableName($table); if ($type === false) { continue; } $date = ArchiveTableCreator::getDateFromTableName($table); list($year, $month) = explode('_', $date); if (self::shouldReportBePurged($year, $month, $toRemoveDate)) { if ($type == ArchiveTableCreator::NUMERIC_TABLE) { $oldNumericTables[] = $table; } else { $oldBlobTables[] = $table; } } } return array($oldNumericTables, $oldBlobTables); }
[ "private", "function", "getArchiveTablesToPurge", "(", ")", "{", "// get month for which reports as old or older than, should be deleted", "// reports whose creation date <= this month will be deleted", "// (NOTE: we ignore how far we are in the current month)", "$", "toRemoveDate", "=", "Date", "::", "factory", "(", "'today'", ")", "->", "subMonth", "(", "1", "+", "$", "this", "->", "deleteReportsOlderThan", ")", ";", "// find all archive tables that are older than N months", "$", "oldNumericTables", "=", "array", "(", ")", ";", "$", "oldBlobTables", "=", "array", "(", ")", ";", "foreach", "(", "DbHelper", "::", "getTablesInstalled", "(", ")", "as", "$", "table", ")", "{", "$", "type", "=", "ArchiveTableCreator", "::", "getTypeFromTableName", "(", "$", "table", ")", ";", "if", "(", "$", "type", "===", "false", ")", "{", "continue", ";", "}", "$", "date", "=", "ArchiveTableCreator", "::", "getDateFromTableName", "(", "$", "table", ")", ";", "list", "(", "$", "year", ",", "$", "month", ")", "=", "explode", "(", "'_'", ",", "$", "date", ")", ";", "if", "(", "self", "::", "shouldReportBePurged", "(", "$", "year", ",", "$", "month", ",", "$", "toRemoveDate", ")", ")", "{", "if", "(", "$", "type", "==", "ArchiveTableCreator", "::", "NUMERIC_TABLE", ")", "{", "$", "oldNumericTables", "[", "]", "=", "$", "table", ";", "}", "else", "{", "$", "oldBlobTables", "[", "]", "=", "$", "table", ";", "}", "}", "}", "return", "array", "(", "$", "oldNumericTables", ",", "$", "oldBlobTables", ")", ";", "}" ]
Utility function that finds every archive table whose reports are considered old. @return array An array of two arrays. The first holds the numeric archive table names, and the second holds the blob archive table names.
[ "Utility", "function", "that", "finds", "every", "archive", "table", "whose", "reports", "are", "considered", "old", "." ]
72df150735664275a60a7861e468c6ff3b152a14
https://github.com/matomo-org/matomo/blob/72df150735664275a60a7861e468c6ff3b152a14/plugins/PrivacyManager/ReportsPurger.php#L212-L240
210,241
matomo-org/matomo
plugins/PrivacyManager/ReportsPurger.php
ReportsPurger.getBlobTableWhereExpr
private function getBlobTableWhereExpr($oldNumericTables, $table) { $where = ""; if (!empty($this->reportPeriodsToKeep)) // if keeping reports { $where = "period NOT IN (" . implode(',', $this->reportPeriodsToKeep) . ")"; // if not keeping segments make sure segments w/ kept periods are also deleted if (!$this->keepSegmentReports) { $this->findSegmentArchives($oldNumericTables); $dateFromTable = ArchiveTableCreator::getDateFromTableName($table); if (!empty($this->segmentArchiveIds[$dateFromTable])) { $archiveIds = $this->segmentArchiveIds[$dateFromTable]; $where .= " OR idarchive IN (" . implode(',', $archiveIds) . ")"; } } $where = "($where)"; } return $where; }
php
private function getBlobTableWhereExpr($oldNumericTables, $table) { $where = ""; if (!empty($this->reportPeriodsToKeep)) // if keeping reports { $where = "period NOT IN (" . implode(',', $this->reportPeriodsToKeep) . ")"; // if not keeping segments make sure segments w/ kept periods are also deleted if (!$this->keepSegmentReports) { $this->findSegmentArchives($oldNumericTables); $dateFromTable = ArchiveTableCreator::getDateFromTableName($table); if (!empty($this->segmentArchiveIds[$dateFromTable])) { $archiveIds = $this->segmentArchiveIds[$dateFromTable]; $where .= " OR idarchive IN (" . implode(',', $archiveIds) . ")"; } } $where = "($where)"; } return $where; }
[ "private", "function", "getBlobTableWhereExpr", "(", "$", "oldNumericTables", ",", "$", "table", ")", "{", "$", "where", "=", "\"\"", ";", "if", "(", "!", "empty", "(", "$", "this", "->", "reportPeriodsToKeep", ")", ")", "// if keeping reports", "{", "$", "where", "=", "\"period NOT IN (\"", ".", "implode", "(", "','", ",", "$", "this", "->", "reportPeriodsToKeep", ")", ".", "\")\"", ";", "// if not keeping segments make sure segments w/ kept periods are also deleted", "if", "(", "!", "$", "this", "->", "keepSegmentReports", ")", "{", "$", "this", "->", "findSegmentArchives", "(", "$", "oldNumericTables", ")", ";", "$", "dateFromTable", "=", "ArchiveTableCreator", "::", "getDateFromTableName", "(", "$", "table", ")", ";", "if", "(", "!", "empty", "(", "$", "this", "->", "segmentArchiveIds", "[", "$", "dateFromTable", "]", ")", ")", "{", "$", "archiveIds", "=", "$", "this", "->", "segmentArchiveIds", "[", "$", "dateFromTable", "]", ";", "$", "where", ".=", "\" OR idarchive IN (\"", ".", "implode", "(", "','", ",", "$", "archiveIds", ")", ".", "\")\"", ";", "}", "}", "$", "where", "=", "\"($where)\"", ";", "}", "return", "$", "where", ";", "}" ]
Returns SQL WHERE expression used to find reports that should be purged.
[ "Returns", "SQL", "WHERE", "expression", "used", "to", "find", "reports", "that", "should", "be", "purged", "." ]
72df150735664275a60a7861e468c6ff3b152a14
https://github.com/matomo-org/matomo/blob/72df150735664275a60a7861e468c6ff3b152a14/plugins/PrivacyManager/ReportsPurger.php#L287-L309
210,242
matomo-org/matomo
plugins/PrivacyManager/ReportsPurger.php
ReportsPurger.findSegmentArchives
private function findSegmentArchives($numericTables) { if (!is_null($this->segmentArchiveIds) || empty($numericTables)) { return; } foreach ($numericTables as $table) { $tableDate = ArchiveTableCreator::getDateFromTableName($table); $maxIdArchive = Db::fetchOne("SELECT MAX(idarchive) FROM $table"); $sql = "SELECT idarchive FROM $table WHERE name != 'done' AND name LIKE 'done_%.%' AND idarchive >= ? AND idarchive < ?"; if (is_null($this->segmentArchiveIds)) { $this->segmentArchiveIds = array(); } $this->segmentArchiveIds[$tableDate] = array(); foreach (Db::segmentedFetchAll($sql, 0, $maxIdArchive, self::$selectSegmentSize) as $row) { $this->segmentArchiveIds[$tableDate][] = $row['idarchive']; } } }
php
private function findSegmentArchives($numericTables) { if (!is_null($this->segmentArchiveIds) || empty($numericTables)) { return; } foreach ($numericTables as $table) { $tableDate = ArchiveTableCreator::getDateFromTableName($table); $maxIdArchive = Db::fetchOne("SELECT MAX(idarchive) FROM $table"); $sql = "SELECT idarchive FROM $table WHERE name != 'done' AND name LIKE 'done_%.%' AND idarchive >= ? AND idarchive < ?"; if (is_null($this->segmentArchiveIds)) { $this->segmentArchiveIds = array(); } $this->segmentArchiveIds[$tableDate] = array(); foreach (Db::segmentedFetchAll($sql, 0, $maxIdArchive, self::$selectSegmentSize) as $row) { $this->segmentArchiveIds[$tableDate][] = $row['idarchive']; } } }
[ "private", "function", "findSegmentArchives", "(", "$", "numericTables", ")", "{", "if", "(", "!", "is_null", "(", "$", "this", "->", "segmentArchiveIds", ")", "||", "empty", "(", "$", "numericTables", ")", ")", "{", "return", ";", "}", "foreach", "(", "$", "numericTables", "as", "$", "table", ")", "{", "$", "tableDate", "=", "ArchiveTableCreator", "::", "getDateFromTableName", "(", "$", "table", ")", ";", "$", "maxIdArchive", "=", "Db", "::", "fetchOne", "(", "\"SELECT MAX(idarchive) FROM $table\"", ")", ";", "$", "sql", "=", "\"SELECT idarchive FROM $table\n WHERE name != 'done'\n AND name LIKE 'done_%.%'\n AND idarchive >= ?\n AND idarchive < ?\"", ";", "if", "(", "is_null", "(", "$", "this", "->", "segmentArchiveIds", ")", ")", "{", "$", "this", "->", "segmentArchiveIds", "=", "array", "(", ")", ";", "}", "$", "this", "->", "segmentArchiveIds", "[", "$", "tableDate", "]", "=", "array", "(", ")", ";", "foreach", "(", "Db", "::", "segmentedFetchAll", "(", "$", "sql", ",", "0", ",", "$", "maxIdArchive", ",", "self", "::", "$", "selectSegmentSize", ")", "as", "$", "row", ")", "{", "$", "this", "->", "segmentArchiveIds", "[", "$", "tableDate", "]", "[", "]", "=", "$", "row", "[", "'idarchive'", "]", ";", "}", "}", "}" ]
If we're going to keep segmented reports, we need to know which archives are for segments. This info is only in the numeric tables, so we must query them.
[ "If", "we", "re", "going", "to", "keep", "segmented", "reports", "we", "need", "to", "know", "which", "archives", "are", "for", "segments", ".", "This", "info", "is", "only", "in", "the", "numeric", "tables", "so", "we", "must", "query", "them", "." ]
72df150735664275a60a7861e468c6ff3b152a14
https://github.com/matomo-org/matomo/blob/72df150735664275a60a7861e468c6ff3b152a14/plugins/PrivacyManager/ReportsPurger.php#L315-L341
210,243
matomo-org/matomo
plugins/PrivacyManager/ReportsPurger.php
ReportsPurger.make
public static function make($settings, $metricsToKeep) { return new ReportsPurger( $settings['delete_reports_older_than'], $settings['delete_reports_keep_basic_metrics'] == 1, self::getReportPeriodsToKeep($settings), $settings['delete_reports_keep_segment_reports'] == 1, $metricsToKeep, $settings['delete_logs_max_rows_per_query'] ); }
php
public static function make($settings, $metricsToKeep) { return new ReportsPurger( $settings['delete_reports_older_than'], $settings['delete_reports_keep_basic_metrics'] == 1, self::getReportPeriodsToKeep($settings), $settings['delete_reports_keep_segment_reports'] == 1, $metricsToKeep, $settings['delete_logs_max_rows_per_query'] ); }
[ "public", "static", "function", "make", "(", "$", "settings", ",", "$", "metricsToKeep", ")", "{", "return", "new", "ReportsPurger", "(", "$", "settings", "[", "'delete_reports_older_than'", "]", ",", "$", "settings", "[", "'delete_reports_keep_basic_metrics'", "]", "==", "1", ",", "self", "::", "getReportPeriodsToKeep", "(", "$", "settings", ")", ",", "$", "settings", "[", "'delete_reports_keep_segment_reports'", "]", "==", "1", ",", "$", "metricsToKeep", ",", "$", "settings", "[", "'delete_logs_max_rows_per_query'", "]", ")", ";", "}" ]
Utility function. Creates a new instance of ReportsPurger with the supplied array of settings. $settings must contain the following keys: -'delete_reports_older_than': The number of months after which reports/metrics are considered old. -'delete_reports_keep_basic_metrics': 1 if basic metrics should be kept, 0 if otherwise. -'delete_reports_keep_day_reports': 1 if daily reports should be kept, 0 if otherwise. -'delete_reports_keep_week_reports': 1 if weekly reports should be kept, 0 if otherwise. -'delete_reports_keep_month_reports': 1 if monthly reports should be kept, 0 if otherwise. -'delete_reports_keep_year_reports': 1 if yearly reports should be kept, 0 if otherwise. -'delete_reports_keep_range_reports': 1 if range reports should be kept, 0 if otherwise. -'delete_reports_keep_segment_reports': 1 if reports for segments should be kept, 0 if otherwise. -'delete_logs_max_rows_per_query': Maximum number of rows to delete in one DELETE query.
[ "Utility", "function", ".", "Creates", "a", "new", "instance", "of", "ReportsPurger", "with", "the", "supplied", "array", "of", "settings", "." ]
72df150735664275a60a7861e468c6ff3b152a14
https://github.com/matomo-org/matomo/blob/72df150735664275a60a7861e468c6ff3b152a14/plugins/PrivacyManager/ReportsPurger.php#L359-L369
210,244
matomo-org/matomo
plugins/CoreHome/Tracker/VisitRequestProcessor.php
VisitRequestProcessor.isVisitNew
public function isVisitNew(VisitProperties $visitProperties, Request $request) { $isKnown = $request->getMetadata('CoreHome', 'isVisitorKnown'); if (!$isKnown) { return true; } $isLastActionInTheSameVisit = $this->isLastActionInTheSameVisit($visitProperties, $request); if (!$isLastActionInTheSameVisit) { Common::printDebug("Visitor detected, but last action was more than 30 minutes ago..."); return true; } $wasLastActionYesterday = $this->wasLastActionNotToday($visitProperties, $request); $forceNewVisitAtMidnight = (bool) Config::getInstance()->Tracker['create_new_visit_after_midnight']; if ($wasLastActionYesterday && $forceNewVisitAtMidnight) { Common::printDebug("Visitor detected, but last action was yesterday..."); return true; } return false; }
php
public function isVisitNew(VisitProperties $visitProperties, Request $request) { $isKnown = $request->getMetadata('CoreHome', 'isVisitorKnown'); if (!$isKnown) { return true; } $isLastActionInTheSameVisit = $this->isLastActionInTheSameVisit($visitProperties, $request); if (!$isLastActionInTheSameVisit) { Common::printDebug("Visitor detected, but last action was more than 30 minutes ago..."); return true; } $wasLastActionYesterday = $this->wasLastActionNotToday($visitProperties, $request); $forceNewVisitAtMidnight = (bool) Config::getInstance()->Tracker['create_new_visit_after_midnight']; if ($wasLastActionYesterday && $forceNewVisitAtMidnight) { Common::printDebug("Visitor detected, but last action was yesterday..."); return true; } return false; }
[ "public", "function", "isVisitNew", "(", "VisitProperties", "$", "visitProperties", ",", "Request", "$", "request", ")", "{", "$", "isKnown", "=", "$", "request", "->", "getMetadata", "(", "'CoreHome'", ",", "'isVisitorKnown'", ")", ";", "if", "(", "!", "$", "isKnown", ")", "{", "return", "true", ";", "}", "$", "isLastActionInTheSameVisit", "=", "$", "this", "->", "isLastActionInTheSameVisit", "(", "$", "visitProperties", ",", "$", "request", ")", ";", "if", "(", "!", "$", "isLastActionInTheSameVisit", ")", "{", "Common", "::", "printDebug", "(", "\"Visitor detected, but last action was more than 30 minutes ago...\"", ")", ";", "return", "true", ";", "}", "$", "wasLastActionYesterday", "=", "$", "this", "->", "wasLastActionNotToday", "(", "$", "visitProperties", ",", "$", "request", ")", ";", "$", "forceNewVisitAtMidnight", "=", "(", "bool", ")", "Config", "::", "getInstance", "(", ")", "->", "Tracker", "[", "'create_new_visit_after_midnight'", "]", ";", "if", "(", "$", "wasLastActionYesterday", "&&", "$", "forceNewVisitAtMidnight", ")", "{", "Common", "::", "printDebug", "(", "\"Visitor detected, but last action was yesterday...\"", ")", ";", "return", "true", ";", "}", "return", "false", ";", "}" ]
Determines if the tracker if the current action should be treated as the start of a new visit or an action in an existing visit. Note: public only for tests. @param VisitProperties $visitProperties The current visit/visitor information. @param Request $request @return bool
[ "Determines", "if", "the", "tracker", "if", "the", "current", "action", "should", "be", "treated", "as", "the", "start", "of", "a", "new", "visit", "or", "an", "action", "in", "an", "existing", "visit", "." ]
72df150735664275a60a7861e468c6ff3b152a14
https://github.com/matomo-org/matomo/blob/72df150735664275a60a7861e468c6ff3b152a14/plugins/CoreHome/Tracker/VisitRequestProcessor.php#L149-L173
210,245
matomo-org/matomo
plugins/CoreHome/Tracker/VisitRequestProcessor.php
VisitRequestProcessor.isLastActionInTheSameVisit
protected function isLastActionInTheSameVisit(VisitProperties $visitProperties, Request $request) { $lastActionTime = $visitProperties->getProperty('visit_last_action_time'); return isset($lastActionTime) && false !== $lastActionTime && ($lastActionTime > ($request->getCurrentTimestamp() - $this->visitStandardLength)); }
php
protected function isLastActionInTheSameVisit(VisitProperties $visitProperties, Request $request) { $lastActionTime = $visitProperties->getProperty('visit_last_action_time'); return isset($lastActionTime) && false !== $lastActionTime && ($lastActionTime > ($request->getCurrentTimestamp() - $this->visitStandardLength)); }
[ "protected", "function", "isLastActionInTheSameVisit", "(", "VisitProperties", "$", "visitProperties", ",", "Request", "$", "request", ")", "{", "$", "lastActionTime", "=", "$", "visitProperties", "->", "getProperty", "(", "'visit_last_action_time'", ")", ";", "return", "isset", "(", "$", "lastActionTime", ")", "&&", "false", "!==", "$", "lastActionTime", "&&", "(", "$", "lastActionTime", ">", "(", "$", "request", "->", "getCurrentTimestamp", "(", ")", "-", "$", "this", "->", "visitStandardLength", ")", ")", ";", "}" ]
Returns true if the last action was done during the last 30 minutes @return bool
[ "Returns", "true", "if", "the", "last", "action", "was", "done", "during", "the", "last", "30", "minutes" ]
72df150735664275a60a7861e468c6ff3b152a14
https://github.com/matomo-org/matomo/blob/72df150735664275a60a7861e468c6ff3b152a14/plugins/CoreHome/Tracker/VisitRequestProcessor.php#L179-L186
210,246
matomo-org/matomo
plugins/CoreHome/Tracker/VisitRequestProcessor.php
VisitRequestProcessor.wasLastActionNotToday
private function wasLastActionNotToday(VisitProperties $visitProperties, Request $request) { $lastActionTime = $visitProperties->getProperty('visit_last_action_time'); if (empty($lastActionTime)) { return false; } $idSite = $request->getIdSite(); $timezone = $this->getTimezoneForSite($idSite); if (empty($timezone)) { throw new UnexpectedWebsiteFoundException('An unexpected website was found, check idSite in the request'); } $date = Date::factory((int)$lastActionTime, $timezone); $now = $request->getCurrentTimestamp(); $now = Date::factory((int)$now, $timezone); return $date->toString() !== $now->toString(); }
php
private function wasLastActionNotToday(VisitProperties $visitProperties, Request $request) { $lastActionTime = $visitProperties->getProperty('visit_last_action_time'); if (empty($lastActionTime)) { return false; } $idSite = $request->getIdSite(); $timezone = $this->getTimezoneForSite($idSite); if (empty($timezone)) { throw new UnexpectedWebsiteFoundException('An unexpected website was found, check idSite in the request'); } $date = Date::factory((int)$lastActionTime, $timezone); $now = $request->getCurrentTimestamp(); $now = Date::factory((int)$now, $timezone); return $date->toString() !== $now->toString(); }
[ "private", "function", "wasLastActionNotToday", "(", "VisitProperties", "$", "visitProperties", ",", "Request", "$", "request", ")", "{", "$", "lastActionTime", "=", "$", "visitProperties", "->", "getProperty", "(", "'visit_last_action_time'", ")", ";", "if", "(", "empty", "(", "$", "lastActionTime", ")", ")", "{", "return", "false", ";", "}", "$", "idSite", "=", "$", "request", "->", "getIdSite", "(", ")", ";", "$", "timezone", "=", "$", "this", "->", "getTimezoneForSite", "(", "$", "idSite", ")", ";", "if", "(", "empty", "(", "$", "timezone", ")", ")", "{", "throw", "new", "UnexpectedWebsiteFoundException", "(", "'An unexpected website was found, check idSite in the request'", ")", ";", "}", "$", "date", "=", "Date", "::", "factory", "(", "(", "int", ")", "$", "lastActionTime", ",", "$", "timezone", ")", ";", "$", "now", "=", "$", "request", "->", "getCurrentTimestamp", "(", ")", ";", "$", "now", "=", "Date", "::", "factory", "(", "(", "int", ")", "$", "now", ",", "$", "timezone", ")", ";", "return", "$", "date", "->", "toString", "(", ")", "!==", "$", "now", "->", "toString", "(", ")", ";", "}" ]
Returns true if the last action was not today. @param VisitProperties $visitor @return bool
[ "Returns", "true", "if", "the", "last", "action", "was", "not", "today", "." ]
72df150735664275a60a7861e468c6ff3b152a14
https://github.com/matomo-org/matomo/blob/72df150735664275a60a7861e468c6ff3b152a14/plugins/CoreHome/Tracker/VisitRequestProcessor.php#L193-L213
210,247
matomo-org/matomo
libs/Zend/Db/Profiler.php
Zend_Db_Profiler.getLastQueryProfile
public function getLastQueryProfile() { if (empty($this->_queryProfiles)) { return false; } end($this->_queryProfiles); return current($this->_queryProfiles); }
php
public function getLastQueryProfile() { if (empty($this->_queryProfiles)) { return false; } end($this->_queryProfiles); return current($this->_queryProfiles); }
[ "public", "function", "getLastQueryProfile", "(", ")", "{", "if", "(", "empty", "(", "$", "this", "->", "_queryProfiles", ")", ")", "{", "return", "false", ";", "}", "end", "(", "$", "this", "->", "_queryProfiles", ")", ";", "return", "current", "(", "$", "this", "->", "_queryProfiles", ")", ";", "}" ]
Get the Zend_Db_Profiler_Query object for the last query that was run, regardless if it has ended or not. If the query has not ended, its end time will be null. If no queries have been profiled, false is returned. @return Zend_Db_Profiler_Query|false
[ "Get", "the", "Zend_Db_Profiler_Query", "object", "for", "the", "last", "query", "that", "was", "run", "regardless", "if", "it", "has", "ended", "or", "not", ".", "If", "the", "query", "has", "not", "ended", "its", "end", "time", "will", "be", "null", ".", "If", "no", "queries", "have", "been", "profiled", "false", "is", "returned", "." ]
72df150735664275a60a7861e468c6ff3b152a14
https://github.com/matomo-org/matomo/blob/72df150735664275a60a7861e468c6ff3b152a14/libs/Zend/Db/Profiler.php#L459-L468
210,248
matomo-org/matomo
libs/Zend/Validate/File/MimeType.php
Zend_Validate_File_MimeType.setMagicFile
public function setMagicFile($file) { if (empty($file)) { $this->_magicfile = null; } else if (!(class_exists('finfo', false))) { $this->_magicfile = null; // require_once 'Zend/Validate/Exception.php'; throw new Zend_Validate_Exception('Magicfile can not be set. There is no finfo extension installed'); } else if (!is_file($file) || !is_readable($file)) { // require_once 'Zend/Validate/Exception.php'; throw new Zend_Validate_Exception('The given magicfile can not be read'); } else { $const = defined('FILEINFO_MIME_TYPE') ? FILEINFO_MIME_TYPE : FILEINFO_MIME; $this->_finfo = @finfo_open($const, $file); if (empty($this->_finfo)) { $this->_finfo = null; // require_once 'Zend/Validate/Exception.php'; throw new Zend_Validate_Exception('The given magicfile is not accepted by finfo'); } else { $this->_magicfile = $file; } } return $this; }
php
public function setMagicFile($file) { if (empty($file)) { $this->_magicfile = null; } else if (!(class_exists('finfo', false))) { $this->_magicfile = null; // require_once 'Zend/Validate/Exception.php'; throw new Zend_Validate_Exception('Magicfile can not be set. There is no finfo extension installed'); } else if (!is_file($file) || !is_readable($file)) { // require_once 'Zend/Validate/Exception.php'; throw new Zend_Validate_Exception('The given magicfile can not be read'); } else { $const = defined('FILEINFO_MIME_TYPE') ? FILEINFO_MIME_TYPE : FILEINFO_MIME; $this->_finfo = @finfo_open($const, $file); if (empty($this->_finfo)) { $this->_finfo = null; // require_once 'Zend/Validate/Exception.php'; throw new Zend_Validate_Exception('The given magicfile is not accepted by finfo'); } else { $this->_magicfile = $file; } } return $this; }
[ "public", "function", "setMagicFile", "(", "$", "file", ")", "{", "if", "(", "empty", "(", "$", "file", ")", ")", "{", "$", "this", "->", "_magicfile", "=", "null", ";", "}", "else", "if", "(", "!", "(", "class_exists", "(", "'finfo'", ",", "false", ")", ")", ")", "{", "$", "this", "->", "_magicfile", "=", "null", ";", "// require_once 'Zend/Validate/Exception.php';", "throw", "new", "Zend_Validate_Exception", "(", "'Magicfile can not be set. There is no finfo extension installed'", ")", ";", "}", "else", "if", "(", "!", "is_file", "(", "$", "file", ")", "||", "!", "is_readable", "(", "$", "file", ")", ")", "{", "// require_once 'Zend/Validate/Exception.php';", "throw", "new", "Zend_Validate_Exception", "(", "'The given magicfile can not be read'", ")", ";", "}", "else", "{", "$", "const", "=", "defined", "(", "'FILEINFO_MIME_TYPE'", ")", "?", "FILEINFO_MIME_TYPE", ":", "FILEINFO_MIME", ";", "$", "this", "->", "_finfo", "=", "@", "finfo_open", "(", "$", "const", ",", "$", "file", ")", ";", "if", "(", "empty", "(", "$", "this", "->", "_finfo", ")", ")", "{", "$", "this", "->", "_finfo", "=", "null", ";", "// require_once 'Zend/Validate/Exception.php';", "throw", "new", "Zend_Validate_Exception", "(", "'The given magicfile is not accepted by finfo'", ")", ";", "}", "else", "{", "$", "this", "->", "_magicfile", "=", "$", "file", ";", "}", "}", "return", "$", "this", ";", "}" ]
Sets the magicfile to use if null, the MAGIC constant from php is used if the MAGIC file is errorous, no file will be set @param string $file @throws Zend_Validate_Exception When finfo can not read the magicfile @return Zend_Validate_File_MimeType Provides fluid interface
[ "Sets", "the", "magicfile", "to", "use", "if", "null", "the", "MAGIC", "constant", "from", "php", "is", "used", "if", "the", "MAGIC", "file", "is", "errorous", "no", "file", "will", "be", "set" ]
72df150735664275a60a7861e468c6ff3b152a14
https://github.com/matomo-org/matomo/blob/72df150735664275a60a7861e468c6ff3b152a14/libs/Zend/Validate/File/MimeType.php#L186-L210
210,249
matomo-org/matomo
libs/Zend/Validate/File/MimeType.php
Zend_Validate_File_MimeType.getMimeType
public function getMimeType($asArray = false) { $asArray = (bool) $asArray; $mimetype = (string) $this->_mimetype; if ($asArray) { $mimetype = explode(',', $mimetype); } return $mimetype; }
php
public function getMimeType($asArray = false) { $asArray = (bool) $asArray; $mimetype = (string) $this->_mimetype; if ($asArray) { $mimetype = explode(',', $mimetype); } return $mimetype; }
[ "public", "function", "getMimeType", "(", "$", "asArray", "=", "false", ")", "{", "$", "asArray", "=", "(", "bool", ")", "$", "asArray", ";", "$", "mimetype", "=", "(", "string", ")", "$", "this", "->", "_mimetype", ";", "if", "(", "$", "asArray", ")", "{", "$", "mimetype", "=", "explode", "(", "','", ",", "$", "mimetype", ")", ";", "}", "return", "$", "mimetype", ";", "}" ]
Returns the set mimetypes @param boolean $asArray Returns the values as array, when false an concated string is returned @return string|array
[ "Returns", "the", "set", "mimetypes" ]
72df150735664275a60a7861e468c6ff3b152a14
https://github.com/matomo-org/matomo/blob/72df150735664275a60a7861e468c6ff3b152a14/libs/Zend/Validate/File/MimeType.php#L241-L250
210,250
matomo-org/matomo
core/Twig.php
Twig.getCustomThemeLoader
protected function getCustomThemeLoader(Plugin $theme) { $pluginsDir = Manager::getPluginDirectory($theme->getPluginName()); $themeDir = $pluginsDir . '/templates/'; if (!file_exists($themeDir)) { return false; } $themeLoader = new Twig_Loader_Filesystem(array($themeDir), PIWIK_DOCUMENT_ROOT.DIRECTORY_SEPARATOR); return $themeLoader; }
php
protected function getCustomThemeLoader(Plugin $theme) { $pluginsDir = Manager::getPluginDirectory($theme->getPluginName()); $themeDir = $pluginsDir . '/templates/'; if (!file_exists($themeDir)) { return false; } $themeLoader = new Twig_Loader_Filesystem(array($themeDir), PIWIK_DOCUMENT_ROOT.DIRECTORY_SEPARATOR); return $themeLoader; }
[ "protected", "function", "getCustomThemeLoader", "(", "Plugin", "$", "theme", ")", "{", "$", "pluginsDir", "=", "Manager", "::", "getPluginDirectory", "(", "$", "theme", "->", "getPluginName", "(", ")", ")", ";", "$", "themeDir", "=", "$", "pluginsDir", ".", "'/templates/'", ";", "if", "(", "!", "file_exists", "(", "$", "themeDir", ")", ")", "{", "return", "false", ";", "}", "$", "themeLoader", "=", "new", "Twig_Loader_Filesystem", "(", "array", "(", "$", "themeDir", ")", ",", "PIWIK_DOCUMENT_ROOT", ".", "DIRECTORY_SEPARATOR", ")", ";", "return", "$", "themeLoader", ";", "}" ]
create template loader for a custom theme @param \Piwik\Plugin $theme @return \Twig_Loader_Filesystem
[ "create", "template", "loader", "for", "a", "custom", "theme" ]
72df150735664275a60a7861e468c6ff3b152a14
https://github.com/matomo-org/matomo/blob/72df150735664275a60a7861e468c6ff3b152a14/core/Twig.php#L327-L338
210,251
matomo-org/matomo
libs/HTML/QuickForm2/Rule/Compare.php
HTML_QuickForm2_Rule_Compare.toCanonicalForm
protected static function toCanonicalForm($config, $key = 'operand') { if (!is_array($config)) { return array($key => $config); } elseif (array_key_exists('operator', $config) || array_key_exists('operand', $config) ) { return $config; } elseif (1 == count($config)) { return array($key => end($config)); } else { return array('operator' => reset($config), 'operand' => end($config)); } }
php
protected static function toCanonicalForm($config, $key = 'operand') { if (!is_array($config)) { return array($key => $config); } elseif (array_key_exists('operator', $config) || array_key_exists('operand', $config) ) { return $config; } elseif (1 == count($config)) { return array($key => end($config)); } else { return array('operator' => reset($config), 'operand' => end($config)); } }
[ "protected", "static", "function", "toCanonicalForm", "(", "$", "config", ",", "$", "key", "=", "'operand'", ")", "{", "if", "(", "!", "is_array", "(", "$", "config", ")", ")", "{", "return", "array", "(", "$", "key", "=>", "$", "config", ")", ";", "}", "elseif", "(", "array_key_exists", "(", "'operator'", ",", "$", "config", ")", "||", "array_key_exists", "(", "'operand'", ",", "$", "config", ")", ")", "{", "return", "$", "config", ";", "}", "elseif", "(", "1", "==", "count", "(", "$", "config", ")", ")", "{", "return", "array", "(", "$", "key", "=>", "end", "(", "$", "config", ")", ")", ";", "}", "else", "{", "return", "array", "(", "'operator'", "=>", "reset", "(", "$", "config", ")", ",", "'operand'", "=>", "end", "(", "$", "config", ")", ")", ";", "}", "}" ]
Converts configuration data to a canonical associative array form @param mixed Configuration data @param string Array key to assign $config to if it is scalar @return array Associative array that may contain 'operand' and 'operator' keys
[ "Converts", "configuration", "data", "to", "a", "canonical", "associative", "array", "form" ]
72df150735664275a60a7861e468c6ff3b152a14
https://github.com/matomo-org/matomo/blob/72df150735664275a60a7861e468c6ff3b152a14/libs/HTML/QuickForm2/Rule/Compare.php#L195-L211
210,252
matomo-org/matomo
libs/HTML/QuickForm2/Rule/Compare.php
HTML_QuickForm2_Rule_Compare.setConfig
public function setConfig($config) { if (0 == count($config)) { throw new HTML_QuickForm2_InvalidArgumentException( 'Compare Rule requires an argument to compare with' ); } $config = self::toCanonicalForm($config); $config += array('operator' => '==='); if (!in_array($config['operator'], $this->operators)) { throw new HTML_QuickForm2_InvalidArgumentException( 'Compare Rule requires a valid comparison operator, ' . preg_replace('/\s+/', ' ', var_export($config['operator'], true)) . ' given' ); } if (in_array($config['operator'], array('==', '!='))) { $config['operator'] .= '='; } return parent::setConfig($config); }
php
public function setConfig($config) { if (0 == count($config)) { throw new HTML_QuickForm2_InvalidArgumentException( 'Compare Rule requires an argument to compare with' ); } $config = self::toCanonicalForm($config); $config += array('operator' => '==='); if (!in_array($config['operator'], $this->operators)) { throw new HTML_QuickForm2_InvalidArgumentException( 'Compare Rule requires a valid comparison operator, ' . preg_replace('/\s+/', ' ', var_export($config['operator'], true)) . ' given' ); } if (in_array($config['operator'], array('==', '!='))) { $config['operator'] .= '='; } return parent::setConfig($config); }
[ "public", "function", "setConfig", "(", "$", "config", ")", "{", "if", "(", "0", "==", "count", "(", "$", "config", ")", ")", "{", "throw", "new", "HTML_QuickForm2_InvalidArgumentException", "(", "'Compare Rule requires an argument to compare with'", ")", ";", "}", "$", "config", "=", "self", "::", "toCanonicalForm", "(", "$", "config", ")", ";", "$", "config", "+=", "array", "(", "'operator'", "=>", "'==='", ")", ";", "if", "(", "!", "in_array", "(", "$", "config", "[", "'operator'", "]", ",", "$", "this", "->", "operators", ")", ")", "{", "throw", "new", "HTML_QuickForm2_InvalidArgumentException", "(", "'Compare Rule requires a valid comparison operator, '", ".", "preg_replace", "(", "'/\\s+/'", ",", "' '", ",", "var_export", "(", "$", "config", "[", "'operator'", "]", ",", "true", ")", ")", ".", "' given'", ")", ";", "}", "if", "(", "in_array", "(", "$", "config", "[", "'operator'", "]", ",", "array", "(", "'=='", ",", "'!='", ")", ")", ")", "{", "$", "config", "[", "'operator'", "]", ".=", "'='", ";", "}", "return", "parent", "::", "setConfig", "(", "$", "config", ")", ";", "}" ]
Sets the comparison operator and operand to compare to $config can be either of the following - operand - array([operator, ]operand) - array(['operator' => operator, ]['operand' => operand]) If operator is missing it will default to '===' @param mixed Configuration data @return HTML_QuickForm2_Rule @throws HTML_QuickForm2_InvalidArgumentException if a bogus comparison operator is used for configuration, if an operand is missing
[ "Sets", "the", "comparison", "operator", "and", "operand", "to", "compare", "to" ]
72df150735664275a60a7861e468c6ff3b152a14
https://github.com/matomo-org/matomo/blob/72df150735664275a60a7861e468c6ff3b152a14/libs/HTML/QuickForm2/Rule/Compare.php#L227-L248
210,253
matomo-org/matomo
plugins/SEO/Metric/DomainAge.php
DomainAge.getAgeArchiveOrg
private function getAgeArchiveOrg($domain) { $response = $this->getUrl('https://archive.org/wayback/available?timestamp=19900101&url=' . urlencode($domain)); $data = json_decode($response, true); if (empty($data["archived_snapshots"]["closest"]["timestamp"])) { return 0; } return strtotime($data["archived_snapshots"]["closest"]["timestamp"]); }
php
private function getAgeArchiveOrg($domain) { $response = $this->getUrl('https://archive.org/wayback/available?timestamp=19900101&url=' . urlencode($domain)); $data = json_decode($response, true); if (empty($data["archived_snapshots"]["closest"]["timestamp"])) { return 0; } return strtotime($data["archived_snapshots"]["closest"]["timestamp"]); }
[ "private", "function", "getAgeArchiveOrg", "(", "$", "domain", ")", "{", "$", "response", "=", "$", "this", "->", "getUrl", "(", "'https://archive.org/wayback/available?timestamp=19900101&url='", ".", "urlencode", "(", "$", "domain", ")", ")", ";", "$", "data", "=", "json_decode", "(", "$", "response", ",", "true", ")", ";", "if", "(", "empty", "(", "$", "data", "[", "\"archived_snapshots\"", "]", "[", "\"closest\"", "]", "[", "\"timestamp\"", "]", ")", ")", "{", "return", "0", ";", "}", "return", "strtotime", "(", "$", "data", "[", "\"archived_snapshots\"", "]", "[", "\"closest\"", "]", "[", "\"timestamp\"", "]", ")", ";", "}" ]
Returns the domain age archive.org lists for the current url @param string $domain @return int
[ "Returns", "the", "domain", "age", "archive", ".", "org", "lists", "for", "the", "current", "url" ]
72df150735664275a60a7861e468c6ff3b152a14
https://github.com/matomo-org/matomo/blob/72df150735664275a60a7861e468c6ff3b152a14/plugins/SEO/Metric/DomainAge.php#L75-L83
210,254
matomo-org/matomo
plugins/SEO/Metric/DomainAge.php
DomainAge.getAgeWhoIs
private function getAgeWhoIs($domain) { $data = $this->getUrl('https://www.who.is/whois/' . urlencode($domain)); preg_match('#(?:Creation Date|Created On|created|Registered on)\.*:\s*([ \ta-z0-9\/\-:\.]+)#si', $data, $p); if (!empty($p[1])) { $value = strtotime(trim($p[1])); if ($value === false) { return 0; } return $value; } return 0; }
php
private function getAgeWhoIs($domain) { $data = $this->getUrl('https://www.who.is/whois/' . urlencode($domain)); preg_match('#(?:Creation Date|Created On|created|Registered on)\.*:\s*([ \ta-z0-9\/\-:\.]+)#si', $data, $p); if (!empty($p[1])) { $value = strtotime(trim($p[1])); if ($value === false) { return 0; } return $value; } return 0; }
[ "private", "function", "getAgeWhoIs", "(", "$", "domain", ")", "{", "$", "data", "=", "$", "this", "->", "getUrl", "(", "'https://www.who.is/whois/'", ".", "urlencode", "(", "$", "domain", ")", ")", ";", "preg_match", "(", "'#(?:Creation Date|Created On|created|Registered on)\\.*:\\s*([ \\ta-z0-9\\/\\-:\\.]+)#si'", ",", "$", "data", ",", "$", "p", ")", ";", "if", "(", "!", "empty", "(", "$", "p", "[", "1", "]", ")", ")", "{", "$", "value", "=", "strtotime", "(", "trim", "(", "$", "p", "[", "1", "]", ")", ")", ";", "if", "(", "$", "value", "===", "false", ")", "{", "return", "0", ";", "}", "return", "$", "value", ";", "}", "return", "0", ";", "}" ]
Returns the domain age who.is lists for the current url @param string $domain @return int
[ "Returns", "the", "domain", "age", "who", ".", "is", "lists", "for", "the", "current", "url" ]
72df150735664275a60a7861e468c6ff3b152a14
https://github.com/matomo-org/matomo/blob/72df150735664275a60a7861e468c6ff3b152a14/plugins/SEO/Metric/DomainAge.php#L91-L103
210,255
guzzle/guzzle
src/Handler/EasyHandle.php
EasyHandle.createResponse
public function createResponse() { if (empty($this->headers)) { throw new \RuntimeException('No headers have been received'); } // HTTP-version SP status-code SP reason-phrase $startLine = explode(' ', array_shift($this->headers), 3); $headers = \GuzzleHttp\headers_from_lines($this->headers); $normalizedKeys = \GuzzleHttp\normalize_header_keys($headers); if (!empty($this->options['decode_content']) && isset($normalizedKeys['content-encoding']) ) { $headers['x-encoded-content-encoding'] = $headers[$normalizedKeys['content-encoding']]; unset($headers[$normalizedKeys['content-encoding']]); if (isset($normalizedKeys['content-length'])) { $headers['x-encoded-content-length'] = $headers[$normalizedKeys['content-length']]; $bodyLength = (int) $this->sink->getSize(); if ($bodyLength) { $headers[$normalizedKeys['content-length']] = $bodyLength; } else { unset($headers[$normalizedKeys['content-length']]); } } } // Attach a response to the easy handle with the parsed headers. $this->response = new Response( $startLine[1], $headers, $this->sink, substr($startLine[0], 5), isset($startLine[2]) ? (string) $startLine[2] : null ); }
php
public function createResponse() { if (empty($this->headers)) { throw new \RuntimeException('No headers have been received'); } // HTTP-version SP status-code SP reason-phrase $startLine = explode(' ', array_shift($this->headers), 3); $headers = \GuzzleHttp\headers_from_lines($this->headers); $normalizedKeys = \GuzzleHttp\normalize_header_keys($headers); if (!empty($this->options['decode_content']) && isset($normalizedKeys['content-encoding']) ) { $headers['x-encoded-content-encoding'] = $headers[$normalizedKeys['content-encoding']]; unset($headers[$normalizedKeys['content-encoding']]); if (isset($normalizedKeys['content-length'])) { $headers['x-encoded-content-length'] = $headers[$normalizedKeys['content-length']]; $bodyLength = (int) $this->sink->getSize(); if ($bodyLength) { $headers[$normalizedKeys['content-length']] = $bodyLength; } else { unset($headers[$normalizedKeys['content-length']]); } } } // Attach a response to the easy handle with the parsed headers. $this->response = new Response( $startLine[1], $headers, $this->sink, substr($startLine[0], 5), isset($startLine[2]) ? (string) $startLine[2] : null ); }
[ "public", "function", "createResponse", "(", ")", "{", "if", "(", "empty", "(", "$", "this", "->", "headers", ")", ")", "{", "throw", "new", "\\", "RuntimeException", "(", "'No headers have been received'", ")", ";", "}", "// HTTP-version SP status-code SP reason-phrase", "$", "startLine", "=", "explode", "(", "' '", ",", "array_shift", "(", "$", "this", "->", "headers", ")", ",", "3", ")", ";", "$", "headers", "=", "\\", "GuzzleHttp", "\\", "headers_from_lines", "(", "$", "this", "->", "headers", ")", ";", "$", "normalizedKeys", "=", "\\", "GuzzleHttp", "\\", "normalize_header_keys", "(", "$", "headers", ")", ";", "if", "(", "!", "empty", "(", "$", "this", "->", "options", "[", "'decode_content'", "]", ")", "&&", "isset", "(", "$", "normalizedKeys", "[", "'content-encoding'", "]", ")", ")", "{", "$", "headers", "[", "'x-encoded-content-encoding'", "]", "=", "$", "headers", "[", "$", "normalizedKeys", "[", "'content-encoding'", "]", "]", ";", "unset", "(", "$", "headers", "[", "$", "normalizedKeys", "[", "'content-encoding'", "]", "]", ")", ";", "if", "(", "isset", "(", "$", "normalizedKeys", "[", "'content-length'", "]", ")", ")", "{", "$", "headers", "[", "'x-encoded-content-length'", "]", "=", "$", "headers", "[", "$", "normalizedKeys", "[", "'content-length'", "]", "]", ";", "$", "bodyLength", "=", "(", "int", ")", "$", "this", "->", "sink", "->", "getSize", "(", ")", ";", "if", "(", "$", "bodyLength", ")", "{", "$", "headers", "[", "$", "normalizedKeys", "[", "'content-length'", "]", "]", "=", "$", "bodyLength", ";", "}", "else", "{", "unset", "(", "$", "headers", "[", "$", "normalizedKeys", "[", "'content-length'", "]", "]", ")", ";", "}", "}", "}", "// Attach a response to the easy handle with the parsed headers.", "$", "this", "->", "response", "=", "new", "Response", "(", "$", "startLine", "[", "1", "]", ",", "$", "headers", ",", "$", "this", "->", "sink", ",", "substr", "(", "$", "startLine", "[", "0", "]", ",", "5", ")", ",", "isset", "(", "$", "startLine", "[", "2", "]", ")", "?", "(", "string", ")", "$", "startLine", "[", "2", "]", ":", "null", ")", ";", "}" ]
Attach a response to the easy handle based on the received headers. @throws \RuntimeException if no headers have been received.
[ "Attach", "a", "response", "to", "the", "easy", "handle", "based", "on", "the", "received", "headers", "." ]
bf595424e4d442a190582e088985dc835a789071
https://github.com/guzzle/guzzle/blob/bf595424e4d442a190582e088985dc835a789071/src/Handler/EasyHandle.php#L45-L83
210,256
guzzle/guzzle
src/Client.php
Client.transfer
private function transfer(RequestInterface $request, array $options) { // save_to -> sink if (isset($options['save_to'])) { $options['sink'] = $options['save_to']; unset($options['save_to']); } // exceptions -> http_errors if (isset($options['exceptions'])) { $options['http_errors'] = $options['exceptions']; unset($options['exceptions']); } $request = $this->applyOptions($request, $options); $handler = $options['handler']; try { return Promise\promise_for($handler($request, $options)); } catch (\Exception $e) { return Promise\rejection_for($e); } }
php
private function transfer(RequestInterface $request, array $options) { // save_to -> sink if (isset($options['save_to'])) { $options['sink'] = $options['save_to']; unset($options['save_to']); } // exceptions -> http_errors if (isset($options['exceptions'])) { $options['http_errors'] = $options['exceptions']; unset($options['exceptions']); } $request = $this->applyOptions($request, $options); $handler = $options['handler']; try { return Promise\promise_for($handler($request, $options)); } catch (\Exception $e) { return Promise\rejection_for($e); } }
[ "private", "function", "transfer", "(", "RequestInterface", "$", "request", ",", "array", "$", "options", ")", "{", "// save_to -> sink", "if", "(", "isset", "(", "$", "options", "[", "'save_to'", "]", ")", ")", "{", "$", "options", "[", "'sink'", "]", "=", "$", "options", "[", "'save_to'", "]", ";", "unset", "(", "$", "options", "[", "'save_to'", "]", ")", ";", "}", "// exceptions -> http_errors", "if", "(", "isset", "(", "$", "options", "[", "'exceptions'", "]", ")", ")", "{", "$", "options", "[", "'http_errors'", "]", "=", "$", "options", "[", "'exceptions'", "]", ";", "unset", "(", "$", "options", "[", "'exceptions'", "]", ")", ";", "}", "$", "request", "=", "$", "this", "->", "applyOptions", "(", "$", "request", ",", "$", "options", ")", ";", "$", "handler", "=", "$", "options", "[", "'handler'", "]", ";", "try", "{", "return", "Promise", "\\", "promise_for", "(", "$", "handler", "(", "$", "request", ",", "$", "options", ")", ")", ";", "}", "catch", "(", "\\", "Exception", "$", "e", ")", "{", "return", "Promise", "\\", "rejection_for", "(", "$", "e", ")", ";", "}", "}" ]
Transfers the given request and applies request options. The URI of the request is not modified and the request options are used as-is without merging in default options. @param RequestInterface $request @param array $options @return Promise\PromiseInterface
[ "Transfers", "the", "given", "request", "and", "applies", "request", "options", "." ]
bf595424e4d442a190582e088985dc835a789071
https://github.com/guzzle/guzzle/blob/bf595424e4d442a190582e088985dc835a789071/src/Client.php#L259-L281
210,257
guzzle/guzzle
src/Middleware.php
Middleware.cookies
public static function cookies() { return function (callable $handler) { return function ($request, array $options) use ($handler) { if (empty($options['cookies'])) { return $handler($request, $options); } elseif (!($options['cookies'] instanceof CookieJarInterface)) { throw new \InvalidArgumentException('cookies must be an instance of GuzzleHttp\Cookie\CookieJarInterface'); } $cookieJar = $options['cookies']; $request = $cookieJar->withCookieHeader($request); return $handler($request, $options) ->then( function ($response) use ($cookieJar, $request) { $cookieJar->extractCookies($request, $response); return $response; } ); }; }; }
php
public static function cookies() { return function (callable $handler) { return function ($request, array $options) use ($handler) { if (empty($options['cookies'])) { return $handler($request, $options); } elseif (!($options['cookies'] instanceof CookieJarInterface)) { throw new \InvalidArgumentException('cookies must be an instance of GuzzleHttp\Cookie\CookieJarInterface'); } $cookieJar = $options['cookies']; $request = $cookieJar->withCookieHeader($request); return $handler($request, $options) ->then( function ($response) use ($cookieJar, $request) { $cookieJar->extractCookies($request, $response); return $response; } ); }; }; }
[ "public", "static", "function", "cookies", "(", ")", "{", "return", "function", "(", "callable", "$", "handler", ")", "{", "return", "function", "(", "$", "request", ",", "array", "$", "options", ")", "use", "(", "$", "handler", ")", "{", "if", "(", "empty", "(", "$", "options", "[", "'cookies'", "]", ")", ")", "{", "return", "$", "handler", "(", "$", "request", ",", "$", "options", ")", ";", "}", "elseif", "(", "!", "(", "$", "options", "[", "'cookies'", "]", "instanceof", "CookieJarInterface", ")", ")", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "'cookies must be an instance of GuzzleHttp\\Cookie\\CookieJarInterface'", ")", ";", "}", "$", "cookieJar", "=", "$", "options", "[", "'cookies'", "]", ";", "$", "request", "=", "$", "cookieJar", "->", "withCookieHeader", "(", "$", "request", ")", ";", "return", "$", "handler", "(", "$", "request", ",", "$", "options", ")", "->", "then", "(", "function", "(", "$", "response", ")", "use", "(", "$", "cookieJar", ",", "$", "request", ")", "{", "$", "cookieJar", "->", "extractCookies", "(", "$", "request", ",", "$", "response", ")", ";", "return", "$", "response", ";", "}", ")", ";", "}", ";", "}", ";", "}" ]
Middleware that adds cookies to requests. The options array must be set to a CookieJarInterface in order to use cookies. This is typically handled for you by a client. @return callable Returns a function that accepts the next handler.
[ "Middleware", "that", "adds", "cookies", "to", "requests", "." ]
bf595424e4d442a190582e088985dc835a789071
https://github.com/guzzle/guzzle/blob/bf595424e4d442a190582e088985dc835a789071/src/Middleware.php#L25-L45
210,258
guzzle/guzzle
src/Middleware.php
Middleware.history
public static function history(&$container) { if (!is_array($container) && !$container instanceof \ArrayAccess) { throw new \InvalidArgumentException('history container must be an array or object implementing ArrayAccess'); } return function (callable $handler) use (&$container) { return function ($request, array $options) use ($handler, &$container) { return $handler($request, $options)->then( function ($value) use ($request, &$container, $options) { $container[] = [ 'request' => $request, 'response' => $value, 'error' => null, 'options' => $options ]; return $value; }, function ($reason) use ($request, &$container, $options) { $container[] = [ 'request' => $request, 'response' => null, 'error' => $reason, 'options' => $options ]; return \GuzzleHttp\Promise\rejection_for($reason); } ); }; }; }
php
public static function history(&$container) { if (!is_array($container) && !$container instanceof \ArrayAccess) { throw new \InvalidArgumentException('history container must be an array or object implementing ArrayAccess'); } return function (callable $handler) use (&$container) { return function ($request, array $options) use ($handler, &$container) { return $handler($request, $options)->then( function ($value) use ($request, &$container, $options) { $container[] = [ 'request' => $request, 'response' => $value, 'error' => null, 'options' => $options ]; return $value; }, function ($reason) use ($request, &$container, $options) { $container[] = [ 'request' => $request, 'response' => null, 'error' => $reason, 'options' => $options ]; return \GuzzleHttp\Promise\rejection_for($reason); } ); }; }; }
[ "public", "static", "function", "history", "(", "&", "$", "container", ")", "{", "if", "(", "!", "is_array", "(", "$", "container", ")", "&&", "!", "$", "container", "instanceof", "\\", "ArrayAccess", ")", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "'history container must be an array or object implementing ArrayAccess'", ")", ";", "}", "return", "function", "(", "callable", "$", "handler", ")", "use", "(", "&", "$", "container", ")", "{", "return", "function", "(", "$", "request", ",", "array", "$", "options", ")", "use", "(", "$", "handler", ",", "&", "$", "container", ")", "{", "return", "$", "handler", "(", "$", "request", ",", "$", "options", ")", "->", "then", "(", "function", "(", "$", "value", ")", "use", "(", "$", "request", ",", "&", "$", "container", ",", "$", "options", ")", "{", "$", "container", "[", "]", "=", "[", "'request'", "=>", "$", "request", ",", "'response'", "=>", "$", "value", ",", "'error'", "=>", "null", ",", "'options'", "=>", "$", "options", "]", ";", "return", "$", "value", ";", "}", ",", "function", "(", "$", "reason", ")", "use", "(", "$", "request", ",", "&", "$", "container", ",", "$", "options", ")", "{", "$", "container", "[", "]", "=", "[", "'request'", "=>", "$", "request", ",", "'response'", "=>", "null", ",", "'error'", "=>", "$", "reason", ",", "'options'", "=>", "$", "options", "]", ";", "return", "\\", "GuzzleHttp", "\\", "Promise", "\\", "rejection_for", "(", "$", "reason", ")", ";", "}", ")", ";", "}", ";", "}", ";", "}" ]
Middleware that pushes history data to an ArrayAccess container. @param array|\ArrayAccess $container Container to hold the history (by reference). @return callable Returns a function that accepts the next handler. @throws \InvalidArgumentException if container is not an array or ArrayAccess.
[ "Middleware", "that", "pushes", "history", "data", "to", "an", "ArrayAccess", "container", "." ]
bf595424e4d442a190582e088985dc835a789071
https://github.com/guzzle/guzzle/blob/bf595424e4d442a190582e088985dc835a789071/src/Middleware.php#L81-L111
210,259
guzzle/guzzle
src/Middleware.php
Middleware.tap
public static function tap(callable $before = null, callable $after = null) { return function (callable $handler) use ($before, $after) { return function ($request, array $options) use ($handler, $before, $after) { if ($before) { $before($request, $options); } $response = $handler($request, $options); if ($after) { $after($request, $options, $response); } return $response; }; }; }
php
public static function tap(callable $before = null, callable $after = null) { return function (callable $handler) use ($before, $after) { return function ($request, array $options) use ($handler, $before, $after) { if ($before) { $before($request, $options); } $response = $handler($request, $options); if ($after) { $after($request, $options, $response); } return $response; }; }; }
[ "public", "static", "function", "tap", "(", "callable", "$", "before", "=", "null", ",", "callable", "$", "after", "=", "null", ")", "{", "return", "function", "(", "callable", "$", "handler", ")", "use", "(", "$", "before", ",", "$", "after", ")", "{", "return", "function", "(", "$", "request", ",", "array", "$", "options", ")", "use", "(", "$", "handler", ",", "$", "before", ",", "$", "after", ")", "{", "if", "(", "$", "before", ")", "{", "$", "before", "(", "$", "request", ",", "$", "options", ")", ";", "}", "$", "response", "=", "$", "handler", "(", "$", "request", ",", "$", "options", ")", ";", "if", "(", "$", "after", ")", "{", "$", "after", "(", "$", "request", ",", "$", "options", ",", "$", "response", ")", ";", "}", "return", "$", "response", ";", "}", ";", "}", ";", "}" ]
Middleware that invokes a callback before and after sending a request. The provided listener cannot modify or alter the response. It simply "taps" into the chain to be notified before returning the promise. The before listener accepts a request and options array, and the after listener accepts a request, options array, and response promise. @param callable $before Function to invoke before forwarding the request. @param callable $after Function invoked after forwarding. @return callable Returns a function that accepts the next handler.
[ "Middleware", "that", "invokes", "a", "callback", "before", "and", "after", "sending", "a", "request", "." ]
bf595424e4d442a190582e088985dc835a789071
https://github.com/guzzle/guzzle/blob/bf595424e4d442a190582e088985dc835a789071/src/Middleware.php#L126-L140
210,260
guzzle/guzzle
src/Middleware.php
Middleware.retry
public static function retry(callable $decider, callable $delay = null) { return function (callable $handler) use ($decider, $delay) { return new RetryMiddleware($decider, $handler, $delay); }; }
php
public static function retry(callable $decider, callable $delay = null) { return function (callable $handler) use ($decider, $delay) { return new RetryMiddleware($decider, $handler, $delay); }; }
[ "public", "static", "function", "retry", "(", "callable", "$", "decider", ",", "callable", "$", "delay", "=", "null", ")", "{", "return", "function", "(", "callable", "$", "handler", ")", "use", "(", "$", "decider", ",", "$", "delay", ")", "{", "return", "new", "RetryMiddleware", "(", "$", "decider", ",", "$", "handler", ",", "$", "delay", ")", ";", "}", ";", "}" ]
Middleware that retries requests based on the boolean result of invoking the provided "decider" function. If no delay function is provided, a simple implementation of exponential backoff will be utilized. @param callable $decider Function that accepts the number of retries, a request, [response], and [exception] and returns true if the request is to be retried. @param callable $delay Function that accepts the number of retries and returns the number of milliseconds to delay. @return callable Returns a function that accepts the next handler.
[ "Middleware", "that", "retries", "requests", "based", "on", "the", "boolean", "result", "of", "invoking", "the", "provided", "decider", "function", "." ]
bf595424e4d442a190582e088985dc835a789071
https://github.com/guzzle/guzzle/blob/bf595424e4d442a190582e088985dc835a789071/src/Middleware.php#L169-L174
210,261
guzzle/guzzle
src/TransferStats.php
TransferStats.getHandlerStat
public function getHandlerStat($stat) { return isset($this->handlerStats[$stat]) ? $this->handlerStats[$stat] : null; }
php
public function getHandlerStat($stat) { return isset($this->handlerStats[$stat]) ? $this->handlerStats[$stat] : null; }
[ "public", "function", "getHandlerStat", "(", "$", "stat", ")", "{", "return", "isset", "(", "$", "this", "->", "handlerStats", "[", "$", "stat", "]", ")", "?", "$", "this", "->", "handlerStats", "[", "$", "stat", "]", ":", "null", ";", "}" ]
Get a specific handler statistic from the handler by name. @param string $stat Handler specific transfer stat to retrieve. @return mixed|null
[ "Get", "a", "specific", "handler", "statistic", "from", "the", "handler", "by", "name", "." ]
bf595424e4d442a190582e088985dc835a789071
https://github.com/guzzle/guzzle/blob/bf595424e4d442a190582e088985dc835a789071/src/TransferStats.php#L120-L125
210,262
guzzle/guzzle
src/HandlerStack.php
HandlerStack.create
public static function create(callable $handler = null) { $stack = new self($handler ?: choose_handler()); $stack->push(Middleware::httpErrors(), 'http_errors'); $stack->push(Middleware::redirect(), 'allow_redirects'); $stack->push(Middleware::cookies(), 'cookies'); $stack->push(Middleware::prepareBody(), 'prepare_body'); return $stack; }
php
public static function create(callable $handler = null) { $stack = new self($handler ?: choose_handler()); $stack->push(Middleware::httpErrors(), 'http_errors'); $stack->push(Middleware::redirect(), 'allow_redirects'); $stack->push(Middleware::cookies(), 'cookies'); $stack->push(Middleware::prepareBody(), 'prepare_body'); return $stack; }
[ "public", "static", "function", "create", "(", "callable", "$", "handler", "=", "null", ")", "{", "$", "stack", "=", "new", "self", "(", "$", "handler", "?", ":", "choose_handler", "(", ")", ")", ";", "$", "stack", "->", "push", "(", "Middleware", "::", "httpErrors", "(", ")", ",", "'http_errors'", ")", ";", "$", "stack", "->", "push", "(", "Middleware", "::", "redirect", "(", ")", ",", "'allow_redirects'", ")", ";", "$", "stack", "->", "push", "(", "Middleware", "::", "cookies", "(", ")", ",", "'cookies'", ")", ";", "$", "stack", "->", "push", "(", "Middleware", "::", "prepareBody", "(", ")", ",", "'prepare_body'", ")", ";", "return", "$", "stack", ";", "}" ]
Creates a default handler stack that can be used by clients. The returned handler will wrap the provided handler or use the most appropriate default handler for your system. The returned HandlerStack has support for cookies, redirects, HTTP error exceptions, and preparing a body before sending. The returned handler stack can be passed to a client in the "handler" option. @param callable $handler HTTP handler function to use with the stack. If no handler is provided, the best handler for your system will be utilized. @return HandlerStack
[ "Creates", "a", "default", "handler", "stack", "that", "can", "be", "used", "by", "clients", "." ]
bf595424e4d442a190582e088985dc835a789071
https://github.com/guzzle/guzzle/blob/bf595424e4d442a190582e088985dc835a789071/src/HandlerStack.php#L38-L47
210,263
guzzle/guzzle
src/HandlerStack.php
HandlerStack.unshift
public function unshift(callable $middleware, $name = null) { array_unshift($this->stack, [$middleware, $name]); $this->cached = null; }
php
public function unshift(callable $middleware, $name = null) { array_unshift($this->stack, [$middleware, $name]); $this->cached = null; }
[ "public", "function", "unshift", "(", "callable", "$", "middleware", ",", "$", "name", "=", "null", ")", "{", "array_unshift", "(", "$", "this", "->", "stack", ",", "[", "$", "middleware", ",", "$", "name", "]", ")", ";", "$", "this", "->", "cached", "=", "null", ";", "}" ]
Unshift a middleware to the bottom of the stack. @param callable $middleware Middleware function @param string $name Name to register for this middleware.
[ "Unshift", "a", "middleware", "to", "the", "bottom", "of", "the", "stack", "." ]
bf595424e4d442a190582e088985dc835a789071
https://github.com/guzzle/guzzle/blob/bf595424e4d442a190582e088985dc835a789071/src/HandlerStack.php#L127-L131
210,264
guzzle/guzzle
src/HandlerStack.php
HandlerStack.push
public function push(callable $middleware, $name = '') { $this->stack[] = [$middleware, $name]; $this->cached = null; }
php
public function push(callable $middleware, $name = '') { $this->stack[] = [$middleware, $name]; $this->cached = null; }
[ "public", "function", "push", "(", "callable", "$", "middleware", ",", "$", "name", "=", "''", ")", "{", "$", "this", "->", "stack", "[", "]", "=", "[", "$", "middleware", ",", "$", "name", "]", ";", "$", "this", "->", "cached", "=", "null", ";", "}" ]
Push a middleware to the top of the stack. @param callable $middleware Middleware function @param string $name Name to register for this middleware.
[ "Push", "a", "middleware", "to", "the", "top", "of", "the", "stack", "." ]
bf595424e4d442a190582e088985dc835a789071
https://github.com/guzzle/guzzle/blob/bf595424e4d442a190582e088985dc835a789071/src/HandlerStack.php#L139-L143
210,265
guzzle/guzzle
src/HandlerStack.php
HandlerStack.after
public function after($findName, callable $middleware, $withName = '') { $this->splice($findName, $withName, $middleware, false); }
php
public function after($findName, callable $middleware, $withName = '') { $this->splice($findName, $withName, $middleware, false); }
[ "public", "function", "after", "(", "$", "findName", ",", "callable", "$", "middleware", ",", "$", "withName", "=", "''", ")", "{", "$", "this", "->", "splice", "(", "$", "findName", ",", "$", "withName", ",", "$", "middleware", ",", "false", ")", ";", "}" ]
Add a middleware after another middleware by name. @param string $findName Middleware to find @param callable $middleware Middleware function @param string $withName Name to register for this middleware.
[ "Add", "a", "middleware", "after", "another", "middleware", "by", "name", "." ]
bf595424e4d442a190582e088985dc835a789071
https://github.com/guzzle/guzzle/blob/bf595424e4d442a190582e088985dc835a789071/src/HandlerStack.php#L164-L167
210,266
guzzle/guzzle
src/HandlerStack.php
HandlerStack.remove
public function remove($remove) { $this->cached = null; $idx = is_callable($remove) ? 0 : 1; $this->stack = array_values(array_filter( $this->stack, function ($tuple) use ($idx, $remove) { return $tuple[$idx] !== $remove; } )); }
php
public function remove($remove) { $this->cached = null; $idx = is_callable($remove) ? 0 : 1; $this->stack = array_values(array_filter( $this->stack, function ($tuple) use ($idx, $remove) { return $tuple[$idx] !== $remove; } )); }
[ "public", "function", "remove", "(", "$", "remove", ")", "{", "$", "this", "->", "cached", "=", "null", ";", "$", "idx", "=", "is_callable", "(", "$", "remove", ")", "?", "0", ":", "1", ";", "$", "this", "->", "stack", "=", "array_values", "(", "array_filter", "(", "$", "this", "->", "stack", ",", "function", "(", "$", "tuple", ")", "use", "(", "$", "idx", ",", "$", "remove", ")", "{", "return", "$", "tuple", "[", "$", "idx", "]", "!==", "$", "remove", ";", "}", ")", ")", ";", "}" ]
Remove a middleware by instance or name from the stack. @param callable|string $remove Middleware to remove by instance or name.
[ "Remove", "a", "middleware", "by", "instance", "or", "name", "from", "the", "stack", "." ]
bf595424e4d442a190582e088985dc835a789071
https://github.com/guzzle/guzzle/blob/bf595424e4d442a190582e088985dc835a789071/src/HandlerStack.php#L174-L184
210,267
guzzle/guzzle
src/HandlerStack.php
HandlerStack.debugCallable
private function debugCallable($fn) { if (is_string($fn)) { return "callable({$fn})"; } if (is_array($fn)) { return is_string($fn[0]) ? "callable({$fn[0]}::{$fn[1]})" : "callable(['" . get_class($fn[0]) . "', '{$fn[1]}'])"; } return 'callable(' . spl_object_hash($fn) . ')'; }
php
private function debugCallable($fn) { if (is_string($fn)) { return "callable({$fn})"; } if (is_array($fn)) { return is_string($fn[0]) ? "callable({$fn[0]}::{$fn[1]})" : "callable(['" . get_class($fn[0]) . "', '{$fn[1]}'])"; } return 'callable(' . spl_object_hash($fn) . ')'; }
[ "private", "function", "debugCallable", "(", "$", "fn", ")", "{", "if", "(", "is_string", "(", "$", "fn", ")", ")", "{", "return", "\"callable({$fn})\"", ";", "}", "if", "(", "is_array", "(", "$", "fn", ")", ")", "{", "return", "is_string", "(", "$", "fn", "[", "0", "]", ")", "?", "\"callable({$fn[0]}::{$fn[1]})\"", ":", "\"callable(['\"", ".", "get_class", "(", "$", "fn", "[", "0", "]", ")", ".", "\"', '{$fn[1]}'])\"", ";", "}", "return", "'callable('", ".", "spl_object_hash", "(", "$", "fn", ")", ".", "')'", ";", "}" ]
Provides a debug string for a given callable. @param array|callable $fn Function to write as a string. @return string
[ "Provides", "a", "debug", "string", "for", "a", "given", "callable", "." ]
bf595424e4d442a190582e088985dc835a789071
https://github.com/guzzle/guzzle/blob/bf595424e4d442a190582e088985dc835a789071/src/HandlerStack.php#L259-L272
210,268
guzzle/guzzle
src/Handler/StreamHandler.php
StreamHandler.drain
private function drain( StreamInterface $source, StreamInterface $sink, $contentLength ) { // If a content-length header is provided, then stop reading once // that number of bytes has been read. This can prevent infinitely // reading from a stream when dealing with servers that do not honor // Connection: Close headers. Psr7\copy_to_stream( $source, $sink, (strlen($contentLength) > 0 && (int) $contentLength > 0) ? (int) $contentLength : -1 ); $sink->seek(0); $source->close(); return $sink; }
php
private function drain( StreamInterface $source, StreamInterface $sink, $contentLength ) { // If a content-length header is provided, then stop reading once // that number of bytes has been read. This can prevent infinitely // reading from a stream when dealing with servers that do not honor // Connection: Close headers. Psr7\copy_to_stream( $source, $sink, (strlen($contentLength) > 0 && (int) $contentLength > 0) ? (int) $contentLength : -1 ); $sink->seek(0); $source->close(); return $sink; }
[ "private", "function", "drain", "(", "StreamInterface", "$", "source", ",", "StreamInterface", "$", "sink", ",", "$", "contentLength", ")", "{", "// If a content-length header is provided, then stop reading once", "// that number of bytes has been read. This can prevent infinitely", "// reading from a stream when dealing with servers that do not honor", "// Connection: Close headers.", "Psr7", "\\", "copy_to_stream", "(", "$", "source", ",", "$", "sink", ",", "(", "strlen", "(", "$", "contentLength", ")", ">", "0", "&&", "(", "int", ")", "$", "contentLength", ">", "0", ")", "?", "(", "int", ")", "$", "contentLength", ":", "-", "1", ")", ";", "$", "sink", "->", "seek", "(", "0", ")", ";", "$", "source", "->", "close", "(", ")", ";", "return", "$", "sink", ";", "}" ]
Drains the source stream into the "sink" client option. @param StreamInterface $source @param StreamInterface $sink @param string $contentLength Header specifying the amount of data to read. @return StreamInterface @throws \RuntimeException when the sink option is invalid.
[ "Drains", "the", "source", "stream", "into", "the", "sink", "client", "option", "." ]
bf595424e4d442a190582e088985dc835a789071
https://github.com/guzzle/guzzle/blob/bf595424e4d442a190582e088985dc835a789071/src/Handler/StreamHandler.php#L201-L220
210,269
guzzle/guzzle
src/Pool.php
Pool.batch
public static function batch( ClientInterface $client, $requests, array $options = [] ) { $res = []; self::cmpCallback($options, 'fulfilled', $res); self::cmpCallback($options, 'rejected', $res); $pool = new static($client, $requests, $options); $pool->promise()->wait(); ksort($res); return $res; }
php
public static function batch( ClientInterface $client, $requests, array $options = [] ) { $res = []; self::cmpCallback($options, 'fulfilled', $res); self::cmpCallback($options, 'rejected', $res); $pool = new static($client, $requests, $options); $pool->promise()->wait(); ksort($res); return $res; }
[ "public", "static", "function", "batch", "(", "ClientInterface", "$", "client", ",", "$", "requests", ",", "array", "$", "options", "=", "[", "]", ")", "{", "$", "res", "=", "[", "]", ";", "self", "::", "cmpCallback", "(", "$", "options", ",", "'fulfilled'", ",", "$", "res", ")", ";", "self", "::", "cmpCallback", "(", "$", "options", ",", "'rejected'", ",", "$", "res", ")", ";", "$", "pool", "=", "new", "static", "(", "$", "client", ",", "$", "requests", ",", "$", "options", ")", ";", "$", "pool", "->", "promise", "(", ")", "->", "wait", "(", ")", ";", "ksort", "(", "$", "res", ")", ";", "return", "$", "res", ";", "}" ]
Sends multiple requests concurrently and returns an array of responses and exceptions that uses the same ordering as the provided requests. IMPORTANT: This method keeps every request and response in memory, and as such, is NOT recommended when sending a large number or an indeterminate number of requests concurrently. @param ClientInterface $client Client used to send the requests @param array|\Iterator $requests Requests to send concurrently. @param array $options Passes through the options available in {@see GuzzleHttp\Pool::__construct} @return array Returns an array containing the response or an exception in the same order that the requests were sent. @throws \InvalidArgumentException if the event format is incorrect.
[ "Sends", "multiple", "requests", "concurrently", "and", "returns", "an", "array", "of", "responses", "and", "exceptions", "that", "uses", "the", "same", "ordering", "as", "the", "provided", "requests", "." ]
bf595424e4d442a190582e088985dc835a789071
https://github.com/guzzle/guzzle/blob/bf595424e4d442a190582e088985dc835a789071/src/Pool.php#L94-L107
210,270
guzzle/guzzle
src/Cookie/SetCookie.php
SetCookie.matchesPath
public function matchesPath($requestPath) { $cookiePath = $this->getPath(); // Match on exact matches or when path is the default empty "/" if ($cookiePath === '/' || $cookiePath == $requestPath) { return true; } // Ensure that the cookie-path is a prefix of the request path. if (0 !== strpos($requestPath, $cookiePath)) { return false; } // Match if the last character of the cookie-path is "/" if (substr($cookiePath, -1, 1) === '/') { return true; } // Match if the first character not included in cookie path is "/" return substr($requestPath, strlen($cookiePath), 1) === '/'; }
php
public function matchesPath($requestPath) { $cookiePath = $this->getPath(); // Match on exact matches or when path is the default empty "/" if ($cookiePath === '/' || $cookiePath == $requestPath) { return true; } // Ensure that the cookie-path is a prefix of the request path. if (0 !== strpos($requestPath, $cookiePath)) { return false; } // Match if the last character of the cookie-path is "/" if (substr($cookiePath, -1, 1) === '/') { return true; } // Match if the first character not included in cookie path is "/" return substr($requestPath, strlen($cookiePath), 1) === '/'; }
[ "public", "function", "matchesPath", "(", "$", "requestPath", ")", "{", "$", "cookiePath", "=", "$", "this", "->", "getPath", "(", ")", ";", "// Match on exact matches or when path is the default empty \"/\"", "if", "(", "$", "cookiePath", "===", "'/'", "||", "$", "cookiePath", "==", "$", "requestPath", ")", "{", "return", "true", ";", "}", "// Ensure that the cookie-path is a prefix of the request path.", "if", "(", "0", "!==", "strpos", "(", "$", "requestPath", ",", "$", "cookiePath", ")", ")", "{", "return", "false", ";", "}", "// Match if the last character of the cookie-path is \"/\"", "if", "(", "substr", "(", "$", "cookiePath", ",", "-", "1", ",", "1", ")", "===", "'/'", ")", "{", "return", "true", ";", "}", "// Match if the first character not included in cookie path is \"/\"", "return", "substr", "(", "$", "requestPath", ",", "strlen", "(", "$", "cookiePath", ")", ",", "1", ")", "===", "'/'", ";", "}" ]
Check if the cookie matches a path value. A request-path path-matches a given cookie-path if at least one of the following conditions holds: - The cookie-path and the request-path are identical. - The cookie-path is a prefix of the request-path, and the last character of the cookie-path is %x2F ("/"). - The cookie-path is a prefix of the request-path, and the first character of the request-path that is not included in the cookie- path is a %x2F ("/") character. @param string $requestPath Path to check against @return bool
[ "Check", "if", "the", "cookie", "matches", "a", "path", "value", "." ]
bf595424e4d442a190582e088985dc835a789071
https://github.com/guzzle/guzzle/blob/bf595424e4d442a190582e088985dc835a789071/src/Cookie/SetCookie.php#L304-L325
210,271
guzzle/guzzle
src/Handler/MockHandler.php
MockHandler.createWithMiddleware
public static function createWithMiddleware( array $queue = null, callable $onFulfilled = null, callable $onRejected = null ) { return HandlerStack::create(new self($queue, $onFulfilled, $onRejected)); }
php
public static function createWithMiddleware( array $queue = null, callable $onFulfilled = null, callable $onRejected = null ) { return HandlerStack::create(new self($queue, $onFulfilled, $onRejected)); }
[ "public", "static", "function", "createWithMiddleware", "(", "array", "$", "queue", "=", "null", ",", "callable", "$", "onFulfilled", "=", "null", ",", "callable", "$", "onRejected", "=", "null", ")", "{", "return", "HandlerStack", "::", "create", "(", "new", "self", "(", "$", "queue", ",", "$", "onFulfilled", ",", "$", "onRejected", ")", ")", ";", "}" ]
Creates a new MockHandler that uses the default handler stack list of middlewares. @param array $queue Array of responses, callables, or exceptions. @param callable $onFulfilled Callback to invoke when the return value is fulfilled. @param callable $onRejected Callback to invoke when the return value is rejected. @return HandlerStack
[ "Creates", "a", "new", "MockHandler", "that", "uses", "the", "default", "handler", "stack", "list", "of", "middlewares", "." ]
bf595424e4d442a190582e088985dc835a789071
https://github.com/guzzle/guzzle/blob/bf595424e4d442a190582e088985dc835a789071/src/Handler/MockHandler.php#L33-L39
210,272
guzzle/guzzle
src/Handler/MockHandler.php
MockHandler.append
public function append() { foreach (func_get_args() as $value) { if ($value instanceof ResponseInterface || $value instanceof \Exception || $value instanceof PromiseInterface || is_callable($value) ) { $this->queue[] = $value; } else { throw new \InvalidArgumentException('Expected a response or ' . 'exception. Found ' . \GuzzleHttp\describe_type($value)); } } }
php
public function append() { foreach (func_get_args() as $value) { if ($value instanceof ResponseInterface || $value instanceof \Exception || $value instanceof PromiseInterface || is_callable($value) ) { $this->queue[] = $value; } else { throw new \InvalidArgumentException('Expected a response or ' . 'exception. Found ' . \GuzzleHttp\describe_type($value)); } } }
[ "public", "function", "append", "(", ")", "{", "foreach", "(", "func_get_args", "(", ")", "as", "$", "value", ")", "{", "if", "(", "$", "value", "instanceof", "ResponseInterface", "||", "$", "value", "instanceof", "\\", "Exception", "||", "$", "value", "instanceof", "PromiseInterface", "||", "is_callable", "(", "$", "value", ")", ")", "{", "$", "this", "->", "queue", "[", "]", "=", "$", "value", ";", "}", "else", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "'Expected a response or '", ".", "'exception. Found '", ".", "\\", "GuzzleHttp", "\\", "describe_type", "(", "$", "value", ")", ")", ";", "}", "}", "}" ]
Adds one or more variadic requests, exceptions, callables, or promises to the queue.
[ "Adds", "one", "or", "more", "variadic", "requests", "exceptions", "callables", "or", "promises", "to", "the", "queue", "." ]
bf595424e4d442a190582e088985dc835a789071
https://github.com/guzzle/guzzle/blob/bf595424e4d442a190582e088985dc835a789071/src/Handler/MockHandler.php#L132-L146
210,273
guzzle/guzzle
src/Handler/Proxy.php
Proxy.wrapSync
public static function wrapSync( callable $default, callable $sync ) { return function (RequestInterface $request, array $options) use ($default, $sync) { return empty($options[RequestOptions::SYNCHRONOUS]) ? $default($request, $options) : $sync($request, $options); }; }
php
public static function wrapSync( callable $default, callable $sync ) { return function (RequestInterface $request, array $options) use ($default, $sync) { return empty($options[RequestOptions::SYNCHRONOUS]) ? $default($request, $options) : $sync($request, $options); }; }
[ "public", "static", "function", "wrapSync", "(", "callable", "$", "default", ",", "callable", "$", "sync", ")", "{", "return", "function", "(", "RequestInterface", "$", "request", ",", "array", "$", "options", ")", "use", "(", "$", "default", ",", "$", "sync", ")", "{", "return", "empty", "(", "$", "options", "[", "RequestOptions", "::", "SYNCHRONOUS", "]", ")", "?", "$", "default", "(", "$", "request", ",", "$", "options", ")", ":", "$", "sync", "(", "$", "request", ",", "$", "options", ")", ";", "}", ";", "}" ]
Sends synchronous requests to a specific handler while sending all other requests to another handler. @param callable $default Handler used for normal responses @param callable $sync Handler used for synchronous responses. @return callable Returns the composed handler.
[ "Sends", "synchronous", "requests", "to", "a", "specific", "handler", "while", "sending", "all", "other", "requests", "to", "another", "handler", "." ]
bf595424e4d442a190582e088985dc835a789071
https://github.com/guzzle/guzzle/blob/bf595424e4d442a190582e088985dc835a789071/src/Handler/Proxy.php#L21-L30
210,274
guzzle/guzzle
src/Handler/Proxy.php
Proxy.wrapStreaming
public static function wrapStreaming( callable $default, callable $streaming ) { return function (RequestInterface $request, array $options) use ($default, $streaming) { return empty($options['stream']) ? $default($request, $options) : $streaming($request, $options); }; }
php
public static function wrapStreaming( callable $default, callable $streaming ) { return function (RequestInterface $request, array $options) use ($default, $streaming) { return empty($options['stream']) ? $default($request, $options) : $streaming($request, $options); }; }
[ "public", "static", "function", "wrapStreaming", "(", "callable", "$", "default", ",", "callable", "$", "streaming", ")", "{", "return", "function", "(", "RequestInterface", "$", "request", ",", "array", "$", "options", ")", "use", "(", "$", "default", ",", "$", "streaming", ")", "{", "return", "empty", "(", "$", "options", "[", "'stream'", "]", ")", "?", "$", "default", "(", "$", "request", ",", "$", "options", ")", ":", "$", "streaming", "(", "$", "request", ",", "$", "options", ")", ";", "}", ";", "}" ]
Sends streaming requests to a streaming compatible handler while sending all other requests to a default handler. This, for example, could be useful for taking advantage of the performance benefits of curl while still supporting true streaming through the StreamHandler. @param callable $default Handler used for non-streaming responses @param callable $streaming Handler used for streaming responses @return callable Returns the composed handler.
[ "Sends", "streaming", "requests", "to", "a", "streaming", "compatible", "handler", "while", "sending", "all", "other", "requests", "to", "a", "default", "handler", "." ]
bf595424e4d442a190582e088985dc835a789071
https://github.com/guzzle/guzzle/blob/bf595424e4d442a190582e088985dc835a789071/src/Handler/Proxy.php#L45-L54
210,275
guzzle/guzzle
build/Burgomaster.php
Burgomaster.debug
public function debug($message) { $prefix = date('c') . ': '; if ($this->sections) { $prefix .= '[' . end($this->sections) . '] '; } fwrite(STDERR, $prefix . $message . "\n"); }
php
public function debug($message) { $prefix = date('c') . ': '; if ($this->sections) { $prefix .= '[' . end($this->sections) . '] '; } fwrite(STDERR, $prefix . $message . "\n"); }
[ "public", "function", "debug", "(", "$", "message", ")", "{", "$", "prefix", "=", "date", "(", "'c'", ")", ".", "': '", ";", "if", "(", "$", "this", "->", "sections", ")", "{", "$", "prefix", ".=", "'['", ".", "end", "(", "$", "this", "->", "sections", ")", ".", "'] '", ";", "}", "fwrite", "(", "STDERR", ",", "$", "prefix", ".", "$", "message", ".", "\"\\n\"", ")", ";", "}" ]
Prints a debug message to STDERR bound to the current section. @param string $message Message to echo to STDERR
[ "Prints", "a", "debug", "message", "to", "STDERR", "bound", "to", "the", "current", "section", "." ]
bf595424e4d442a190582e088985dc835a789071
https://github.com/guzzle/guzzle/blob/bf595424e4d442a190582e088985dc835a789071/build/Burgomaster.php#L107-L116
210,276
guzzle/guzzle
build/Burgomaster.php
Burgomaster.deepCopy
public function deepCopy($from, $to) { if (!is_file($from)) { throw new \InvalidArgumentException("File not found: {$from}"); } $to = str_replace('//', '/', $this->stageDir . '/' . $to); $dir = dirname($to); if (!is_dir($dir)) { if (!mkdir($dir, 0777, true)) { throw new \RuntimeException("Unable to create directory: $dir"); } } if (!copy($from, $to)) { throw new \RuntimeException("Unable to copy $from to $to"); } }
php
public function deepCopy($from, $to) { if (!is_file($from)) { throw new \InvalidArgumentException("File not found: {$from}"); } $to = str_replace('//', '/', $this->stageDir . '/' . $to); $dir = dirname($to); if (!is_dir($dir)) { if (!mkdir($dir, 0777, true)) { throw new \RuntimeException("Unable to create directory: $dir"); } } if (!copy($from, $to)) { throw new \RuntimeException("Unable to copy $from to $to"); } }
[ "public", "function", "deepCopy", "(", "$", "from", ",", "$", "to", ")", "{", "if", "(", "!", "is_file", "(", "$", "from", ")", ")", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "\"File not found: {$from}\"", ")", ";", "}", "$", "to", "=", "str_replace", "(", "'//'", ",", "'/'", ",", "$", "this", "->", "stageDir", ".", "'/'", ".", "$", "to", ")", ";", "$", "dir", "=", "dirname", "(", "$", "to", ")", ";", "if", "(", "!", "is_dir", "(", "$", "dir", ")", ")", "{", "if", "(", "!", "mkdir", "(", "$", "dir", ",", "0777", ",", "true", ")", ")", "{", "throw", "new", "\\", "RuntimeException", "(", "\"Unable to create directory: $dir\"", ")", ";", "}", "}", "if", "(", "!", "copy", "(", "$", "from", ",", "$", "to", ")", ")", "{", "throw", "new", "\\", "RuntimeException", "(", "\"Unable to copy $from to $to\"", ")", ";", "}", "}" ]
Copies a file and creates the destination directory if needed. @param string $from File to copy @param string $to Destination to copy the file to, relative to the base staging directory. @throws \InvalidArgumentException if the file cannot be found @throws \RuntimeException if the directory cannot be created. @throws \RuntimeException if the file cannot be copied.
[ "Copies", "a", "file", "and", "creates", "the", "destination", "directory", "if", "needed", "." ]
bf595424e4d442a190582e088985dc835a789071
https://github.com/guzzle/guzzle/blob/bf595424e4d442a190582e088985dc835a789071/build/Burgomaster.php#L128-L146
210,277
guzzle/guzzle
build/Burgomaster.php
Burgomaster.recursiveCopy
public function recursiveCopy( $sourceDir, $destDir, $extensions = array('php') ) { if (!realpath($sourceDir)) { throw new \InvalidArgumentException("$sourceDir not found"); } if (!$extensions) { throw new \InvalidArgumentException('$extensions is empty!'); } $sourceDir = realpath($sourceDir); $exts = array_fill_keys($extensions, true); $iter = new \RecursiveDirectoryIterator($sourceDir); $iter = new \RecursiveIteratorIterator($iter); $total = 0; $this->startSection('copy'); $this->debug("Starting to copy files from $sourceDir"); foreach ($iter as $file) { if (isset($exts[$file->getExtension()]) || $file->getBaseName() == 'LICENSE' ) { // Remove the source directory from the destination path $toPath = str_replace($sourceDir, '', (string) $file); $toPath = $destDir . '/' . $toPath; $toPath = str_replace('//', '/', $toPath); $this->deepCopy((string) $file, $toPath); $total++; } } $this->debug("Copied $total files from $sourceDir"); $this->endSection(); }
php
public function recursiveCopy( $sourceDir, $destDir, $extensions = array('php') ) { if (!realpath($sourceDir)) { throw new \InvalidArgumentException("$sourceDir not found"); } if (!$extensions) { throw new \InvalidArgumentException('$extensions is empty!'); } $sourceDir = realpath($sourceDir); $exts = array_fill_keys($extensions, true); $iter = new \RecursiveDirectoryIterator($sourceDir); $iter = new \RecursiveIteratorIterator($iter); $total = 0; $this->startSection('copy'); $this->debug("Starting to copy files from $sourceDir"); foreach ($iter as $file) { if (isset($exts[$file->getExtension()]) || $file->getBaseName() == 'LICENSE' ) { // Remove the source directory from the destination path $toPath = str_replace($sourceDir, '', (string) $file); $toPath = $destDir . '/' . $toPath; $toPath = str_replace('//', '/', $toPath); $this->deepCopy((string) $file, $toPath); $total++; } } $this->debug("Copied $total files from $sourceDir"); $this->endSection(); }
[ "public", "function", "recursiveCopy", "(", "$", "sourceDir", ",", "$", "destDir", ",", "$", "extensions", "=", "array", "(", "'php'", ")", ")", "{", "if", "(", "!", "realpath", "(", "$", "sourceDir", ")", ")", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "\"$sourceDir not found\"", ")", ";", "}", "if", "(", "!", "$", "extensions", ")", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "'$extensions is empty!'", ")", ";", "}", "$", "sourceDir", "=", "realpath", "(", "$", "sourceDir", ")", ";", "$", "exts", "=", "array_fill_keys", "(", "$", "extensions", ",", "true", ")", ";", "$", "iter", "=", "new", "\\", "RecursiveDirectoryIterator", "(", "$", "sourceDir", ")", ";", "$", "iter", "=", "new", "\\", "RecursiveIteratorIterator", "(", "$", "iter", ")", ";", "$", "total", "=", "0", ";", "$", "this", "->", "startSection", "(", "'copy'", ")", ";", "$", "this", "->", "debug", "(", "\"Starting to copy files from $sourceDir\"", ")", ";", "foreach", "(", "$", "iter", "as", "$", "file", ")", "{", "if", "(", "isset", "(", "$", "exts", "[", "$", "file", "->", "getExtension", "(", ")", "]", ")", "||", "$", "file", "->", "getBaseName", "(", ")", "==", "'LICENSE'", ")", "{", "// Remove the source directory from the destination path", "$", "toPath", "=", "str_replace", "(", "$", "sourceDir", ",", "''", ",", "(", "string", ")", "$", "file", ")", ";", "$", "toPath", "=", "$", "destDir", ".", "'/'", ".", "$", "toPath", ";", "$", "toPath", "=", "str_replace", "(", "'//'", ",", "'/'", ",", "$", "toPath", ")", ";", "$", "this", "->", "deepCopy", "(", "(", "string", ")", "$", "file", ",", "$", "toPath", ")", ";", "$", "total", "++", ";", "}", "}", "$", "this", "->", "debug", "(", "\"Copied $total files from $sourceDir\"", ")", ";", "$", "this", "->", "endSection", "(", ")", ";", "}" ]
Recursively copy one folder to another. Any LICENSE file is automatically copied. @param string $sourceDir Source directory to copy from @param string $destDir Directory to copy the files to that is relative to the the stage base directory. @param array $extensions File extensions to copy from the $sourceDir. Defaults to "php" files only (e.g., ['php']). @throws \InvalidArgumentException if the source directory is invalid.
[ "Recursively", "copy", "one", "folder", "to", "another", "." ]
bf595424e4d442a190582e088985dc835a789071
https://github.com/guzzle/guzzle/blob/bf595424e4d442a190582e088985dc835a789071/build/Burgomaster.php#L160-L197
210,278
guzzle/guzzle
build/Burgomaster.php
Burgomaster.exec
public function exec($command) { $this->debug("Executing: $command"); $output = $returnValue = null; exec($command, $output, $returnValue); if ($returnValue != 0) { throw new \RuntimeException('Error executing command: ' . $command . ' : ' . implode("\n", $output)); } return implode("\n", $output); }
php
public function exec($command) { $this->debug("Executing: $command"); $output = $returnValue = null; exec($command, $output, $returnValue); if ($returnValue != 0) { throw new \RuntimeException('Error executing command: ' . $command . ' : ' . implode("\n", $output)); } return implode("\n", $output); }
[ "public", "function", "exec", "(", "$", "command", ")", "{", "$", "this", "->", "debug", "(", "\"Executing: $command\"", ")", ";", "$", "output", "=", "$", "returnValue", "=", "null", ";", "exec", "(", "$", "command", ",", "$", "output", ",", "$", "returnValue", ")", ";", "if", "(", "$", "returnValue", "!=", "0", ")", "{", "throw", "new", "\\", "RuntimeException", "(", "'Error executing command: '", ".", "$", "command", ".", "' : '", ".", "implode", "(", "\"\\n\"", ",", "$", "output", ")", ")", ";", "}", "return", "implode", "(", "\"\\n\"", ",", "$", "output", ")", ";", "}" ]
Execute a command and throw an exception if the return code is not 0. @param string $command Command to execute @return string Returns the output of the command as a string @throws \RuntimeException on error.
[ "Execute", "a", "command", "and", "throw", "an", "exception", "if", "the", "return", "code", "is", "not", "0", "." ]
bf595424e4d442a190582e088985dc835a789071
https://github.com/guzzle/guzzle/blob/bf595424e4d442a190582e088985dc835a789071/build/Burgomaster.php#L207-L219
210,279
guzzle/guzzle
build/Burgomaster.php
Burgomaster.createAutoloader
public function createAutoloader($files = array(), $filename = 'autoloader.php') { $sourceDir = realpath($this->stageDir); $iter = new \RecursiveDirectoryIterator($sourceDir); $iter = new \RecursiveIteratorIterator($iter); $this->startSection('autoloader'); $this->debug('Creating classmap autoloader'); $this->debug("Collecting valid PHP files from {$this->stageDir}"); $classMap = array(); foreach ($iter as $file) { if ($file->getExtension() == 'php') { $location = str_replace($this->stageDir . '/', '', (string) $file); $className = str_replace('/', '\\', $location); $className = substr($className, 0, -4); // Remove "src\" or "lib\" if (strpos($className, 'src\\') === 0 || strpos($className, 'lib\\') === 0 ) { $className = substr($className, 4); } $classMap[$className] = "__DIR__ . '/$location'"; $this->debug("Found $className"); } } $destFile = $this->stageDir . '/' . $filename; $this->debug("Writing autoloader to {$destFile}"); if (!($h = fopen($destFile, 'w'))) { throw new \RuntimeException('Unable to open file for writing'); } $this->debug('Writing classmap files'); fwrite($h, "<?php\n\n"); fwrite($h, "\$mapping = array(\n"); foreach ($classMap as $c => $f) { fwrite($h, " '$c' => $f,\n"); } fwrite($h, ");\n\n"); fwrite($h, <<<EOT spl_autoload_register(function (\$class) use (\$mapping) { if (isset(\$mapping[\$class])) { require \$mapping[\$class]; } }, true); EOT ); fwrite($h, "\n"); $this->debug('Writing automatically included files'); foreach ($files as $file) { fwrite($h, "require __DIR__ . '/$file';\n"); } fclose($h); $this->endSection(); }
php
public function createAutoloader($files = array(), $filename = 'autoloader.php') { $sourceDir = realpath($this->stageDir); $iter = new \RecursiveDirectoryIterator($sourceDir); $iter = new \RecursiveIteratorIterator($iter); $this->startSection('autoloader'); $this->debug('Creating classmap autoloader'); $this->debug("Collecting valid PHP files from {$this->stageDir}"); $classMap = array(); foreach ($iter as $file) { if ($file->getExtension() == 'php') { $location = str_replace($this->stageDir . '/', '', (string) $file); $className = str_replace('/', '\\', $location); $className = substr($className, 0, -4); // Remove "src\" or "lib\" if (strpos($className, 'src\\') === 0 || strpos($className, 'lib\\') === 0 ) { $className = substr($className, 4); } $classMap[$className] = "__DIR__ . '/$location'"; $this->debug("Found $className"); } } $destFile = $this->stageDir . '/' . $filename; $this->debug("Writing autoloader to {$destFile}"); if (!($h = fopen($destFile, 'w'))) { throw new \RuntimeException('Unable to open file for writing'); } $this->debug('Writing classmap files'); fwrite($h, "<?php\n\n"); fwrite($h, "\$mapping = array(\n"); foreach ($classMap as $c => $f) { fwrite($h, " '$c' => $f,\n"); } fwrite($h, ");\n\n"); fwrite($h, <<<EOT spl_autoload_register(function (\$class) use (\$mapping) { if (isset(\$mapping[\$class])) { require \$mapping[\$class]; } }, true); EOT ); fwrite($h, "\n"); $this->debug('Writing automatically included files'); foreach ($files as $file) { fwrite($h, "require __DIR__ . '/$file';\n"); } fclose($h); $this->endSection(); }
[ "public", "function", "createAutoloader", "(", "$", "files", "=", "array", "(", ")", ",", "$", "filename", "=", "'autoloader.php'", ")", "{", "$", "sourceDir", "=", "realpath", "(", "$", "this", "->", "stageDir", ")", ";", "$", "iter", "=", "new", "\\", "RecursiveDirectoryIterator", "(", "$", "sourceDir", ")", ";", "$", "iter", "=", "new", "\\", "RecursiveIteratorIterator", "(", "$", "iter", ")", ";", "$", "this", "->", "startSection", "(", "'autoloader'", ")", ";", "$", "this", "->", "debug", "(", "'Creating classmap autoloader'", ")", ";", "$", "this", "->", "debug", "(", "\"Collecting valid PHP files from {$this->stageDir}\"", ")", ";", "$", "classMap", "=", "array", "(", ")", ";", "foreach", "(", "$", "iter", "as", "$", "file", ")", "{", "if", "(", "$", "file", "->", "getExtension", "(", ")", "==", "'php'", ")", "{", "$", "location", "=", "str_replace", "(", "$", "this", "->", "stageDir", ".", "'/'", ",", "''", ",", "(", "string", ")", "$", "file", ")", ";", "$", "className", "=", "str_replace", "(", "'/'", ",", "'\\\\'", ",", "$", "location", ")", ";", "$", "className", "=", "substr", "(", "$", "className", ",", "0", ",", "-", "4", ")", ";", "// Remove \"src\\\" or \"lib\\\"", "if", "(", "strpos", "(", "$", "className", ",", "'src\\\\'", ")", "===", "0", "||", "strpos", "(", "$", "className", ",", "'lib\\\\'", ")", "===", "0", ")", "{", "$", "className", "=", "substr", "(", "$", "className", ",", "4", ")", ";", "}", "$", "classMap", "[", "$", "className", "]", "=", "\"__DIR__ . '/$location'\"", ";", "$", "this", "->", "debug", "(", "\"Found $className\"", ")", ";", "}", "}", "$", "destFile", "=", "$", "this", "->", "stageDir", ".", "'/'", ".", "$", "filename", ";", "$", "this", "->", "debug", "(", "\"Writing autoloader to {$destFile}\"", ")", ";", "if", "(", "!", "(", "$", "h", "=", "fopen", "(", "$", "destFile", ",", "'w'", ")", ")", ")", "{", "throw", "new", "\\", "RuntimeException", "(", "'Unable to open file for writing'", ")", ";", "}", "$", "this", "->", "debug", "(", "'Writing classmap files'", ")", ";", "fwrite", "(", "$", "h", ",", "\"<?php\\n\\n\"", ")", ";", "fwrite", "(", "$", "h", ",", "\"\\$mapping = array(\\n\"", ")", ";", "foreach", "(", "$", "classMap", "as", "$", "c", "=>", "$", "f", ")", "{", "fwrite", "(", "$", "h", ",", "\" '$c' => $f,\\n\"", ")", ";", "}", "fwrite", "(", "$", "h", ",", "\");\\n\\n\"", ")", ";", "fwrite", "(", "$", "h", ",", " <<<EOT\nspl_autoload_register(function (\\$class) use (\\$mapping) {\n if (isset(\\$mapping[\\$class])) {\n require \\$mapping[\\$class];\n }\n}, true);\n\nEOT", ")", ";", "fwrite", "(", "$", "h", ",", "\"\\n\"", ")", ";", "$", "this", "->", "debug", "(", "'Writing automatically included files'", ")", ";", "foreach", "(", "$", "files", "as", "$", "file", ")", "{", "fwrite", "(", "$", "h", ",", "\"require __DIR__ . '/$file';\\n\"", ")", ";", "}", "fclose", "(", "$", "h", ")", ";", "$", "this", "->", "endSection", "(", ")", ";", "}" ]
Creates a class-map autoloader to the staging directory in a file named autoloader.php @param array $files Files to explicitly require in the autoloader. This is similar to Composer's "files" "autoload" section. @param string $filename Name of the autoloader file. @throws \RuntimeException if the file cannot be written
[ "Creates", "a", "class", "-", "map", "autoloader", "to", "the", "staging", "directory", "in", "a", "file", "named", "autoloader", ".", "php" ]
bf595424e4d442a190582e088985dc835a789071
https://github.com/guzzle/guzzle/blob/bf595424e4d442a190582e088985dc835a789071/build/Burgomaster.php#L230-L293
210,280
guzzle/guzzle
build/Burgomaster.php
Burgomaster.createStub
private function createStub($dest, $autoloaderFilename = 'autoloader.php') { $this->startSection('stub'); $this->debug("Creating phar stub at $dest"); $alias = basename($dest); $constName = str_replace('.phar', '', strtoupper($alias)) . '_PHAR'; $stub = "<?php\n"; $stub .= "define('$constName', true);\n"; $stub .= "require 'phar://$alias/{$autoloaderFilename}';\n"; $stub .= "__HALT_COMPILER();\n"; $this->endSection(); return $stub; }
php
private function createStub($dest, $autoloaderFilename = 'autoloader.php') { $this->startSection('stub'); $this->debug("Creating phar stub at $dest"); $alias = basename($dest); $constName = str_replace('.phar', '', strtoupper($alias)) . '_PHAR'; $stub = "<?php\n"; $stub .= "define('$constName', true);\n"; $stub .= "require 'phar://$alias/{$autoloaderFilename}';\n"; $stub .= "__HALT_COMPILER();\n"; $this->endSection(); return $stub; }
[ "private", "function", "createStub", "(", "$", "dest", ",", "$", "autoloaderFilename", "=", "'autoloader.php'", ")", "{", "$", "this", "->", "startSection", "(", "'stub'", ")", ";", "$", "this", "->", "debug", "(", "\"Creating phar stub at $dest\"", ")", ";", "$", "alias", "=", "basename", "(", "$", "dest", ")", ";", "$", "constName", "=", "str_replace", "(", "'.phar'", ",", "''", ",", "strtoupper", "(", "$", "alias", ")", ")", ".", "'_PHAR'", ";", "$", "stub", "=", "\"<?php\\n\"", ";", "$", "stub", ".=", "\"define('$constName', true);\\n\"", ";", "$", "stub", ".=", "\"require 'phar://$alias/{$autoloaderFilename}';\\n\"", ";", "$", "stub", ".=", "\"__HALT_COMPILER();\\n\"", ";", "$", "this", "->", "endSection", "(", ")", ";", "return", "$", "stub", ";", "}" ]
Creates a default stub for the phar that includeds the generated autoloader. This phar also registers a constant that can be used to check if you are running the phar. The constant is the basename of the $dest variable without the extension, with "_PHAR" appended, then converted to all caps (e.g., "/foo/guzzle.phar" gets a contant defined as GUZZLE_PHAR. @param $dest @param string $autoloaderFilename Name of the autoloader file. @return string
[ "Creates", "a", "default", "stub", "for", "the", "phar", "that", "includeds", "the", "generated", "autoloader", "." ]
bf595424e4d442a190582e088985dc835a789071
https://github.com/guzzle/guzzle/blob/bf595424e4d442a190582e088985dc835a789071/build/Burgomaster.php#L309-L323
210,281
guzzle/guzzle
build/Burgomaster.php
Burgomaster.createPhar
public function createPhar( $dest, $stub = null, $autoloaderFilename = 'autoloader.php' ) { $this->startSection('phar'); $this->debug("Creating phar file at $dest"); $this->createDirIfNeeded(dirname($dest)); $phar = new \Phar($dest, 0, basename($dest)); $phar->buildFromDirectory($this->stageDir); if ($stub !== false) { if (!$stub) { $stub = $this->createStub($dest, $autoloaderFilename); } $phar->setStub($stub); } $this->debug("Created phar at $dest"); $this->endSection(); }
php
public function createPhar( $dest, $stub = null, $autoloaderFilename = 'autoloader.php' ) { $this->startSection('phar'); $this->debug("Creating phar file at $dest"); $this->createDirIfNeeded(dirname($dest)); $phar = new \Phar($dest, 0, basename($dest)); $phar->buildFromDirectory($this->stageDir); if ($stub !== false) { if (!$stub) { $stub = $this->createStub($dest, $autoloaderFilename); } $phar->setStub($stub); } $this->debug("Created phar at $dest"); $this->endSection(); }
[ "public", "function", "createPhar", "(", "$", "dest", ",", "$", "stub", "=", "null", ",", "$", "autoloaderFilename", "=", "'autoloader.php'", ")", "{", "$", "this", "->", "startSection", "(", "'phar'", ")", ";", "$", "this", "->", "debug", "(", "\"Creating phar file at $dest\"", ")", ";", "$", "this", "->", "createDirIfNeeded", "(", "dirname", "(", "$", "dest", ")", ")", ";", "$", "phar", "=", "new", "\\", "Phar", "(", "$", "dest", ",", "0", ",", "basename", "(", "$", "dest", ")", ")", ";", "$", "phar", "->", "buildFromDirectory", "(", "$", "this", "->", "stageDir", ")", ";", "if", "(", "$", "stub", "!==", "false", ")", "{", "if", "(", "!", "$", "stub", ")", "{", "$", "stub", "=", "$", "this", "->", "createStub", "(", "$", "dest", ",", "$", "autoloaderFilename", ")", ";", "}", "$", "phar", "->", "setStub", "(", "$", "stub", ")", ";", "}", "$", "this", "->", "debug", "(", "\"Created phar at $dest\"", ")", ";", "$", "this", "->", "endSection", "(", ")", ";", "}" ]
Creates a phar that automatically registers an autoloader. Call this only after your staging directory is built. @param string $dest Where to save the file. The basename of the file is also used as the alias name in the phar (e.g., /path/to/guzzle.phar => guzzle.phar). @param string|bool|null $stub The path to the phar stub file. Pass or leave null to automatically have one created for you. Pass false to no use a stub in the generated phar. @param string $autoloaderFilename Name of the autolaoder filename.
[ "Creates", "a", "phar", "that", "automatically", "registers", "an", "autoloader", "." ]
bf595424e4d442a190582e088985dc835a789071
https://github.com/guzzle/guzzle/blob/bf595424e4d442a190582e088985dc835a789071/build/Burgomaster.php#L338-L358
210,282
guzzle/guzzle
build/Burgomaster.php
Burgomaster.createZip
public function createZip($dest) { $this->startSection('zip'); $this->debug("Creating a zip file at $dest"); $this->createDirIfNeeded(dirname($dest)); chdir($this->stageDir); $this->exec("zip -r $dest ./"); $this->debug(" > Created at $dest"); chdir(__DIR__); $this->endSection(); }
php
public function createZip($dest) { $this->startSection('zip'); $this->debug("Creating a zip file at $dest"); $this->createDirIfNeeded(dirname($dest)); chdir($this->stageDir); $this->exec("zip -r $dest ./"); $this->debug(" > Created at $dest"); chdir(__DIR__); $this->endSection(); }
[ "public", "function", "createZip", "(", "$", "dest", ")", "{", "$", "this", "->", "startSection", "(", "'zip'", ")", ";", "$", "this", "->", "debug", "(", "\"Creating a zip file at $dest\"", ")", ";", "$", "this", "->", "createDirIfNeeded", "(", "dirname", "(", "$", "dest", ")", ")", ";", "chdir", "(", "$", "this", "->", "stageDir", ")", ";", "$", "this", "->", "exec", "(", "\"zip -r $dest ./\"", ")", ";", "$", "this", "->", "debug", "(", "\" > Created at $dest\"", ")", ";", "chdir", "(", "__DIR__", ")", ";", "$", "this", "->", "endSection", "(", ")", ";", "}" ]
Creates a zip file containing the staged files of your project. Call this only after your staging directory is built. @param string $dest Where to save the zip file
[ "Creates", "a", "zip", "file", "containing", "the", "staged", "files", "of", "your", "project", "." ]
bf595424e4d442a190582e088985dc835a789071
https://github.com/guzzle/guzzle/blob/bf595424e4d442a190582e088985dc835a789071/build/Burgomaster.php#L367-L377
210,283
guzzle/guzzle
src/Handler/CurlFactory.php
CurlFactory.finish
public static function finish( callable $handler, EasyHandle $easy, CurlFactoryInterface $factory ) { if (isset($easy->options['on_stats'])) { self::invokeStats($easy); } if (!$easy->response || $easy->errno) { return self::finishError($handler, $easy, $factory); } // Return the response if it is present and there is no error. $factory->release($easy); // Rewind the body of the response if possible. $body = $easy->response->getBody(); if ($body->isSeekable()) { $body->rewind(); } return new FulfilledPromise($easy->response); }
php
public static function finish( callable $handler, EasyHandle $easy, CurlFactoryInterface $factory ) { if (isset($easy->options['on_stats'])) { self::invokeStats($easy); } if (!$easy->response || $easy->errno) { return self::finishError($handler, $easy, $factory); } // Return the response if it is present and there is no error. $factory->release($easy); // Rewind the body of the response if possible. $body = $easy->response->getBody(); if ($body->isSeekable()) { $body->rewind(); } return new FulfilledPromise($easy->response); }
[ "public", "static", "function", "finish", "(", "callable", "$", "handler", ",", "EasyHandle", "$", "easy", ",", "CurlFactoryInterface", "$", "factory", ")", "{", "if", "(", "isset", "(", "$", "easy", "->", "options", "[", "'on_stats'", "]", ")", ")", "{", "self", "::", "invokeStats", "(", "$", "easy", ")", ";", "}", "if", "(", "!", "$", "easy", "->", "response", "||", "$", "easy", "->", "errno", ")", "{", "return", "self", "::", "finishError", "(", "$", "handler", ",", "$", "easy", ",", "$", "factory", ")", ";", "}", "// Return the response if it is present and there is no error.", "$", "factory", "->", "release", "(", "$", "easy", ")", ";", "// Rewind the body of the response if possible.", "$", "body", "=", "$", "easy", "->", "response", "->", "getBody", "(", ")", ";", "if", "(", "$", "body", "->", "isSeekable", "(", ")", ")", "{", "$", "body", "->", "rewind", "(", ")", ";", "}", "return", "new", "FulfilledPromise", "(", "$", "easy", "->", "response", ")", ";", "}" ]
Completes a cURL transaction, either returning a response promise or a rejected promise. @param callable $handler @param EasyHandle $easy @param CurlFactoryInterface $factory Dictates how the handle is released @return \GuzzleHttp\Promise\PromiseInterface
[ "Completes", "a", "cURL", "transaction", "either", "returning", "a", "response", "promise", "or", "a", "rejected", "promise", "." ]
bf595424e4d442a190582e088985dc835a789071
https://github.com/guzzle/guzzle/blob/bf595424e4d442a190582e088985dc835a789071/src/Handler/CurlFactory.php#L95-L118
210,284
guzzle/guzzle
src/Handler/CurlFactory.php
CurlFactory.removeHeader
private function removeHeader($name, array &$options) { foreach (array_keys($options['_headers']) as $key) { if (!strcasecmp($key, $name)) { unset($options['_headers'][$key]); return; } } }
php
private function removeHeader($name, array &$options) { foreach (array_keys($options['_headers']) as $key) { if (!strcasecmp($key, $name)) { unset($options['_headers'][$key]); return; } } }
[ "private", "function", "removeHeader", "(", "$", "name", ",", "array", "&", "$", "options", ")", "{", "foreach", "(", "array_keys", "(", "$", "options", "[", "'_headers'", "]", ")", "as", "$", "key", ")", "{", "if", "(", "!", "strcasecmp", "(", "$", "key", ",", "$", "name", ")", ")", "{", "unset", "(", "$", "options", "[", "'_headers'", "]", "[", "$", "key", "]", ")", ";", "return", ";", "}", "}", "}" ]
Remove a header from the options array. @param string $name Case-insensitive header to remove @param array $options Array of options to modify
[ "Remove", "a", "header", "from", "the", "options", "array", "." ]
bf595424e4d442a190582e088985dc835a789071
https://github.com/guzzle/guzzle/blob/bf595424e4d442a190582e088985dc835a789071/src/Handler/CurlFactory.php#L328-L336
210,285
guzzle/guzzle
src/Handler/CurlMultiHandler.php
CurlMultiHandler.tick
public function tick() { // Add any delayed handles if needed. if ($this->delays) { $currentTime = \GuzzleHttp\_current_time(); foreach ($this->delays as $id => $delay) { if ($currentTime >= $delay) { unset($this->delays[$id]); curl_multi_add_handle( $this->_mh, $this->handles[$id]['easy']->handle ); } } } // Step through the task queue which may add additional requests. P\queue()->run(); if ($this->active && curl_multi_select($this->_mh, $this->selectTimeout) === -1 ) { // Perform a usleep if a select returns -1. // See: https://bugs.php.net/bug.php?id=61141 usleep(250); } while (curl_multi_exec($this->_mh, $this->active) === CURLM_CALL_MULTI_PERFORM); $this->processMessages(); }
php
public function tick() { // Add any delayed handles if needed. if ($this->delays) { $currentTime = \GuzzleHttp\_current_time(); foreach ($this->delays as $id => $delay) { if ($currentTime >= $delay) { unset($this->delays[$id]); curl_multi_add_handle( $this->_mh, $this->handles[$id]['easy']->handle ); } } } // Step through the task queue which may add additional requests. P\queue()->run(); if ($this->active && curl_multi_select($this->_mh, $this->selectTimeout) === -1 ) { // Perform a usleep if a select returns -1. // See: https://bugs.php.net/bug.php?id=61141 usleep(250); } while (curl_multi_exec($this->_mh, $this->active) === CURLM_CALL_MULTI_PERFORM); $this->processMessages(); }
[ "public", "function", "tick", "(", ")", "{", "// Add any delayed handles if needed.", "if", "(", "$", "this", "->", "delays", ")", "{", "$", "currentTime", "=", "\\", "GuzzleHttp", "\\", "_current_time", "(", ")", ";", "foreach", "(", "$", "this", "->", "delays", "as", "$", "id", "=>", "$", "delay", ")", "{", "if", "(", "$", "currentTime", ">=", "$", "delay", ")", "{", "unset", "(", "$", "this", "->", "delays", "[", "$", "id", "]", ")", ";", "curl_multi_add_handle", "(", "$", "this", "->", "_mh", ",", "$", "this", "->", "handles", "[", "$", "id", "]", "[", "'easy'", "]", "->", "handle", ")", ";", "}", "}", "}", "// Step through the task queue which may add additional requests.", "P", "\\", "queue", "(", ")", "->", "run", "(", ")", ";", "if", "(", "$", "this", "->", "active", "&&", "curl_multi_select", "(", "$", "this", "->", "_mh", ",", "$", "this", "->", "selectTimeout", ")", "===", "-", "1", ")", "{", "// Perform a usleep if a select returns -1.", "// See: https://bugs.php.net/bug.php?id=61141", "usleep", "(", "250", ")", ";", "}", "while", "(", "curl_multi_exec", "(", "$", "this", "->", "_mh", ",", "$", "this", "->", "active", ")", "===", "CURLM_CALL_MULTI_PERFORM", ")", ";", "$", "this", "->", "processMessages", "(", ")", ";", "}" ]
Ticks the curl event loop.
[ "Ticks", "the", "curl", "event", "loop", "." ]
bf595424e4d442a190582e088985dc835a789071
https://github.com/guzzle/guzzle/blob/bf595424e4d442a190582e088985dc835a789071/src/Handler/CurlMultiHandler.php#L87-L117
210,286
guzzle/guzzle
src/Handler/CurlMultiHandler.php
CurlMultiHandler.cancel
private function cancel($id) { // Cannot cancel if it has been processed. if (!isset($this->handles[$id])) { return false; } $handle = $this->handles[$id]['easy']->handle; unset($this->delays[$id], $this->handles[$id]); curl_multi_remove_handle($this->_mh, $handle); curl_close($handle); return true; }
php
private function cancel($id) { // Cannot cancel if it has been processed. if (!isset($this->handles[$id])) { return false; } $handle = $this->handles[$id]['easy']->handle; unset($this->delays[$id], $this->handles[$id]); curl_multi_remove_handle($this->_mh, $handle); curl_close($handle); return true; }
[ "private", "function", "cancel", "(", "$", "id", ")", "{", "// Cannot cancel if it has been processed.", "if", "(", "!", "isset", "(", "$", "this", "->", "handles", "[", "$", "id", "]", ")", ")", "{", "return", "false", ";", "}", "$", "handle", "=", "$", "this", "->", "handles", "[", "$", "id", "]", "[", "'easy'", "]", "->", "handle", ";", "unset", "(", "$", "this", "->", "delays", "[", "$", "id", "]", ",", "$", "this", "->", "handles", "[", "$", "id", "]", ")", ";", "curl_multi_remove_handle", "(", "$", "this", "->", "_mh", ",", "$", "handle", ")", ";", "curl_close", "(", "$", "handle", ")", ";", "return", "true", ";", "}" ]
Cancels a handle from sending and removes references to it. @param int $id Handle ID to cancel and remove. @return bool True on success, false on failure.
[ "Cancels", "a", "handle", "from", "sending", "and", "removes", "references", "to", "it", "." ]
bf595424e4d442a190582e088985dc835a789071
https://github.com/guzzle/guzzle/blob/bf595424e4d442a190582e088985dc835a789071/src/Handler/CurlMultiHandler.php#L154-L167
210,287
guzzle/guzzle
src/Cookie/CookieJar.php
CookieJar.fromArray
public static function fromArray(array $cookies, $domain) { $cookieJar = new self(); foreach ($cookies as $name => $value) { $cookieJar->setCookie(new SetCookie([ 'Domain' => $domain, 'Name' => $name, 'Value' => $value, 'Discard' => true ])); } return $cookieJar; }
php
public static function fromArray(array $cookies, $domain) { $cookieJar = new self(); foreach ($cookies as $name => $value) { $cookieJar->setCookie(new SetCookie([ 'Domain' => $domain, 'Name' => $name, 'Value' => $value, 'Discard' => true ])); } return $cookieJar; }
[ "public", "static", "function", "fromArray", "(", "array", "$", "cookies", ",", "$", "domain", ")", "{", "$", "cookieJar", "=", "new", "self", "(", ")", ";", "foreach", "(", "$", "cookies", "as", "$", "name", "=>", "$", "value", ")", "{", "$", "cookieJar", "->", "setCookie", "(", "new", "SetCookie", "(", "[", "'Domain'", "=>", "$", "domain", ",", "'Name'", "=>", "$", "name", ",", "'Value'", "=>", "$", "value", ",", "'Discard'", "=>", "true", "]", ")", ")", ";", "}", "return", "$", "cookieJar", ";", "}" ]
Create a new Cookie jar from an associative array and domain. @param array $cookies Cookies to create the jar from @param string $domain Domain to set the cookies to @return self
[ "Create", "a", "new", "Cookie", "jar", "from", "an", "associative", "array", "and", "domain", "." ]
bf595424e4d442a190582e088985dc835a789071
https://github.com/guzzle/guzzle/blob/bf595424e4d442a190582e088985dc835a789071/src/Cookie/CookieJar.php#L45-L58
210,288
guzzle/guzzle
src/Cookie/CookieJar.php
CookieJar.getCookieByName
public function getCookieByName($name) { // don't allow a null name if ($name === null) { return null; } foreach ($this->cookies as $cookie) { if ($cookie->getName() !== null && strcasecmp($cookie->getName(), $name) === 0) { return $cookie; } } }
php
public function getCookieByName($name) { // don't allow a null name if ($name === null) { return null; } foreach ($this->cookies as $cookie) { if ($cookie->getName() !== null && strcasecmp($cookie->getName(), $name) === 0) { return $cookie; } } }
[ "public", "function", "getCookieByName", "(", "$", "name", ")", "{", "// don't allow a null name", "if", "(", "$", "name", "===", "null", ")", "{", "return", "null", ";", "}", "foreach", "(", "$", "this", "->", "cookies", "as", "$", "cookie", ")", "{", "if", "(", "$", "cookie", "->", "getName", "(", ")", "!==", "null", "&&", "strcasecmp", "(", "$", "cookie", "->", "getName", "(", ")", ",", "$", "name", ")", "===", "0", ")", "{", "return", "$", "cookie", ";", "}", "}", "}" ]
Finds and returns the cookie based on the name @param string $name cookie name to search for @return SetCookie|null cookie that was found or null if not found
[ "Finds", "and", "returns", "the", "cookie", "based", "on", "the", "name" ]
bf595424e4d442a190582e088985dc835a789071
https://github.com/guzzle/guzzle/blob/bf595424e4d442a190582e088985dc835a789071/src/Cookie/CookieJar.php#L95-L106
210,289
guzzle/guzzle
src/Exception/RequestException.php
RequestException.obfuscateUri
private static function obfuscateUri($uri) { $userInfo = $uri->getUserInfo(); if (false !== ($pos = strpos($userInfo, ':'))) { return $uri->withUserInfo(substr($userInfo, 0, $pos), '***'); } return $uri; }
php
private static function obfuscateUri($uri) { $userInfo = $uri->getUserInfo(); if (false !== ($pos = strpos($userInfo, ':'))) { return $uri->withUserInfo(substr($userInfo, 0, $pos), '***'); } return $uri; }
[ "private", "static", "function", "obfuscateUri", "(", "$", "uri", ")", "{", "$", "userInfo", "=", "$", "uri", "->", "getUserInfo", "(", ")", ";", "if", "(", "false", "!==", "(", "$", "pos", "=", "strpos", "(", "$", "userInfo", ",", "':'", ")", ")", ")", "{", "return", "$", "uri", "->", "withUserInfo", "(", "substr", "(", "$", "userInfo", ",", "0", ",", "$", "pos", ")", ",", "'***'", ")", ";", "}", "return", "$", "uri", ";", "}" ]
Obfuscates URI if there is an username and a password present @param UriInterface $uri @return UriInterface
[ "Obfuscates", "URI", "if", "there", "is", "an", "username", "and", "a", "password", "present" ]
bf595424e4d442a190582e088985dc835a789071
https://github.com/guzzle/guzzle/blob/bf595424e4d442a190582e088985dc835a789071/src/Exception/RequestException.php#L162-L171
210,290
guzzle/guzzle
src/Cookie/SessionCookieJar.php
SessionCookieJar.load
protected function load() { if (!isset($_SESSION[$this->sessionKey])) { return; } $data = json_decode($_SESSION[$this->sessionKey], true); if (is_array($data)) { foreach ($data as $cookie) { $this->setCookie(new SetCookie($cookie)); } } elseif (strlen($data)) { throw new \RuntimeException("Invalid cookie data"); } }
php
protected function load() { if (!isset($_SESSION[$this->sessionKey])) { return; } $data = json_decode($_SESSION[$this->sessionKey], true); if (is_array($data)) { foreach ($data as $cookie) { $this->setCookie(new SetCookie($cookie)); } } elseif (strlen($data)) { throw new \RuntimeException("Invalid cookie data"); } }
[ "protected", "function", "load", "(", ")", "{", "if", "(", "!", "isset", "(", "$", "_SESSION", "[", "$", "this", "->", "sessionKey", "]", ")", ")", "{", "return", ";", "}", "$", "data", "=", "json_decode", "(", "$", "_SESSION", "[", "$", "this", "->", "sessionKey", "]", ",", "true", ")", ";", "if", "(", "is_array", "(", "$", "data", ")", ")", "{", "foreach", "(", "$", "data", "as", "$", "cookie", ")", "{", "$", "this", "->", "setCookie", "(", "new", "SetCookie", "(", "$", "cookie", ")", ")", ";", "}", "}", "elseif", "(", "strlen", "(", "$", "data", ")", ")", "{", "throw", "new", "\\", "RuntimeException", "(", "\"Invalid cookie data\"", ")", ";", "}", "}" ]
Load the contents of the client session into the data array
[ "Load", "the", "contents", "of", "the", "client", "session", "into", "the", "data", "array" ]
bf595424e4d442a190582e088985dc835a789071
https://github.com/guzzle/guzzle/blob/bf595424e4d442a190582e088985dc835a789071/src/Cookie/SessionCookieJar.php#L57-L70
210,291
barryvdh/laravel-debugbar
src/Controllers/OpenHandlerController.php
OpenHandlerController.clockwork
public function clockwork($id) { $request = [ 'op' => 'get', 'id' => $id, ]; $openHandler = new OpenHandler($this->debugbar); $data = $openHandler->handle($request, false, false); // Convert to Clockwork $converter = new Converter(); $output = $converter->convert(json_decode($data, true)); return response()->json($output); }
php
public function clockwork($id) { $request = [ 'op' => 'get', 'id' => $id, ]; $openHandler = new OpenHandler($this->debugbar); $data = $openHandler->handle($request, false, false); // Convert to Clockwork $converter = new Converter(); $output = $converter->convert(json_decode($data, true)); return response()->json($output); }
[ "public", "function", "clockwork", "(", "$", "id", ")", "{", "$", "request", "=", "[", "'op'", "=>", "'get'", ",", "'id'", "=>", "$", "id", ",", "]", ";", "$", "openHandler", "=", "new", "OpenHandler", "(", "$", "this", "->", "debugbar", ")", ";", "$", "data", "=", "$", "openHandler", "->", "handle", "(", "$", "request", ",", "false", ",", "false", ")", ";", "// Convert to Clockwork", "$", "converter", "=", "new", "Converter", "(", ")", ";", "$", "output", "=", "$", "converter", "->", "convert", "(", "json_decode", "(", "$", "data", ",", "true", ")", ")", ";", "return", "response", "(", ")", "->", "json", "(", "$", "output", ")", ";", "}" ]
Return Clockwork output @param $id @return mixed @throws \DebugBar\DebugBarException
[ "Return", "Clockwork", "output" ]
2d195779ea4f809f69764a795e2ec371dbb76a96
https://github.com/barryvdh/laravel-debugbar/blob/2d195779ea4f809f69764a795e2ec371dbb76a96/src/Controllers/OpenHandlerController.php#L29-L44
210,292
barryvdh/laravel-debugbar
src/Controllers/CacheController.php
CacheController.delete
public function delete($key, $tags = '') { $cache = app('cache'); if (!empty($tags)) { $tags = json_decode($tags, true); $cache = $cache->tags($tags); } else { unset($tags); } $success = $cache->forget($key); return response()->json(compact('success')); }
php
public function delete($key, $tags = '') { $cache = app('cache'); if (!empty($tags)) { $tags = json_decode($tags, true); $cache = $cache->tags($tags); } else { unset($tags); } $success = $cache->forget($key); return response()->json(compact('success')); }
[ "public", "function", "delete", "(", "$", "key", ",", "$", "tags", "=", "''", ")", "{", "$", "cache", "=", "app", "(", "'cache'", ")", ";", "if", "(", "!", "empty", "(", "$", "tags", ")", ")", "{", "$", "tags", "=", "json_decode", "(", "$", "tags", ",", "true", ")", ";", "$", "cache", "=", "$", "cache", "->", "tags", "(", "$", "tags", ")", ";", "}", "else", "{", "unset", "(", "$", "tags", ")", ";", "}", "$", "success", "=", "$", "cache", "->", "forget", "(", "$", "key", ")", ";", "return", "response", "(", ")", "->", "json", "(", "compact", "(", "'success'", ")", ")", ";", "}" ]
Forget a cache key
[ "Forget", "a", "cache", "key" ]
2d195779ea4f809f69764a795e2ec371dbb76a96
https://github.com/barryvdh/laravel-debugbar/blob/2d195779ea4f809f69764a795e2ec371dbb76a96/src/Controllers/CacheController.php#L11-L25
210,293
barryvdh/laravel-debugbar
src/DataCollector/QueryCollector.php
QueryCollector.fileIsInExcludedPath
protected function fileIsInExcludedPath($file) { $excludedPaths = [ '/vendor/laravel/framework/src/Illuminate/Database', '/vendor/laravel/framework/src/Illuminate/Events', '/vendor/barryvdh/laravel-debugbar', ]; $normalizedPath = str_replace('\\', '/', $file); foreach ($excludedPaths as $excludedPath) { if (strpos($normalizedPath, $excludedPath) !== false) { return true; } } return false; }
php
protected function fileIsInExcludedPath($file) { $excludedPaths = [ '/vendor/laravel/framework/src/Illuminate/Database', '/vendor/laravel/framework/src/Illuminate/Events', '/vendor/barryvdh/laravel-debugbar', ]; $normalizedPath = str_replace('\\', '/', $file); foreach ($excludedPaths as $excludedPath) { if (strpos($normalizedPath, $excludedPath) !== false) { return true; } } return false; }
[ "protected", "function", "fileIsInExcludedPath", "(", "$", "file", ")", "{", "$", "excludedPaths", "=", "[", "'/vendor/laravel/framework/src/Illuminate/Database'", ",", "'/vendor/laravel/framework/src/Illuminate/Events'", ",", "'/vendor/barryvdh/laravel-debugbar'", ",", "]", ";", "$", "normalizedPath", "=", "str_replace", "(", "'\\\\'", ",", "'/'", ",", "$", "file", ")", ";", "foreach", "(", "$", "excludedPaths", "as", "$", "excludedPath", ")", "{", "if", "(", "strpos", "(", "$", "normalizedPath", ",", "$", "excludedPath", ")", "!==", "false", ")", "{", "return", "true", ";", "}", "}", "return", "false", ";", "}" ]
Check if the given file is to be excluded from analysis @param string $file @return bool
[ "Check", "if", "the", "given", "file", "is", "to", "be", "excluded", "from", "analysis" ]
2d195779ea4f809f69764a795e2ec371dbb76a96
https://github.com/barryvdh/laravel-debugbar/blob/2d195779ea4f809f69764a795e2ec371dbb76a96/src/DataCollector/QueryCollector.php#L273-L290
210,294
barryvdh/laravel-debugbar
src/DataCollector/QueryCollector.php
QueryCollector.findMiddlewareFromFile
protected function findMiddlewareFromFile($file) { $filename = pathinfo($file, PATHINFO_FILENAME); foreach ($this->middleware as $alias => $class) { if (strpos($class, $filename) !== false) { return $alias; } } }
php
protected function findMiddlewareFromFile($file) { $filename = pathinfo($file, PATHINFO_FILENAME); foreach ($this->middleware as $alias => $class) { if (strpos($class, $filename) !== false) { return $alias; } } }
[ "protected", "function", "findMiddlewareFromFile", "(", "$", "file", ")", "{", "$", "filename", "=", "pathinfo", "(", "$", "file", ",", "PATHINFO_FILENAME", ")", ";", "foreach", "(", "$", "this", "->", "middleware", "as", "$", "alias", "=>", "$", "class", ")", "{", "if", "(", "strpos", "(", "$", "class", ",", "$", "filename", ")", "!==", "false", ")", "{", "return", "$", "alias", ";", "}", "}", "}" ]
Find the middleware alias from the file. @param string $file @return string|null
[ "Find", "the", "middleware", "alias", "from", "the", "file", "." ]
2d195779ea4f809f69764a795e2ec371dbb76a96
https://github.com/barryvdh/laravel-debugbar/blob/2d195779ea4f809f69764a795e2ec371dbb76a96/src/DataCollector/QueryCollector.php#L298-L307
210,295
barryvdh/laravel-debugbar
src/DataCollector/QueryCollector.php
QueryCollector.findViewFromHash
protected function findViewFromHash($hash) { $finder = app('view')->getFinder(); if (isset($this->reflection['viewfinderViews'])) { $property = $this->reflection['viewfinderViews']; } else { $reflection = new \ReflectionClass($finder); $property = $reflection->getProperty('views'); $property->setAccessible(true); $this->reflection['viewfinderViews'] = $property; } foreach ($property->getValue($finder) as $name => $path){ if (sha1($path) == $hash || md5($path) == $hash) { return $name; } } }
php
protected function findViewFromHash($hash) { $finder = app('view')->getFinder(); if (isset($this->reflection['viewfinderViews'])) { $property = $this->reflection['viewfinderViews']; } else { $reflection = new \ReflectionClass($finder); $property = $reflection->getProperty('views'); $property->setAccessible(true); $this->reflection['viewfinderViews'] = $property; } foreach ($property->getValue($finder) as $name => $path){ if (sha1($path) == $hash || md5($path) == $hash) { return $name; } } }
[ "protected", "function", "findViewFromHash", "(", "$", "hash", ")", "{", "$", "finder", "=", "app", "(", "'view'", ")", "->", "getFinder", "(", ")", ";", "if", "(", "isset", "(", "$", "this", "->", "reflection", "[", "'viewfinderViews'", "]", ")", ")", "{", "$", "property", "=", "$", "this", "->", "reflection", "[", "'viewfinderViews'", "]", ";", "}", "else", "{", "$", "reflection", "=", "new", "\\", "ReflectionClass", "(", "$", "finder", ")", ";", "$", "property", "=", "$", "reflection", "->", "getProperty", "(", "'views'", ")", ";", "$", "property", "->", "setAccessible", "(", "true", ")", ";", "$", "this", "->", "reflection", "[", "'viewfinderViews'", "]", "=", "$", "property", ";", "}", "foreach", "(", "$", "property", "->", "getValue", "(", "$", "finder", ")", "as", "$", "name", "=>", "$", "path", ")", "{", "if", "(", "sha1", "(", "$", "path", ")", "==", "$", "hash", "||", "md5", "(", "$", "path", ")", "==", "$", "hash", ")", "{", "return", "$", "name", ";", "}", "}", "}" ]
Find the template name from the hash. @param string $hash @return null|string
[ "Find", "the", "template", "name", "from", "the", "hash", "." ]
2d195779ea4f809f69764a795e2ec371dbb76a96
https://github.com/barryvdh/laravel-debugbar/blob/2d195779ea4f809f69764a795e2ec371dbb76a96/src/DataCollector/QueryCollector.php#L315-L333
210,296
barryvdh/laravel-debugbar
src/DataCollector/QueryCollector.php
QueryCollector.collectTransactionEvent
public function collectTransactionEvent($event, $connection) { $source = []; if ($this->findSource) { try { $source = $this->findSource(); } catch (\Exception $e) { } } $this->queries[] = [ 'query' => $event, 'type' => 'transaction', 'bindings' => [], 'time' => 0, 'source' => $source, 'explain' => [], 'connection' => $connection->getDatabaseName(), 'hints' => null, ]; }
php
public function collectTransactionEvent($event, $connection) { $source = []; if ($this->findSource) { try { $source = $this->findSource(); } catch (\Exception $e) { } } $this->queries[] = [ 'query' => $event, 'type' => 'transaction', 'bindings' => [], 'time' => 0, 'source' => $source, 'explain' => [], 'connection' => $connection->getDatabaseName(), 'hints' => null, ]; }
[ "public", "function", "collectTransactionEvent", "(", "$", "event", ",", "$", "connection", ")", "{", "$", "source", "=", "[", "]", ";", "if", "(", "$", "this", "->", "findSource", ")", "{", "try", "{", "$", "source", "=", "$", "this", "->", "findSource", "(", ")", ";", "}", "catch", "(", "\\", "Exception", "$", "e", ")", "{", "}", "}", "$", "this", "->", "queries", "[", "]", "=", "[", "'query'", "=>", "$", "event", ",", "'type'", "=>", "'transaction'", ",", "'bindings'", "=>", "[", "]", ",", "'time'", "=>", "0", ",", "'source'", "=>", "$", "source", ",", "'explain'", "=>", "[", "]", ",", "'connection'", "=>", "$", "connection", "->", "getDatabaseName", "(", ")", ",", "'hints'", "=>", "null", ",", "]", ";", "}" ]
Collect a database transaction event. @param string $event @param \Illuminate\Database\Connection $connection @return array
[ "Collect", "a", "database", "transaction", "event", "." ]
2d195779ea4f809f69764a795e2ec371dbb76a96
https://github.com/barryvdh/laravel-debugbar/blob/2d195779ea4f809f69764a795e2ec371dbb76a96/src/DataCollector/QueryCollector.php#L376-L397
210,297
barryvdh/laravel-debugbar
src/Storage/FilesystemStorage.php
FilesystemStorage.filter
protected function filter($meta, $filters) { foreach ($filters as $key => $value) { if (!isset($meta[$key]) || fnmatch($value, $meta[$key]) === false) { return false; } } return true; }
php
protected function filter($meta, $filters) { foreach ($filters as $key => $value) { if (!isset($meta[$key]) || fnmatch($value, $meta[$key]) === false) { return false; } } return true; }
[ "protected", "function", "filter", "(", "$", "meta", ",", "$", "filters", ")", "{", "foreach", "(", "$", "filters", "as", "$", "key", "=>", "$", "value", ")", "{", "if", "(", "!", "isset", "(", "$", "meta", "[", "$", "key", "]", ")", "||", "fnmatch", "(", "$", "value", ",", "$", "meta", "[", "$", "key", "]", ")", "===", "false", ")", "{", "return", "false", ";", "}", "}", "return", "true", ";", "}" ]
Filter the metadata for matches. @param $meta @param $filters @return bool
[ "Filter", "the", "metadata", "for", "matches", "." ]
2d195779ea4f809f69764a795e2ec371dbb76a96
https://github.com/barryvdh/laravel-debugbar/blob/2d195779ea4f809f69764a795e2ec371dbb76a96/src/Storage/FilesystemStorage.php#L123-L131
210,298
barryvdh/laravel-debugbar
src/DataCollector/FilesCollector.php
FilesCollector.getCompiledFiles
protected function getCompiledFiles() { if ($this->app && class_exists('Illuminate\Foundation\Console\OptimizeCommand')) { $reflector = new \ReflectionClass('Illuminate\Foundation\Console\OptimizeCommand'); $path = dirname($reflector->getFileName()) . '/Optimize/config.php'; if (file_exists($path)) { $app = $this->app; $core = require $path; return array_merge($core, $app['config']['compile']); } } return []; }
php
protected function getCompiledFiles() { if ($this->app && class_exists('Illuminate\Foundation\Console\OptimizeCommand')) { $reflector = new \ReflectionClass('Illuminate\Foundation\Console\OptimizeCommand'); $path = dirname($reflector->getFileName()) . '/Optimize/config.php'; if (file_exists($path)) { $app = $this->app; $core = require $path; return array_merge($core, $app['config']['compile']); } } return []; }
[ "protected", "function", "getCompiledFiles", "(", ")", "{", "if", "(", "$", "this", "->", "app", "&&", "class_exists", "(", "'Illuminate\\Foundation\\Console\\OptimizeCommand'", ")", ")", "{", "$", "reflector", "=", "new", "\\", "ReflectionClass", "(", "'Illuminate\\Foundation\\Console\\OptimizeCommand'", ")", ";", "$", "path", "=", "dirname", "(", "$", "reflector", "->", "getFileName", "(", ")", ")", ".", "'/Optimize/config.php'", ";", "if", "(", "file_exists", "(", "$", "path", ")", ")", "{", "$", "app", "=", "$", "this", "->", "app", ";", "$", "core", "=", "require", "$", "path", ";", "return", "array_merge", "(", "$", "core", ",", "$", "app", "[", "'config'", "]", "[", "'compile'", "]", ")", ";", "}", "}", "return", "[", "]", ";", "}" ]
Get the files that are going to be compiled, so they aren't as important. @return array
[ "Get", "the", "files", "that", "are", "going", "to", "be", "compiled", "so", "they", "aren", "t", "as", "important", "." ]
2d195779ea4f809f69764a795e2ec371dbb76a96
https://github.com/barryvdh/laravel-debugbar/blob/2d195779ea4f809f69764a795e2ec371dbb76a96/src/DataCollector/FilesCollector.php#L82-L95
210,299
barryvdh/laravel-debugbar
src/Controllers/AssetController.php
AssetController.js
public function js() { $renderer = $this->debugbar->getJavascriptRenderer(); $content = $renderer->dumpAssetsToString('js'); $response = new Response( $content, 200, [ 'Content-Type' => 'text/javascript', ] ); return $this->cacheResponse($response); }
php
public function js() { $renderer = $this->debugbar->getJavascriptRenderer(); $content = $renderer->dumpAssetsToString('js'); $response = new Response( $content, 200, [ 'Content-Type' => 'text/javascript', ] ); return $this->cacheResponse($response); }
[ "public", "function", "js", "(", ")", "{", "$", "renderer", "=", "$", "this", "->", "debugbar", "->", "getJavascriptRenderer", "(", ")", ";", "$", "content", "=", "$", "renderer", "->", "dumpAssetsToString", "(", "'js'", ")", ";", "$", "response", "=", "new", "Response", "(", "$", "content", ",", "200", ",", "[", "'Content-Type'", "=>", "'text/javascript'", ",", "]", ")", ";", "return", "$", "this", "->", "cacheResponse", "(", "$", "response", ")", ";", "}" ]
Return the javascript for the Debugbar @return \Symfony\Component\HttpFoundation\Response
[ "Return", "the", "javascript", "for", "the", "Debugbar" ]
2d195779ea4f809f69764a795e2ec371dbb76a96
https://github.com/barryvdh/laravel-debugbar/blob/2d195779ea4f809f69764a795e2ec371dbb76a96/src/Controllers/AssetController.php#L12-L25