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,100
matomo-org/matomo
core/DataTable/Renderer/Php.php
Php.renderTable
protected function renderTable($table) { $array = array(); foreach ($table->getRows() as $id => $row) { $newRow = array( 'columns' => $row->getColumns(), 'metadata' => $row->getMetadata(), 'idsubdatatable' => $row->getIdSubDataTable(), ); if ($id == DataTable::ID_SUMMARY_ROW) { $newRow['issummaryrow'] = true; } $subTable = $row->getSubtable(); if ($this->isRenderSubtables() && $subTable ) { $subTable = $this->renderTable($subTable); $newRow['subtable'] = $subTable; if ($this->hideIdSubDatatable === false && isset($newRow['metadata']['idsubdatatable_in_db']) ) { $newRow['columns']['idsubdatatable'] = $newRow['metadata']['idsubdatatable_in_db']; } unset($newRow['metadata']['idsubdatatable_in_db']); } if ($this->hideIdSubDatatable !== false) { unset($newRow['idsubdatatable']); } $array[] = $newRow; } return $array; }
php
protected function renderTable($table) { $array = array(); foreach ($table->getRows() as $id => $row) { $newRow = array( 'columns' => $row->getColumns(), 'metadata' => $row->getMetadata(), 'idsubdatatable' => $row->getIdSubDataTable(), ); if ($id == DataTable::ID_SUMMARY_ROW) { $newRow['issummaryrow'] = true; } $subTable = $row->getSubtable(); if ($this->isRenderSubtables() && $subTable ) { $subTable = $this->renderTable($subTable); $newRow['subtable'] = $subTable; if ($this->hideIdSubDatatable === false && isset($newRow['metadata']['idsubdatatable_in_db']) ) { $newRow['columns']['idsubdatatable'] = $newRow['metadata']['idsubdatatable_in_db']; } unset($newRow['metadata']['idsubdatatable_in_db']); } if ($this->hideIdSubDatatable !== false) { unset($newRow['idsubdatatable']); } $array[] = $newRow; } return $array; }
[ "protected", "function", "renderTable", "(", "$", "table", ")", "{", "$", "array", "=", "array", "(", ")", ";", "foreach", "(", "$", "table", "->", "getRows", "(", ")", "as", "$", "id", "=>", "$", "row", ")", "{", "$", "newRow", "=", "array", "(", "'columns'", "=>", "$", "row", "->", "getColumns", "(", ")", ",", "'metadata'", "=>", "$", "row", "->", "getMetadata", "(", ")", ",", "'idsubdatatable'", "=>", "$", "row", "->", "getIdSubDataTable", "(", ")", ",", ")", ";", "if", "(", "$", "id", "==", "DataTable", "::", "ID_SUMMARY_ROW", ")", "{", "$", "newRow", "[", "'issummaryrow'", "]", "=", "true", ";", "}", "$", "subTable", "=", "$", "row", "->", "getSubtable", "(", ")", ";", "if", "(", "$", "this", "->", "isRenderSubtables", "(", ")", "&&", "$", "subTable", ")", "{", "$", "subTable", "=", "$", "this", "->", "renderTable", "(", "$", "subTable", ")", ";", "$", "newRow", "[", "'subtable'", "]", "=", "$", "subTable", ";", "if", "(", "$", "this", "->", "hideIdSubDatatable", "===", "false", "&&", "isset", "(", "$", "newRow", "[", "'metadata'", "]", "[", "'idsubdatatable_in_db'", "]", ")", ")", "{", "$", "newRow", "[", "'columns'", "]", "[", "'idsubdatatable'", "]", "=", "$", "newRow", "[", "'metadata'", "]", "[", "'idsubdatatable_in_db'", "]", ";", "}", "unset", "(", "$", "newRow", "[", "'metadata'", "]", "[", "'idsubdatatable_in_db'", "]", ")", ";", "}", "if", "(", "$", "this", "->", "hideIdSubDatatable", "!==", "false", ")", "{", "unset", "(", "$", "newRow", "[", "'idsubdatatable'", "]", ")", ";", "}", "$", "array", "[", "]", "=", "$", "newRow", ";", "}", "return", "$", "array", ";", "}" ]
Converts the given data table to an array @param DataTable $table @return array
[ "Converts", "the", "given", "data", "table", "to", "an", "array" ]
72df150735664275a60a7861e468c6ff3b152a14
https://github.com/matomo-org/matomo/blob/72df150735664275a60a7861e468c6ff3b152a14/core/DataTable/Renderer/Php.php#L194-L229
210,101
matomo-org/matomo
core/DataTable/Renderer/Php.php
Php.renderSimpleTable
protected function renderSimpleTable($table) { $array = array(); $row = $table->getFirstRow(); if ($row === false) { return $array; } foreach ($row->getColumns() as $columnName => $columnValue) { $array[$columnName] = $columnValue; } return $array; }
php
protected function renderSimpleTable($table) { $array = array(); $row = $table->getFirstRow(); if ($row === false) { return $array; } foreach ($row->getColumns() as $columnName => $columnValue) { $array[$columnName] = $columnValue; } return $array; }
[ "protected", "function", "renderSimpleTable", "(", "$", "table", ")", "{", "$", "array", "=", "array", "(", ")", ";", "$", "row", "=", "$", "table", "->", "getFirstRow", "(", ")", ";", "if", "(", "$", "row", "===", "false", ")", "{", "return", "$", "array", ";", "}", "foreach", "(", "$", "row", "->", "getColumns", "(", ")", "as", "$", "columnName", "=>", "$", "columnValue", ")", "{", "$", "array", "[", "$", "columnName", "]", "=", "$", "columnValue", ";", "}", "return", "$", "array", ";", "}" ]
Converts the simple data table to an array @param Simple $table @return array
[ "Converts", "the", "simple", "data", "table", "to", "an", "array" ]
72df150735664275a60a7861e468c6ff3b152a14
https://github.com/matomo-org/matomo/blob/72df150735664275a60a7861e468c6ff3b152a14/core/DataTable/Renderer/Php.php#L237-L249
210,102
matomo-org/matomo
plugins/SitesManager/Controller.php
Controller.setGlobalSettings
public function setGlobalSettings() { $response = new ResponseBuilder(Common::getRequestVar('format')); try { $this->checkTokenInUrl(); $timezone = Common::getRequestVar('timezone', false); $excludedIps = Common::getRequestVar('excludedIps', false); $excludedQueryParameters = Common::getRequestVar('excludedQueryParameters', false); $excludedUserAgents = Common::getRequestVar('excludedUserAgents', false); $currency = Common::getRequestVar('currency', false); $searchKeywordParameters = Common::getRequestVar('searchKeywordParameters', $default = ""); $searchCategoryParameters = Common::getRequestVar('searchCategoryParameters', $default = ""); $enableSiteUserAgentExclude = Common::getRequestVar('enableSiteUserAgentExclude', $default = 0); $keepURLFragments = Common::getRequestVar('keepURLFragments', $default = 0); $api = API::getInstance(); $api->setDefaultTimezone($timezone); $api->setDefaultCurrency($currency); $api->setGlobalExcludedQueryParameters($excludedQueryParameters); $api->setGlobalExcludedIps($excludedIps); $api->setGlobalExcludedUserAgents($excludedUserAgents); $api->setGlobalSearchParameters($searchKeywordParameters, $searchCategoryParameters); $api->setSiteSpecificUserAgentExcludeEnabled($enableSiteUserAgentExclude == 1); $api->setKeepURLFragmentsGlobal($keepURLFragments); $toReturn = $response->getResponse(); } catch (Exception $e) { $toReturn = $response->getResponseException($e); } return $toReturn; }
php
public function setGlobalSettings() { $response = new ResponseBuilder(Common::getRequestVar('format')); try { $this->checkTokenInUrl(); $timezone = Common::getRequestVar('timezone', false); $excludedIps = Common::getRequestVar('excludedIps', false); $excludedQueryParameters = Common::getRequestVar('excludedQueryParameters', false); $excludedUserAgents = Common::getRequestVar('excludedUserAgents', false); $currency = Common::getRequestVar('currency', false); $searchKeywordParameters = Common::getRequestVar('searchKeywordParameters', $default = ""); $searchCategoryParameters = Common::getRequestVar('searchCategoryParameters', $default = ""); $enableSiteUserAgentExclude = Common::getRequestVar('enableSiteUserAgentExclude', $default = 0); $keepURLFragments = Common::getRequestVar('keepURLFragments', $default = 0); $api = API::getInstance(); $api->setDefaultTimezone($timezone); $api->setDefaultCurrency($currency); $api->setGlobalExcludedQueryParameters($excludedQueryParameters); $api->setGlobalExcludedIps($excludedIps); $api->setGlobalExcludedUserAgents($excludedUserAgents); $api->setGlobalSearchParameters($searchKeywordParameters, $searchCategoryParameters); $api->setSiteSpecificUserAgentExcludeEnabled($enableSiteUserAgentExclude == 1); $api->setKeepURLFragmentsGlobal($keepURLFragments); $toReturn = $response->getResponse(); } catch (Exception $e) { $toReturn = $response->getResponseException($e); } return $toReturn; }
[ "public", "function", "setGlobalSettings", "(", ")", "{", "$", "response", "=", "new", "ResponseBuilder", "(", "Common", "::", "getRequestVar", "(", "'format'", ")", ")", ";", "try", "{", "$", "this", "->", "checkTokenInUrl", "(", ")", ";", "$", "timezone", "=", "Common", "::", "getRequestVar", "(", "'timezone'", ",", "false", ")", ";", "$", "excludedIps", "=", "Common", "::", "getRequestVar", "(", "'excludedIps'", ",", "false", ")", ";", "$", "excludedQueryParameters", "=", "Common", "::", "getRequestVar", "(", "'excludedQueryParameters'", ",", "false", ")", ";", "$", "excludedUserAgents", "=", "Common", "::", "getRequestVar", "(", "'excludedUserAgents'", ",", "false", ")", ";", "$", "currency", "=", "Common", "::", "getRequestVar", "(", "'currency'", ",", "false", ")", ";", "$", "searchKeywordParameters", "=", "Common", "::", "getRequestVar", "(", "'searchKeywordParameters'", ",", "$", "default", "=", "\"\"", ")", ";", "$", "searchCategoryParameters", "=", "Common", "::", "getRequestVar", "(", "'searchCategoryParameters'", ",", "$", "default", "=", "\"\"", ")", ";", "$", "enableSiteUserAgentExclude", "=", "Common", "::", "getRequestVar", "(", "'enableSiteUserAgentExclude'", ",", "$", "default", "=", "0", ")", ";", "$", "keepURLFragments", "=", "Common", "::", "getRequestVar", "(", "'keepURLFragments'", ",", "$", "default", "=", "0", ")", ";", "$", "api", "=", "API", "::", "getInstance", "(", ")", ";", "$", "api", "->", "setDefaultTimezone", "(", "$", "timezone", ")", ";", "$", "api", "->", "setDefaultCurrency", "(", "$", "currency", ")", ";", "$", "api", "->", "setGlobalExcludedQueryParameters", "(", "$", "excludedQueryParameters", ")", ";", "$", "api", "->", "setGlobalExcludedIps", "(", "$", "excludedIps", ")", ";", "$", "api", "->", "setGlobalExcludedUserAgents", "(", "$", "excludedUserAgents", ")", ";", "$", "api", "->", "setGlobalSearchParameters", "(", "$", "searchKeywordParameters", ",", "$", "searchCategoryParameters", ")", ";", "$", "api", "->", "setSiteSpecificUserAgentExcludeEnabled", "(", "$", "enableSiteUserAgentExclude", "==", "1", ")", ";", "$", "api", "->", "setKeepURLFragmentsGlobal", "(", "$", "keepURLFragments", ")", ";", "$", "toReturn", "=", "$", "response", "->", "getResponse", "(", ")", ";", "}", "catch", "(", "Exception", "$", "e", ")", "{", "$", "toReturn", "=", "$", "response", "->", "getResponseException", "(", "$", "e", ")", ";", "}", "return", "$", "toReturn", ";", "}" ]
Records Global settings when user submit changes
[ "Records", "Global", "settings", "when", "user", "submit", "changes" ]
72df150735664275a60a7861e468c6ff3b152a14
https://github.com/matomo-org/matomo/blob/72df150735664275a60a7861e468c6ff3b152a14/plugins/SitesManager/Controller.php#L69-L101
210,103
matomo-org/matomo
plugins/SitesManager/Controller.php
Controller.downloadPiwikTracker
function downloadPiwikTracker() { $path = PIWIK_INCLUDE_PATH . '/libs/PiwikTracker/'; $filename = 'PiwikTracker.php'; Common::sendHeader('Content-type: text/php'); Common::sendHeader('Content-Disposition: attachment; filename="' . $filename . '"'); return file_get_contents($path . $filename); }
php
function downloadPiwikTracker() { $path = PIWIK_INCLUDE_PATH . '/libs/PiwikTracker/'; $filename = 'PiwikTracker.php'; Common::sendHeader('Content-type: text/php'); Common::sendHeader('Content-Disposition: attachment; filename="' . $filename . '"'); return file_get_contents($path . $filename); }
[ "function", "downloadPiwikTracker", "(", ")", "{", "$", "path", "=", "PIWIK_INCLUDE_PATH", ".", "'/libs/PiwikTracker/'", ";", "$", "filename", "=", "'PiwikTracker.php'", ";", "Common", "::", "sendHeader", "(", "'Content-type: text/php'", ")", ";", "Common", "::", "sendHeader", "(", "'Content-Disposition: attachment; filename=\"'", ".", "$", "filename", ".", "'\"'", ")", ";", "return", "file_get_contents", "(", "$", "path", ".", "$", "filename", ")", ";", "}" ]
User will download a file called PiwikTracker.php that is the content of the actual script
[ "User", "will", "download", "a", "file", "called", "PiwikTracker", ".", "php", "that", "is", "the", "content", "of", "the", "actual", "script" ]
72df150735664275a60a7861e468c6ff3b152a14
https://github.com/matomo-org/matomo/blob/72df150735664275a60a7861e468c6ff3b152a14/plugins/SitesManager/Controller.php#L106-L113
210,104
matomo-org/matomo
core/Updater.php
Updater.getCurrentComponentVersion
public function getCurrentComponentVersion($name) { try { $currentVersion = Option::get(self::getNameInOptionTable($name)); } catch (\Exception $e) { // mysql error 1146: table doesn't exist if (Db::get()->isErrNo($e, '1146')) { // case when the option table is not yet created (before 0.2.10) $currentVersion = false; } else { // failed for some other reason throw $e; } } return $currentVersion; }
php
public function getCurrentComponentVersion($name) { try { $currentVersion = Option::get(self::getNameInOptionTable($name)); } catch (\Exception $e) { // mysql error 1146: table doesn't exist if (Db::get()->isErrNo($e, '1146')) { // case when the option table is not yet created (before 0.2.10) $currentVersion = false; } else { // failed for some other reason throw $e; } } return $currentVersion; }
[ "public", "function", "getCurrentComponentVersion", "(", "$", "name", ")", "{", "try", "{", "$", "currentVersion", "=", "Option", "::", "get", "(", "self", "::", "getNameInOptionTable", "(", "$", "name", ")", ")", ";", "}", "catch", "(", "\\", "Exception", "$", "e", ")", "{", "// mysql error 1146: table doesn't exist", "if", "(", "Db", "::", "get", "(", ")", "->", "isErrNo", "(", "$", "e", ",", "'1146'", ")", ")", "{", "// case when the option table is not yet created (before 0.2.10)", "$", "currentVersion", "=", "false", ";", "}", "else", "{", "// failed for some other reason", "throw", "$", "e", ";", "}", "}", "return", "$", "currentVersion", ";", "}" ]
Returns the currently installed version of a Piwik component. @param string $name The component name. Eg, a plugin name, `'core'` or dimension column name. @return string A semantic version. @throws \Exception
[ "Returns", "the", "currently", "installed", "version", "of", "a", "Piwik", "component", "." ]
72df150735664275a60a7861e468c6ff3b152a14
https://github.com/matomo-org/matomo/blob/72df150735664275a60a7861e468c6ff3b152a14/core/Updater.php#L171-L187
210,105
matomo-org/matomo
core/Updater.php
Updater.getSqlQueriesToExecute
public function getSqlQueriesToExecute() { $queries = array(); $classNames = array(); foreach ($this->componentsWithUpdateFile as $componentName => $componentUpdateInfo) { foreach ($componentUpdateInfo as $file => $fileVersion) { require_once $file; // prefixed by PIWIK_INCLUDE_PATH $className = $this->getUpdateClassName($componentName, $fileVersion); if (!class_exists($className, false)) { throw new \Exception("The class $className was not found in $file"); } if (in_array($className, $classNames)) { continue; // prevent from getting updates from Piwik\Columns\Updater multiple times } $classNames[] = $className; /** @var Updates $update */ $update = StaticContainer::getContainer()->make($className); $migrationsForComponent = $update->getMigrations($this); foreach ($migrationsForComponent as $index => $migration) { $migration = $this->keepBcForOldMigrationQueryFormat($index, $migration); $queries[] = $migration; } $this->hasMajorDbUpdate = $this->hasMajorDbUpdate || call_user_func(array($className, 'isMajorUpdate')); } } return $queries; }
php
public function getSqlQueriesToExecute() { $queries = array(); $classNames = array(); foreach ($this->componentsWithUpdateFile as $componentName => $componentUpdateInfo) { foreach ($componentUpdateInfo as $file => $fileVersion) { require_once $file; // prefixed by PIWIK_INCLUDE_PATH $className = $this->getUpdateClassName($componentName, $fileVersion); if (!class_exists($className, false)) { throw new \Exception("The class $className was not found in $file"); } if (in_array($className, $classNames)) { continue; // prevent from getting updates from Piwik\Columns\Updater multiple times } $classNames[] = $className; /** @var Updates $update */ $update = StaticContainer::getContainer()->make($className); $migrationsForComponent = $update->getMigrations($this); foreach ($migrationsForComponent as $index => $migration) { $migration = $this->keepBcForOldMigrationQueryFormat($index, $migration); $queries[] = $migration; } $this->hasMajorDbUpdate = $this->hasMajorDbUpdate || call_user_func(array($className, 'isMajorUpdate')); } } return $queries; }
[ "public", "function", "getSqlQueriesToExecute", "(", ")", "{", "$", "queries", "=", "array", "(", ")", ";", "$", "classNames", "=", "array", "(", ")", ";", "foreach", "(", "$", "this", "->", "componentsWithUpdateFile", "as", "$", "componentName", "=>", "$", "componentUpdateInfo", ")", "{", "foreach", "(", "$", "componentUpdateInfo", "as", "$", "file", "=>", "$", "fileVersion", ")", "{", "require_once", "$", "file", ";", "// prefixed by PIWIK_INCLUDE_PATH", "$", "className", "=", "$", "this", "->", "getUpdateClassName", "(", "$", "componentName", ",", "$", "fileVersion", ")", ";", "if", "(", "!", "class_exists", "(", "$", "className", ",", "false", ")", ")", "{", "throw", "new", "\\", "Exception", "(", "\"The class $className was not found in $file\"", ")", ";", "}", "if", "(", "in_array", "(", "$", "className", ",", "$", "classNames", ")", ")", "{", "continue", ";", "// prevent from getting updates from Piwik\\Columns\\Updater multiple times", "}", "$", "classNames", "[", "]", "=", "$", "className", ";", "/** @var Updates $update */", "$", "update", "=", "StaticContainer", "::", "getContainer", "(", ")", "->", "make", "(", "$", "className", ")", ";", "$", "migrationsForComponent", "=", "$", "update", "->", "getMigrations", "(", "$", "this", ")", ";", "foreach", "(", "$", "migrationsForComponent", "as", "$", "index", "=>", "$", "migration", ")", "{", "$", "migration", "=", "$", "this", "->", "keepBcForOldMigrationQueryFormat", "(", "$", "index", ",", "$", "migration", ")", ";", "$", "queries", "[", "]", "=", "$", "migration", ";", "}", "$", "this", "->", "hasMajorDbUpdate", "=", "$", "this", "->", "hasMajorDbUpdate", "||", "call_user_func", "(", "array", "(", "$", "className", ",", "'isMajorUpdate'", ")", ")", ";", "}", "}", "return", "$", "queries", ";", "}" ]
Returns the list of SQL queries that would be executed during the update @return Migration[] of SQL queries @throws \Exception
[ "Returns", "the", "list", "of", "SQL", "queries", "that", "would", "be", "executed", "during", "the", "update" ]
72df150735664275a60a7861e468c6ff3b152a14
https://github.com/matomo-org/matomo/blob/72df150735664275a60a7861e468c6ff3b152a14/core/Updater.php#L234-L265
210,106
matomo-org/matomo
core/Updater.php
Updater.update
public function update($componentName) { $warningMessages = array(); $this->executeListenerHook('onComponentUpdateStarting', array($componentName)); foreach ($this->componentsWithUpdateFile[$componentName] as $file => $fileVersion) { try { require_once $file; // prefixed by PIWIK_INCLUDE_PATH $className = $this->getUpdateClassName($componentName, $fileVersion); if (!in_array($className, $this->updatedClasses) && class_exists($className, false) ) { $this->executeListenerHook('onComponentUpdateFileStarting', array($componentName, $file, $className, $fileVersion)); $this->executeSingleUpdateClass($className); $this->executeListenerHook('onComponentUpdateFileFinished', array($componentName, $file, $className, $fileVersion)); // makes sure to call Piwik\Columns\Updater only once as one call updates all dimensions at the same // time for better performance $this->updatedClasses[] = $className; } $this->markComponentSuccessfullyUpdated($componentName, $fileVersion); } catch (UpdaterErrorException $e) { $this->executeListenerHook('onError', array($componentName, $fileVersion, $e)); throw $e; } catch (\Exception $e) { $warningMessages[] = $e->getMessage(); $this->executeListenerHook('onWarning', array($componentName, $fileVersion, $e)); } } // to debug, create core/Updates/X.php, update the core/Version.php, throw an Exception in the try, and comment the following lines $updatedVersion = $this->componentsWithNewVersion[$componentName][self::INDEX_NEW_VERSION]; $this->markComponentSuccessfullyUpdated($componentName, $updatedVersion); $this->executeListenerHook('onComponentUpdateFinished', array($componentName, $updatedVersion, $warningMessages)); ServerFilesGenerator::createHtAccessFiles(); return $warningMessages; }
php
public function update($componentName) { $warningMessages = array(); $this->executeListenerHook('onComponentUpdateStarting', array($componentName)); foreach ($this->componentsWithUpdateFile[$componentName] as $file => $fileVersion) { try { require_once $file; // prefixed by PIWIK_INCLUDE_PATH $className = $this->getUpdateClassName($componentName, $fileVersion); if (!in_array($className, $this->updatedClasses) && class_exists($className, false) ) { $this->executeListenerHook('onComponentUpdateFileStarting', array($componentName, $file, $className, $fileVersion)); $this->executeSingleUpdateClass($className); $this->executeListenerHook('onComponentUpdateFileFinished', array($componentName, $file, $className, $fileVersion)); // makes sure to call Piwik\Columns\Updater only once as one call updates all dimensions at the same // time for better performance $this->updatedClasses[] = $className; } $this->markComponentSuccessfullyUpdated($componentName, $fileVersion); } catch (UpdaterErrorException $e) { $this->executeListenerHook('onError', array($componentName, $fileVersion, $e)); throw $e; } catch (\Exception $e) { $warningMessages[] = $e->getMessage(); $this->executeListenerHook('onWarning', array($componentName, $fileVersion, $e)); } } // to debug, create core/Updates/X.php, update the core/Version.php, throw an Exception in the try, and comment the following lines $updatedVersion = $this->componentsWithNewVersion[$componentName][self::INDEX_NEW_VERSION]; $this->markComponentSuccessfullyUpdated($componentName, $updatedVersion); $this->executeListenerHook('onComponentUpdateFinished', array($componentName, $updatedVersion, $warningMessages)); ServerFilesGenerator::createHtAccessFiles(); return $warningMessages; }
[ "public", "function", "update", "(", "$", "componentName", ")", "{", "$", "warningMessages", "=", "array", "(", ")", ";", "$", "this", "->", "executeListenerHook", "(", "'onComponentUpdateStarting'", ",", "array", "(", "$", "componentName", ")", ")", ";", "foreach", "(", "$", "this", "->", "componentsWithUpdateFile", "[", "$", "componentName", "]", "as", "$", "file", "=>", "$", "fileVersion", ")", "{", "try", "{", "require_once", "$", "file", ";", "// prefixed by PIWIK_INCLUDE_PATH", "$", "className", "=", "$", "this", "->", "getUpdateClassName", "(", "$", "componentName", ",", "$", "fileVersion", ")", ";", "if", "(", "!", "in_array", "(", "$", "className", ",", "$", "this", "->", "updatedClasses", ")", "&&", "class_exists", "(", "$", "className", ",", "false", ")", ")", "{", "$", "this", "->", "executeListenerHook", "(", "'onComponentUpdateFileStarting'", ",", "array", "(", "$", "componentName", ",", "$", "file", ",", "$", "className", ",", "$", "fileVersion", ")", ")", ";", "$", "this", "->", "executeSingleUpdateClass", "(", "$", "className", ")", ";", "$", "this", "->", "executeListenerHook", "(", "'onComponentUpdateFileFinished'", ",", "array", "(", "$", "componentName", ",", "$", "file", ",", "$", "className", ",", "$", "fileVersion", ")", ")", ";", "// makes sure to call Piwik\\Columns\\Updater only once as one call updates all dimensions at the same", "// time for better performance", "$", "this", "->", "updatedClasses", "[", "]", "=", "$", "className", ";", "}", "$", "this", "->", "markComponentSuccessfullyUpdated", "(", "$", "componentName", ",", "$", "fileVersion", ")", ";", "}", "catch", "(", "UpdaterErrorException", "$", "e", ")", "{", "$", "this", "->", "executeListenerHook", "(", "'onError'", ",", "array", "(", "$", "componentName", ",", "$", "fileVersion", ",", "$", "e", ")", ")", ";", "throw", "$", "e", ";", "}", "catch", "(", "\\", "Exception", "$", "e", ")", "{", "$", "warningMessages", "[", "]", "=", "$", "e", "->", "getMessage", "(", ")", ";", "$", "this", "->", "executeListenerHook", "(", "'onWarning'", ",", "array", "(", "$", "componentName", ",", "$", "fileVersion", ",", "$", "e", ")", ")", ";", "}", "}", "// to debug, create core/Updates/X.php, update the core/Version.php, throw an Exception in the try, and comment the following lines", "$", "updatedVersion", "=", "$", "this", "->", "componentsWithNewVersion", "[", "$", "componentName", "]", "[", "self", "::", "INDEX_NEW_VERSION", "]", ";", "$", "this", "->", "markComponentSuccessfullyUpdated", "(", "$", "componentName", ",", "$", "updatedVersion", ")", ";", "$", "this", "->", "executeListenerHook", "(", "'onComponentUpdateFinished'", ",", "array", "(", "$", "componentName", ",", "$", "updatedVersion", ",", "$", "warningMessages", ")", ")", ";", "ServerFilesGenerator", "::", "createHtAccessFiles", "(", ")", ";", "return", "$", "warningMessages", ";", "}" ]
Update the named component @param string $componentName 'core', or plugin name @throws \Exception|UpdaterErrorException @return array of warning strings if applicable
[ "Update", "the", "named", "component" ]
72df150735664275a60a7861e468c6ff3b152a14
https://github.com/matomo-org/matomo/blob/72df150735664275a60a7861e468c6ff3b152a14/core/Updater.php#L290-L334
210,107
matomo-org/matomo
core/Updater.php
Updater.loadComponentsWithUpdateFile
private function loadComponentsWithUpdateFile() { $componentsWithUpdateFile = array(); foreach ($this->componentsWithNewVersion as $name => $versions) { $currentVersion = $versions[self::INDEX_CURRENT_VERSION]; $newVersion = $versions[self::INDEX_NEW_VERSION]; if ($name == 'core') { $pathToUpdates = $this->pathUpdateFileCore . '*.php'; } elseif (ColumnUpdater::isDimensionComponent($name)) { $componentsWithUpdateFile[$name][PIWIK_INCLUDE_PATH . '/core/Columns/Updater.php'] = $newVersion; } else { if ($this->pathUpdateFilePlugins) { $pathToUpdates = sprintf($this->pathUpdateFilePlugins, $name) . '*.php'; } else { $pathToUpdates = Manager::getPluginDirectory($name) . '/Updates/*.php'; } } if (!empty($pathToUpdates)) { $files = _glob($pathToUpdates); if ($files == false) { $files = array(); } foreach ($files as $file) { $fileVersion = basename($file, '.php'); if (// if the update is from a newer version version_compare($currentVersion, $fileVersion) == -1 // but we don't execute updates from non existing future releases && version_compare($fileVersion, $newVersion) <= 0 ) { $componentsWithUpdateFile[$name][$file] = $fileVersion; } } } if (isset($componentsWithUpdateFile[$name])) { // order the update files by version asc uasort($componentsWithUpdateFile[$name], "version_compare"); } else { // there are no update file => nothing to do, update to the new version is successful $this->markComponentSuccessfullyUpdated($name, $newVersion); } } return $componentsWithUpdateFile; }
php
private function loadComponentsWithUpdateFile() { $componentsWithUpdateFile = array(); foreach ($this->componentsWithNewVersion as $name => $versions) { $currentVersion = $versions[self::INDEX_CURRENT_VERSION]; $newVersion = $versions[self::INDEX_NEW_VERSION]; if ($name == 'core') { $pathToUpdates = $this->pathUpdateFileCore . '*.php'; } elseif (ColumnUpdater::isDimensionComponent($name)) { $componentsWithUpdateFile[$name][PIWIK_INCLUDE_PATH . '/core/Columns/Updater.php'] = $newVersion; } else { if ($this->pathUpdateFilePlugins) { $pathToUpdates = sprintf($this->pathUpdateFilePlugins, $name) . '*.php'; } else { $pathToUpdates = Manager::getPluginDirectory($name) . '/Updates/*.php'; } } if (!empty($pathToUpdates)) { $files = _glob($pathToUpdates); if ($files == false) { $files = array(); } foreach ($files as $file) { $fileVersion = basename($file, '.php'); if (// if the update is from a newer version version_compare($currentVersion, $fileVersion) == -1 // but we don't execute updates from non existing future releases && version_compare($fileVersion, $newVersion) <= 0 ) { $componentsWithUpdateFile[$name][$file] = $fileVersion; } } } if (isset($componentsWithUpdateFile[$name])) { // order the update files by version asc uasort($componentsWithUpdateFile[$name], "version_compare"); } else { // there are no update file => nothing to do, update to the new version is successful $this->markComponentSuccessfullyUpdated($name, $newVersion); } } return $componentsWithUpdateFile; }
[ "private", "function", "loadComponentsWithUpdateFile", "(", ")", "{", "$", "componentsWithUpdateFile", "=", "array", "(", ")", ";", "foreach", "(", "$", "this", "->", "componentsWithNewVersion", "as", "$", "name", "=>", "$", "versions", ")", "{", "$", "currentVersion", "=", "$", "versions", "[", "self", "::", "INDEX_CURRENT_VERSION", "]", ";", "$", "newVersion", "=", "$", "versions", "[", "self", "::", "INDEX_NEW_VERSION", "]", ";", "if", "(", "$", "name", "==", "'core'", ")", "{", "$", "pathToUpdates", "=", "$", "this", "->", "pathUpdateFileCore", ".", "'*.php'", ";", "}", "elseif", "(", "ColumnUpdater", "::", "isDimensionComponent", "(", "$", "name", ")", ")", "{", "$", "componentsWithUpdateFile", "[", "$", "name", "]", "[", "PIWIK_INCLUDE_PATH", ".", "'/core/Columns/Updater.php'", "]", "=", "$", "newVersion", ";", "}", "else", "{", "if", "(", "$", "this", "->", "pathUpdateFilePlugins", ")", "{", "$", "pathToUpdates", "=", "sprintf", "(", "$", "this", "->", "pathUpdateFilePlugins", ",", "$", "name", ")", ".", "'*.php'", ";", "}", "else", "{", "$", "pathToUpdates", "=", "Manager", "::", "getPluginDirectory", "(", "$", "name", ")", ".", "'/Updates/*.php'", ";", "}", "}", "if", "(", "!", "empty", "(", "$", "pathToUpdates", ")", ")", "{", "$", "files", "=", "_glob", "(", "$", "pathToUpdates", ")", ";", "if", "(", "$", "files", "==", "false", ")", "{", "$", "files", "=", "array", "(", ")", ";", "}", "foreach", "(", "$", "files", "as", "$", "file", ")", "{", "$", "fileVersion", "=", "basename", "(", "$", "file", ",", "'.php'", ")", ";", "if", "(", "// if the update is from a newer version", "version_compare", "(", "$", "currentVersion", ",", "$", "fileVersion", ")", "==", "-", "1", "// but we don't execute updates from non existing future releases", "&&", "version_compare", "(", "$", "fileVersion", ",", "$", "newVersion", ")", "<=", "0", ")", "{", "$", "componentsWithUpdateFile", "[", "$", "name", "]", "[", "$", "file", "]", "=", "$", "fileVersion", ";", "}", "}", "}", "if", "(", "isset", "(", "$", "componentsWithUpdateFile", "[", "$", "name", "]", ")", ")", "{", "// order the update files by version asc", "uasort", "(", "$", "componentsWithUpdateFile", "[", "$", "name", "]", ",", "\"version_compare\"", ")", ";", "}", "else", "{", "// there are no update file => nothing to do, update to the new version is successful", "$", "this", "->", "markComponentSuccessfullyUpdated", "(", "$", "name", ",", "$", "newVersion", ")", ";", "}", "}", "return", "$", "componentsWithUpdateFile", ";", "}" ]
Construct list of update files for the outdated components @return array( componentName => array( file1 => version1, [...]), [...])
[ "Construct", "list", "of", "update", "files", "for", "the", "outdated", "components" ]
72df150735664275a60a7861e468c6ff3b152a14
https://github.com/matomo-org/matomo/blob/72df150735664275a60a7861e468c6ff3b152a14/core/Updater.php#L341-L389
210,108
matomo-org/matomo
core/Updater.php
Updater.getComponentsWithNewVersion
public function getComponentsWithNewVersion($componentsToCheck) { $componentsToUpdate = array(); // we make sure core updates are processed before any plugin updates if (isset($componentsToCheck['core'])) { $coreVersions = $componentsToCheck['core']; unset($componentsToCheck['core']); $componentsToCheck = array_merge(array('core' => $coreVersions), $componentsToCheck); } $recordedCoreVersion = $this->getCurrentComponentVersion('core'); if (empty($recordedCoreVersion)) { // This should not happen $recordedCoreVersion = Version::VERSION; $this->markComponentSuccessfullyUpdated('core', $recordedCoreVersion); } foreach ($componentsToCheck as $name => $version) { $currentVersion = $this->getCurrentComponentVersion($name); if (ColumnUpdater::isDimensionComponent($name)) { $isComponentOutdated = $currentVersion !== $version; } else { // note: when versionCompare == 1, the version in the DB is newer, we choose to ignore $isComponentOutdated = version_compare($currentVersion, $version) == -1; } if ($isComponentOutdated || $currentVersion === false) { $componentsToUpdate[$name] = array( self::INDEX_CURRENT_VERSION => $currentVersion, self::INDEX_NEW_VERSION => $version ); } } return $componentsToUpdate; }
php
public function getComponentsWithNewVersion($componentsToCheck) { $componentsToUpdate = array(); // we make sure core updates are processed before any plugin updates if (isset($componentsToCheck['core'])) { $coreVersions = $componentsToCheck['core']; unset($componentsToCheck['core']); $componentsToCheck = array_merge(array('core' => $coreVersions), $componentsToCheck); } $recordedCoreVersion = $this->getCurrentComponentVersion('core'); if (empty($recordedCoreVersion)) { // This should not happen $recordedCoreVersion = Version::VERSION; $this->markComponentSuccessfullyUpdated('core', $recordedCoreVersion); } foreach ($componentsToCheck as $name => $version) { $currentVersion = $this->getCurrentComponentVersion($name); if (ColumnUpdater::isDimensionComponent($name)) { $isComponentOutdated = $currentVersion !== $version; } else { // note: when versionCompare == 1, the version in the DB is newer, we choose to ignore $isComponentOutdated = version_compare($currentVersion, $version) == -1; } if ($isComponentOutdated || $currentVersion === false) { $componentsToUpdate[$name] = array( self::INDEX_CURRENT_VERSION => $currentVersion, self::INDEX_NEW_VERSION => $version ); } } return $componentsToUpdate; }
[ "public", "function", "getComponentsWithNewVersion", "(", "$", "componentsToCheck", ")", "{", "$", "componentsToUpdate", "=", "array", "(", ")", ";", "// we make sure core updates are processed before any plugin updates", "if", "(", "isset", "(", "$", "componentsToCheck", "[", "'core'", "]", ")", ")", "{", "$", "coreVersions", "=", "$", "componentsToCheck", "[", "'core'", "]", ";", "unset", "(", "$", "componentsToCheck", "[", "'core'", "]", ")", ";", "$", "componentsToCheck", "=", "array_merge", "(", "array", "(", "'core'", "=>", "$", "coreVersions", ")", ",", "$", "componentsToCheck", ")", ";", "}", "$", "recordedCoreVersion", "=", "$", "this", "->", "getCurrentComponentVersion", "(", "'core'", ")", ";", "if", "(", "empty", "(", "$", "recordedCoreVersion", ")", ")", "{", "// This should not happen", "$", "recordedCoreVersion", "=", "Version", "::", "VERSION", ";", "$", "this", "->", "markComponentSuccessfullyUpdated", "(", "'core'", ",", "$", "recordedCoreVersion", ")", ";", "}", "foreach", "(", "$", "componentsToCheck", "as", "$", "name", "=>", "$", "version", ")", "{", "$", "currentVersion", "=", "$", "this", "->", "getCurrentComponentVersion", "(", "$", "name", ")", ";", "if", "(", "ColumnUpdater", "::", "isDimensionComponent", "(", "$", "name", ")", ")", "{", "$", "isComponentOutdated", "=", "$", "currentVersion", "!==", "$", "version", ";", "}", "else", "{", "// note: when versionCompare == 1, the version in the DB is newer, we choose to ignore", "$", "isComponentOutdated", "=", "version_compare", "(", "$", "currentVersion", ",", "$", "version", ")", "==", "-", "1", ";", "}", "if", "(", "$", "isComponentOutdated", "||", "$", "currentVersion", "===", "false", ")", "{", "$", "componentsToUpdate", "[", "$", "name", "]", "=", "array", "(", "self", "::", "INDEX_CURRENT_VERSION", "=>", "$", "currentVersion", ",", "self", "::", "INDEX_NEW_VERSION", "=>", "$", "version", ")", ";", "}", "}", "return", "$", "componentsToUpdate", ";", "}" ]
Construct list of outdated components @param string[] $componentsToCheck An array mapping component names to the latest locally available version. If the version is later than the currently installed version, the component must be upgraded. Example: `array('core' => '2.11.0')` @throws \Exception @return array array( componentName => array( oldVersion, newVersion), [...])
[ "Construct", "list", "of", "outdated", "components" ]
72df150735664275a60a7861e468c6ff3b152a14
https://github.com/matomo-org/matomo/blob/72df150735664275a60a7861e468c6ff3b152a14/core/Updater.php#L402-L439
210,109
matomo-org/matomo
core/Updater.php
Updater.updateComponents
public function updateComponents($componentsWithUpdateFile) { $warnings = array(); $errors = array(); $deactivatedPlugins = array(); $coreError = false; if (!empty($componentsWithUpdateFile)) { $currentAccess = Access::getInstance(); $hasSuperUserAccess = $currentAccess->hasSuperUserAccess(); if (!$hasSuperUserAccess) { $currentAccess->setSuperUserAccess(true); } // if error in any core update, show message + help message + EXIT // if errors in any plugins updates, show them on screen, disable plugins that errored + CONTINUE // if warning in any core update or in any plugins update, show message + CONTINUE // if no error or warning, success message + CONTINUE foreach ($componentsWithUpdateFile as $name => $filenames) { try { $warnings = array_merge($warnings, $this->update($name)); } catch (UpdaterErrorException $e) { $errors[] = $e->getMessage(); if ($name == 'core') { $coreError = true; break; } elseif (\Piwik\Plugin\Manager::getInstance()->isPluginActivated($name)) { \Piwik\Plugin\Manager::getInstance()->deactivatePlugin($name); $deactivatedPlugins[] = $name; } } } if (!$hasSuperUserAccess) { $currentAccess->setSuperUserAccess(false); } } Filesystem::deleteAllCacheOnUpdate(); ServerFilesGenerator::createHtAccessFiles(); $result = array( 'warnings' => $warnings, 'errors' => $errors, 'coreError' => $coreError, 'deactivatedPlugins' => $deactivatedPlugins ); /** * Triggered after Piwik has been updated. */ Piwik::postEvent('CoreUpdater.update.end'); return $result; }
php
public function updateComponents($componentsWithUpdateFile) { $warnings = array(); $errors = array(); $deactivatedPlugins = array(); $coreError = false; if (!empty($componentsWithUpdateFile)) { $currentAccess = Access::getInstance(); $hasSuperUserAccess = $currentAccess->hasSuperUserAccess(); if (!$hasSuperUserAccess) { $currentAccess->setSuperUserAccess(true); } // if error in any core update, show message + help message + EXIT // if errors in any plugins updates, show them on screen, disable plugins that errored + CONTINUE // if warning in any core update or in any plugins update, show message + CONTINUE // if no error or warning, success message + CONTINUE foreach ($componentsWithUpdateFile as $name => $filenames) { try { $warnings = array_merge($warnings, $this->update($name)); } catch (UpdaterErrorException $e) { $errors[] = $e->getMessage(); if ($name == 'core') { $coreError = true; break; } elseif (\Piwik\Plugin\Manager::getInstance()->isPluginActivated($name)) { \Piwik\Plugin\Manager::getInstance()->deactivatePlugin($name); $deactivatedPlugins[] = $name; } } } if (!$hasSuperUserAccess) { $currentAccess->setSuperUserAccess(false); } } Filesystem::deleteAllCacheOnUpdate(); ServerFilesGenerator::createHtAccessFiles(); $result = array( 'warnings' => $warnings, 'errors' => $errors, 'coreError' => $coreError, 'deactivatedPlugins' => $deactivatedPlugins ); /** * Triggered after Piwik has been updated. */ Piwik::postEvent('CoreUpdater.update.end'); return $result; }
[ "public", "function", "updateComponents", "(", "$", "componentsWithUpdateFile", ")", "{", "$", "warnings", "=", "array", "(", ")", ";", "$", "errors", "=", "array", "(", ")", ";", "$", "deactivatedPlugins", "=", "array", "(", ")", ";", "$", "coreError", "=", "false", ";", "if", "(", "!", "empty", "(", "$", "componentsWithUpdateFile", ")", ")", "{", "$", "currentAccess", "=", "Access", "::", "getInstance", "(", ")", ";", "$", "hasSuperUserAccess", "=", "$", "currentAccess", "->", "hasSuperUserAccess", "(", ")", ";", "if", "(", "!", "$", "hasSuperUserAccess", ")", "{", "$", "currentAccess", "->", "setSuperUserAccess", "(", "true", ")", ";", "}", "// if error in any core update, show message + help message + EXIT", "// if errors in any plugins updates, show them on screen, disable plugins that errored + CONTINUE", "// if warning in any core update or in any plugins update, show message + CONTINUE", "// if no error or warning, success message + CONTINUE", "foreach", "(", "$", "componentsWithUpdateFile", "as", "$", "name", "=>", "$", "filenames", ")", "{", "try", "{", "$", "warnings", "=", "array_merge", "(", "$", "warnings", ",", "$", "this", "->", "update", "(", "$", "name", ")", ")", ";", "}", "catch", "(", "UpdaterErrorException", "$", "e", ")", "{", "$", "errors", "[", "]", "=", "$", "e", "->", "getMessage", "(", ")", ";", "if", "(", "$", "name", "==", "'core'", ")", "{", "$", "coreError", "=", "true", ";", "break", ";", "}", "elseif", "(", "\\", "Piwik", "\\", "Plugin", "\\", "Manager", "::", "getInstance", "(", ")", "->", "isPluginActivated", "(", "$", "name", ")", ")", "{", "\\", "Piwik", "\\", "Plugin", "\\", "Manager", "::", "getInstance", "(", ")", "->", "deactivatePlugin", "(", "$", "name", ")", ";", "$", "deactivatedPlugins", "[", "]", "=", "$", "name", ";", "}", "}", "}", "if", "(", "!", "$", "hasSuperUserAccess", ")", "{", "$", "currentAccess", "->", "setSuperUserAccess", "(", "false", ")", ";", "}", "}", "Filesystem", "::", "deleteAllCacheOnUpdate", "(", ")", ";", "ServerFilesGenerator", "::", "createHtAccessFiles", "(", ")", ";", "$", "result", "=", "array", "(", "'warnings'", "=>", "$", "warnings", ",", "'errors'", "=>", "$", "errors", ",", "'coreError'", "=>", "$", "coreError", ",", "'deactivatedPlugins'", "=>", "$", "deactivatedPlugins", ")", ";", "/**\n * Triggered after Piwik has been updated.\n */", "Piwik", "::", "postEvent", "(", "'CoreUpdater.update.end'", ")", ";", "return", "$", "result", ";", "}" ]
Updates multiple components, while capturing & returning errors and warnings. @param string[] $componentsWithUpdateFile Component names mapped with arrays of update files. Same structure as the result of `getComponentsWithUpdateFile()`. @return array Information about the update process, including: * **warnings**: The list of warnings that occurred during the update process. * **errors**: The list of updater exceptions thrown during individual component updates. * **coreError**: True if an exception was thrown while updating core. * **deactivatedPlugins**: The list of plugins that were deactivated due to an error in the update process.
[ "Updates", "multiple", "components", "while", "capturing", "&", "returning", "errors", "and", "warnings", "." ]
72df150735664275a60a7861e468c6ff3b152a14
https://github.com/matomo-org/matomo/blob/72df150735664275a60a7861e468c6ff3b152a14/core/Updater.php#L454-L509
210,110
matomo-org/matomo
core/Updater.php
Updater.getComponentUpdates
public function getComponentUpdates() { $componentsToCheck = array( 'core' => Version::VERSION ); $manager = \Piwik\Plugin\Manager::getInstance(); $plugins = $manager->getLoadedPlugins(); foreach ($plugins as $pluginName => $plugin) { if ($manager->isPluginInstalled($pluginName)) { $componentsToCheck[$pluginName] = $plugin->getVersion(); } } $columnsVersions = $this->columnsUpdater->getAllVersions($this); foreach ($columnsVersions as $component => $version) { $componentsToCheck[$component] = $version; } $componentsWithUpdateFile = $this->getComponentsWithUpdateFile($componentsToCheck); if (count($componentsWithUpdateFile) == 0) { $this->columnsUpdater->onNoUpdateAvailable($columnsVersions); return null; } return $componentsWithUpdateFile; }
php
public function getComponentUpdates() { $componentsToCheck = array( 'core' => Version::VERSION ); $manager = \Piwik\Plugin\Manager::getInstance(); $plugins = $manager->getLoadedPlugins(); foreach ($plugins as $pluginName => $plugin) { if ($manager->isPluginInstalled($pluginName)) { $componentsToCheck[$pluginName] = $plugin->getVersion(); } } $columnsVersions = $this->columnsUpdater->getAllVersions($this); foreach ($columnsVersions as $component => $version) { $componentsToCheck[$component] = $version; } $componentsWithUpdateFile = $this->getComponentsWithUpdateFile($componentsToCheck); if (count($componentsWithUpdateFile) == 0) { $this->columnsUpdater->onNoUpdateAvailable($columnsVersions); return null; } return $componentsWithUpdateFile; }
[ "public", "function", "getComponentUpdates", "(", ")", "{", "$", "componentsToCheck", "=", "array", "(", "'core'", "=>", "Version", "::", "VERSION", ")", ";", "$", "manager", "=", "\\", "Piwik", "\\", "Plugin", "\\", "Manager", "::", "getInstance", "(", ")", ";", "$", "plugins", "=", "$", "manager", "->", "getLoadedPlugins", "(", ")", ";", "foreach", "(", "$", "plugins", "as", "$", "pluginName", "=>", "$", "plugin", ")", "{", "if", "(", "$", "manager", "->", "isPluginInstalled", "(", "$", "pluginName", ")", ")", "{", "$", "componentsToCheck", "[", "$", "pluginName", "]", "=", "$", "plugin", "->", "getVersion", "(", ")", ";", "}", "}", "$", "columnsVersions", "=", "$", "this", "->", "columnsUpdater", "->", "getAllVersions", "(", "$", "this", ")", ";", "foreach", "(", "$", "columnsVersions", "as", "$", "component", "=>", "$", "version", ")", "{", "$", "componentsToCheck", "[", "$", "component", "]", "=", "$", "version", ";", "}", "$", "componentsWithUpdateFile", "=", "$", "this", "->", "getComponentsWithUpdateFile", "(", "$", "componentsToCheck", ")", ";", "if", "(", "count", "(", "$", "componentsWithUpdateFile", ")", "==", "0", ")", "{", "$", "this", "->", "columnsUpdater", "->", "onNoUpdateAvailable", "(", "$", "columnsVersions", ")", ";", "return", "null", ";", "}", "return", "$", "componentsWithUpdateFile", ";", "}" ]
Returns any updates that should occur for core and all plugins that are both loaded and installed. Also includes updates required for dimensions. @return string[]|null Returns the result of `getComponentsWithUpdateFile()`.
[ "Returns", "any", "updates", "that", "should", "occur", "for", "core", "and", "all", "plugins", "that", "are", "both", "loaded", "and", "installed", ".", "Also", "includes", "updates", "required", "for", "dimensions", "." ]
72df150735664275a60a7861e468c6ff3b152a14
https://github.com/matomo-org/matomo/blob/72df150735664275a60a7861e468c6ff3b152a14/core/Updater.php#L517-L545
210,111
matomo-org/matomo
core/Updater.php
Updater.executeMigrations
public function executeMigrations($file, $migrations) { foreach ($migrations as $index => $migration) { $migration = $this->keepBcForOldMigrationQueryFormat($index, $migration); $this->executeMigration($file, $migration); } }
php
public function executeMigrations($file, $migrations) { foreach ($migrations as $index => $migration) { $migration = $this->keepBcForOldMigrationQueryFormat($index, $migration); $this->executeMigration($file, $migration); } }
[ "public", "function", "executeMigrations", "(", "$", "file", ",", "$", "migrations", ")", "{", "foreach", "(", "$", "migrations", "as", "$", "index", "=>", "$", "migration", ")", "{", "$", "migration", "=", "$", "this", "->", "keepBcForOldMigrationQueryFormat", "(", "$", "index", ",", "$", "migration", ")", ";", "$", "this", "->", "executeMigration", "(", "$", "file", ",", "$", "migration", ")", ";", "}", "}" ]
Execute multiple migration queries from a single Update file. @param string $file The path to the Updates file. @param Migration[] $migrations An array of migrations @api
[ "Execute", "multiple", "migration", "queries", "from", "a", "single", "Update", "file", "." ]
72df150735664275a60a7861e468c6ff3b152a14
https://github.com/matomo-org/matomo/blob/72df150735664275a60a7861e468c6ff3b152a14/core/Updater.php#L562-L568
210,112
matomo-org/matomo
core/Settings/Settings.php
Settings.addSetting
public function addSetting(Setting $setting) { $name = $setting->getName(); if (isset($this->settings[$name])) { throw new \Exception(sprintf('A setting with name "%s" does already exist for plugin "%s"', $name, $this->pluginName)); } $this->settings[$name] = $setting; }
php
public function addSetting(Setting $setting) { $name = $setting->getName(); if (isset($this->settings[$name])) { throw new \Exception(sprintf('A setting with name "%s" does already exist for plugin "%s"', $name, $this->pluginName)); } $this->settings[$name] = $setting; }
[ "public", "function", "addSetting", "(", "Setting", "$", "setting", ")", "{", "$", "name", "=", "$", "setting", "->", "getName", "(", ")", ";", "if", "(", "isset", "(", "$", "this", "->", "settings", "[", "$", "name", "]", ")", ")", "{", "throw", "new", "\\", "Exception", "(", "sprintf", "(", "'A setting with name \"%s\" does already exist for plugin \"%s\"'", ",", "$", "name", ",", "$", "this", "->", "pluginName", ")", ")", ";", "}", "$", "this", "->", "settings", "[", "$", "name", "]", "=", "$", "setting", ";", "}" ]
Adds a new setting to the settings container. @param Setting $setting @throws \Exception If there is a setting with the same name that already exists. If the name contains non-alphanumeric characters.
[ "Adds", "a", "new", "setting", "to", "the", "settings", "container", "." ]
72df150735664275a60a7861e468c6ff3b152a14
https://github.com/matomo-org/matomo/blob/72df150735664275a60a7861e468c6ff3b152a14/core/Settings/Settings.php#L102-L111
210,113
matomo-org/matomo
core/Plugin/Controller.php
Controller.getDateParameterInTimezone
protected function getDateParameterInTimezone($date, $timezone) { $timezoneToUse = null; // if the requested date is not YYYY-MM-DD, we need to ensure // it is relative to the website's timezone if (in_array($date, array('today', 'yesterday'))) { // today is at midnight; we really want to get the time now, so that // * if the website is UTC+12 and it is 5PM now in UTC, the calendar will allow to select the UTC "tomorrow" // * if the website is UTC-12 and it is 5AM now in UTC, the calendar will allow to select the UTC "yesterday" if ($date == 'today') { $date = 'now'; } elseif ($date == 'yesterday') { $date = 'yesterdaySameTime'; } $timezoneToUse = $timezone; } return Date::factory($date, $timezoneToUse); }
php
protected function getDateParameterInTimezone($date, $timezone) { $timezoneToUse = null; // if the requested date is not YYYY-MM-DD, we need to ensure // it is relative to the website's timezone if (in_array($date, array('today', 'yesterday'))) { // today is at midnight; we really want to get the time now, so that // * if the website is UTC+12 and it is 5PM now in UTC, the calendar will allow to select the UTC "tomorrow" // * if the website is UTC-12 and it is 5AM now in UTC, the calendar will allow to select the UTC "yesterday" if ($date == 'today') { $date = 'now'; } elseif ($date == 'yesterday') { $date = 'yesterdaySameTime'; } $timezoneToUse = $timezone; } return Date::factory($date, $timezoneToUse); }
[ "protected", "function", "getDateParameterInTimezone", "(", "$", "date", ",", "$", "timezone", ")", "{", "$", "timezoneToUse", "=", "null", ";", "// if the requested date is not YYYY-MM-DD, we need to ensure", "// it is relative to the website's timezone", "if", "(", "in_array", "(", "$", "date", ",", "array", "(", "'today'", ",", "'yesterday'", ")", ")", ")", "{", "// today is at midnight; we really want to get the time now, so that", "// * if the website is UTC+12 and it is 5PM now in UTC, the calendar will allow to select the UTC \"tomorrow\"", "// * if the website is UTC-12 and it is 5AM now in UTC, the calendar will allow to select the UTC \"yesterday\"", "if", "(", "$", "date", "==", "'today'", ")", "{", "$", "date", "=", "'now'", ";", "}", "elseif", "(", "$", "date", "==", "'yesterday'", ")", "{", "$", "date", "=", "'yesterdaySameTime'", ";", "}", "$", "timezoneToUse", "=", "$", "timezone", ";", "}", "return", "Date", "::", "factory", "(", "$", "date", ",", "$", "timezoneToUse", ")", ";", "}" ]
Helper method that converts `"today"` or `"yesterday"` to the specified timezone. If the date is absolute, ie. YYYY-MM-DD, it will not be converted to the timezone. @param string $date `'today'`, `'yesterday'`, `'YYYY-MM-DD'` @param string $timezone The timezone to use. @return Date @api
[ "Helper", "method", "that", "converts", "today", "or", "yesterday", "to", "the", "specified", "timezone", ".", "If", "the", "date", "is", "absolute", "ie", ".", "YYYY", "-", "MM", "-", "DD", "it", "will", "not", "be", "converted", "to", "the", "timezone", "." ]
72df150735664275a60a7861e468c6ff3b152a14
https://github.com/matomo-org/matomo/blob/72df150735664275a60a7861e468c6ff3b152a14/core/Plugin/Controller.php#L152-L169
210,114
matomo-org/matomo
core/Plugin/Controller.php
Controller.setDate
protected function setDate(Date $date) { $this->date = $date; $this->strDate = $date->toString(); }
php
protected function setDate(Date $date) { $this->date = $date; $this->strDate = $date->toString(); }
[ "protected", "function", "setDate", "(", "Date", "$", "date", ")", "{", "$", "this", "->", "date", "=", "$", "date", ";", "$", "this", "->", "strDate", "=", "$", "date", "->", "toString", "(", ")", ";", "}" ]
Sets the date to be used by all other methods in the controller. If the date has to be modified, this method should be called just after construction. @param Date $date The new Date. @return void @api
[ "Sets", "the", "date", "to", "be", "used", "by", "all", "other", "methods", "in", "the", "controller", ".", "If", "the", "date", "has", "to", "be", "modified", "this", "method", "should", "be", "called", "just", "after", "construction", "." ]
72df150735664275a60a7861e468c6ff3b152a14
https://github.com/matomo-org/matomo/blob/72df150735664275a60a7861e468c6ff3b152a14/core/Plugin/Controller.php#L180-L184
210,115
matomo-org/matomo
core/Plugin/Controller.php
Controller.renderReport
protected function renderReport($apiAction, $controllerAction = false) { if (empty($controllerAction) && is_string($apiAction)) { $report = ReportsProvider::factory($this->pluginName, $apiAction); if (!empty($report)) { $apiAction = $report; } } if ($apiAction instanceof Report) { $this->checkSitePermission(); $apiAction->checkIsEnabled(); return $apiAction->render(); } $pluginName = $this->pluginName; /** @var Proxy $apiProxy */ $apiProxy = Proxy::getInstance(); if (!$apiProxy->isExistingApiAction($pluginName, $apiAction)) { throw new \Exception("Invalid action name '$apiAction' for '$pluginName' plugin."); } $apiAction = $apiProxy->buildApiActionName($pluginName, $apiAction); if ($controllerAction !== false) { $controllerAction = $pluginName . '.' . $controllerAction; } $view = ViewDataTableFactory::build(null, $apiAction, $controllerAction); $rendered = $view->render(); return $rendered; }
php
protected function renderReport($apiAction, $controllerAction = false) { if (empty($controllerAction) && is_string($apiAction)) { $report = ReportsProvider::factory($this->pluginName, $apiAction); if (!empty($report)) { $apiAction = $report; } } if ($apiAction instanceof Report) { $this->checkSitePermission(); $apiAction->checkIsEnabled(); return $apiAction->render(); } $pluginName = $this->pluginName; /** @var Proxy $apiProxy */ $apiProxy = Proxy::getInstance(); if (!$apiProxy->isExistingApiAction($pluginName, $apiAction)) { throw new \Exception("Invalid action name '$apiAction' for '$pluginName' plugin."); } $apiAction = $apiProxy->buildApiActionName($pluginName, $apiAction); if ($controllerAction !== false) { $controllerAction = $pluginName . '.' . $controllerAction; } $view = ViewDataTableFactory::build(null, $apiAction, $controllerAction); $rendered = $view->render(); return $rendered; }
[ "protected", "function", "renderReport", "(", "$", "apiAction", ",", "$", "controllerAction", "=", "false", ")", "{", "if", "(", "empty", "(", "$", "controllerAction", ")", "&&", "is_string", "(", "$", "apiAction", ")", ")", "{", "$", "report", "=", "ReportsProvider", "::", "factory", "(", "$", "this", "->", "pluginName", ",", "$", "apiAction", ")", ";", "if", "(", "!", "empty", "(", "$", "report", ")", ")", "{", "$", "apiAction", "=", "$", "report", ";", "}", "}", "if", "(", "$", "apiAction", "instanceof", "Report", ")", "{", "$", "this", "->", "checkSitePermission", "(", ")", ";", "$", "apiAction", "->", "checkIsEnabled", "(", ")", ";", "return", "$", "apiAction", "->", "render", "(", ")", ";", "}", "$", "pluginName", "=", "$", "this", "->", "pluginName", ";", "/** @var Proxy $apiProxy */", "$", "apiProxy", "=", "Proxy", "::", "getInstance", "(", ")", ";", "if", "(", "!", "$", "apiProxy", "->", "isExistingApiAction", "(", "$", "pluginName", ",", "$", "apiAction", ")", ")", "{", "throw", "new", "\\", "Exception", "(", "\"Invalid action name '$apiAction' for '$pluginName' plugin.\"", ")", ";", "}", "$", "apiAction", "=", "$", "apiProxy", "->", "buildApiActionName", "(", "$", "pluginName", ",", "$", "apiAction", ")", ";", "if", "(", "$", "controllerAction", "!==", "false", ")", "{", "$", "controllerAction", "=", "$", "pluginName", ".", "'.'", ".", "$", "controllerAction", ";", "}", "$", "view", "=", "ViewDataTableFactory", "::", "build", "(", "null", ",", "$", "apiAction", ",", "$", "controllerAction", ")", ";", "$", "rendered", "=", "$", "view", "->", "render", "(", ")", ";", "return", "$", "rendered", ";", "}" ]
Convenience method that creates and renders a ViewDataTable for a API method. @param string|\Piwik\Plugin\Report $apiAction The name of the API action (eg, `'getResolution'`) or an instance of an report. @param bool $controllerAction The name of the Controller action name that is rendering the report. Defaults to the `$apiAction`. @param bool $fetch If `true`, the rendered string is returned, if `false` it is `echo`'d. @throws \Exception if `$pluginName` is not an existing plugin or if `$apiAction` is not an existing method of the plugin's API. @return string|void See `$fetch`. @api
[ "Convenience", "method", "that", "creates", "and", "renders", "a", "ViewDataTable", "for", "a", "API", "method", "." ]
72df150735664275a60a7861e468c6ff3b152a14
https://github.com/matomo-org/matomo/blob/72df150735664275a60a7861e468c6ff3b152a14/core/Plugin/Controller.php#L315-L351
210,116
matomo-org/matomo
core/Plugin/Controller.php
Controller.setMinDateView
protected function setMinDateView(Date $minDate, $view) { $view->minDateYear = $minDate->toString('Y'); $view->minDateMonth = $minDate->toString('m'); $view->minDateDay = $minDate->toString('d'); }
php
protected function setMinDateView(Date $minDate, $view) { $view->minDateYear = $minDate->toString('Y'); $view->minDateMonth = $minDate->toString('m'); $view->minDateDay = $minDate->toString('d'); }
[ "protected", "function", "setMinDateView", "(", "Date", "$", "minDate", ",", "$", "view", ")", "{", "$", "view", "->", "minDateYear", "=", "$", "minDate", "->", "toString", "(", "'Y'", ")", ";", "$", "view", "->", "minDateMonth", "=", "$", "minDate", "->", "toString", "(", "'m'", ")", ";", "$", "view", "->", "minDateDay", "=", "$", "minDate", "->", "toString", "(", "'d'", ")", ";", "}" ]
Sets the first date available in the period selector's calendar. @param Date $minDate The min date. @param View $view The view that contains the period selector. @api
[ "Sets", "the", "first", "date", "available", "in", "the", "period", "selector", "s", "calendar", "." ]
72df150735664275a60a7861e468c6ff3b152a14
https://github.com/matomo-org/matomo/blob/72df150735664275a60a7861e468c6ff3b152a14/core/Plugin/Controller.php#L534-L539
210,117
matomo-org/matomo
core/Plugin/Controller.php
Controller.setBasicVariablesNoneAdminView
protected function setBasicVariablesNoneAdminView($view) { $view->clientSideConfig = PiwikConfig::getInstance()->getClientSideOptions(); $view->isSuperUser = Access::getInstance()->hasSuperUserAccess(); $view->hasSomeAdminAccess = Piwik::isUserHasSomeAdminAccess(); $view->hasSomeViewAccess = Piwik::isUserHasSomeViewAccess(); $view->isUserIsAnonymous = Piwik::isUserIsAnonymous(); $view->hasSuperUserAccess = Piwik::hasUserSuperUserAccess(); if (!Piwik::isUserIsAnonymous()) { $view->emailSuperUser = implode(',', Piwik::getAllSuperUserAccessEmailAddresses()); } $capabilities = array(); if ($this->idSite && $this->site) { $capabilityProvider = StaticContainer::get(Access\CapabilitiesProvider::class); foreach ($capabilityProvider->getAllCapabilities() as $capability) { if (Piwik::isUserHasCapability($this->idSite, $capability->getId())) { $capabilities[] = $capability->getId(); } } } $view->userCapabilities = $capabilities; $this->addCustomLogoInfo($view); $view->logoHeader = \Piwik\Plugins\API\API::getInstance()->getHeaderLogoUrl(); $view->logoLarge = \Piwik\Plugins\API\API::getInstance()->getLogoUrl(); $view->logoSVG = \Piwik\Plugins\API\API::getInstance()->getSVGLogoUrl(); $view->hasSVGLogo = \Piwik\Plugins\API\API::getInstance()->hasSVGLogo(); $view->superUserEmails = implode(',', Piwik::getAllSuperUserAccessEmailAddresses()); $view->themeStyles = ThemeStyles::get(); $general = PiwikConfig::getInstance()->General; $view->enableFrames = $general['enable_framed_pages'] || (isset($general['enable_framed_logins']) && $general['enable_framed_logins']); $embeddedAsIframe = (Common::getRequestVar('module', '', 'string') == 'Widgetize'); if (!$view->enableFrames && !$embeddedAsIframe) { $view->setXFrameOptions('sameorigin'); } self::setHostValidationVariablesView($view); }
php
protected function setBasicVariablesNoneAdminView($view) { $view->clientSideConfig = PiwikConfig::getInstance()->getClientSideOptions(); $view->isSuperUser = Access::getInstance()->hasSuperUserAccess(); $view->hasSomeAdminAccess = Piwik::isUserHasSomeAdminAccess(); $view->hasSomeViewAccess = Piwik::isUserHasSomeViewAccess(); $view->isUserIsAnonymous = Piwik::isUserIsAnonymous(); $view->hasSuperUserAccess = Piwik::hasUserSuperUserAccess(); if (!Piwik::isUserIsAnonymous()) { $view->emailSuperUser = implode(',', Piwik::getAllSuperUserAccessEmailAddresses()); } $capabilities = array(); if ($this->idSite && $this->site) { $capabilityProvider = StaticContainer::get(Access\CapabilitiesProvider::class); foreach ($capabilityProvider->getAllCapabilities() as $capability) { if (Piwik::isUserHasCapability($this->idSite, $capability->getId())) { $capabilities[] = $capability->getId(); } } } $view->userCapabilities = $capabilities; $this->addCustomLogoInfo($view); $view->logoHeader = \Piwik\Plugins\API\API::getInstance()->getHeaderLogoUrl(); $view->logoLarge = \Piwik\Plugins\API\API::getInstance()->getLogoUrl(); $view->logoSVG = \Piwik\Plugins\API\API::getInstance()->getSVGLogoUrl(); $view->hasSVGLogo = \Piwik\Plugins\API\API::getInstance()->hasSVGLogo(); $view->superUserEmails = implode(',', Piwik::getAllSuperUserAccessEmailAddresses()); $view->themeStyles = ThemeStyles::get(); $general = PiwikConfig::getInstance()->General; $view->enableFrames = $general['enable_framed_pages'] || (isset($general['enable_framed_logins']) && $general['enable_framed_logins']); $embeddedAsIframe = (Common::getRequestVar('module', '', 'string') == 'Widgetize'); if (!$view->enableFrames && !$embeddedAsIframe) { $view->setXFrameOptions('sameorigin'); } self::setHostValidationVariablesView($view); }
[ "protected", "function", "setBasicVariablesNoneAdminView", "(", "$", "view", ")", "{", "$", "view", "->", "clientSideConfig", "=", "PiwikConfig", "::", "getInstance", "(", ")", "->", "getClientSideOptions", "(", ")", ";", "$", "view", "->", "isSuperUser", "=", "Access", "::", "getInstance", "(", ")", "->", "hasSuperUserAccess", "(", ")", ";", "$", "view", "->", "hasSomeAdminAccess", "=", "Piwik", "::", "isUserHasSomeAdminAccess", "(", ")", ";", "$", "view", "->", "hasSomeViewAccess", "=", "Piwik", "::", "isUserHasSomeViewAccess", "(", ")", ";", "$", "view", "->", "isUserIsAnonymous", "=", "Piwik", "::", "isUserIsAnonymous", "(", ")", ";", "$", "view", "->", "hasSuperUserAccess", "=", "Piwik", "::", "hasUserSuperUserAccess", "(", ")", ";", "if", "(", "!", "Piwik", "::", "isUserIsAnonymous", "(", ")", ")", "{", "$", "view", "->", "emailSuperUser", "=", "implode", "(", "','", ",", "Piwik", "::", "getAllSuperUserAccessEmailAddresses", "(", ")", ")", ";", "}", "$", "capabilities", "=", "array", "(", ")", ";", "if", "(", "$", "this", "->", "idSite", "&&", "$", "this", "->", "site", ")", "{", "$", "capabilityProvider", "=", "StaticContainer", "::", "get", "(", "Access", "\\", "CapabilitiesProvider", "::", "class", ")", ";", "foreach", "(", "$", "capabilityProvider", "->", "getAllCapabilities", "(", ")", "as", "$", "capability", ")", "{", "if", "(", "Piwik", "::", "isUserHasCapability", "(", "$", "this", "->", "idSite", ",", "$", "capability", "->", "getId", "(", ")", ")", ")", "{", "$", "capabilities", "[", "]", "=", "$", "capability", "->", "getId", "(", ")", ";", "}", "}", "}", "$", "view", "->", "userCapabilities", "=", "$", "capabilities", ";", "$", "this", "->", "addCustomLogoInfo", "(", "$", "view", ")", ";", "$", "view", "->", "logoHeader", "=", "\\", "Piwik", "\\", "Plugins", "\\", "API", "\\", "API", "::", "getInstance", "(", ")", "->", "getHeaderLogoUrl", "(", ")", ";", "$", "view", "->", "logoLarge", "=", "\\", "Piwik", "\\", "Plugins", "\\", "API", "\\", "API", "::", "getInstance", "(", ")", "->", "getLogoUrl", "(", ")", ";", "$", "view", "->", "logoSVG", "=", "\\", "Piwik", "\\", "Plugins", "\\", "API", "\\", "API", "::", "getInstance", "(", ")", "->", "getSVGLogoUrl", "(", ")", ";", "$", "view", "->", "hasSVGLogo", "=", "\\", "Piwik", "\\", "Plugins", "\\", "API", "\\", "API", "::", "getInstance", "(", ")", "->", "hasSVGLogo", "(", ")", ";", "$", "view", "->", "superUserEmails", "=", "implode", "(", "','", ",", "Piwik", "::", "getAllSuperUserAccessEmailAddresses", "(", ")", ")", ";", "$", "view", "->", "themeStyles", "=", "ThemeStyles", "::", "get", "(", ")", ";", "$", "general", "=", "PiwikConfig", "::", "getInstance", "(", ")", "->", "General", ";", "$", "view", "->", "enableFrames", "=", "$", "general", "[", "'enable_framed_pages'", "]", "||", "(", "isset", "(", "$", "general", "[", "'enable_framed_logins'", "]", ")", "&&", "$", "general", "[", "'enable_framed_logins'", "]", ")", ";", "$", "embeddedAsIframe", "=", "(", "Common", "::", "getRequestVar", "(", "'module'", ",", "''", ",", "'string'", ")", "==", "'Widgetize'", ")", ";", "if", "(", "!", "$", "view", "->", "enableFrames", "&&", "!", "$", "embeddedAsIframe", ")", "{", "$", "view", "->", "setXFrameOptions", "(", "'sameorigin'", ")", ";", "}", "self", "::", "setHostValidationVariablesView", "(", "$", "view", ")", ";", "}" ]
Needed when a controller extends ControllerAdmin but you don't want to call the controller admin basic variables view. Solves a problem when a controller has regular controller and admin controller views. @param View $view
[ "Needed", "when", "a", "controller", "extends", "ControllerAdmin", "but", "you", "don", "t", "want", "to", "call", "the", "controller", "admin", "basic", "variables", "view", ".", "Solves", "a", "problem", "when", "a", "controller", "has", "regular", "controller", "and", "admin", "controller", "views", "." ]
72df150735664275a60a7861e468c6ff3b152a14
https://github.com/matomo-org/matomo/blob/72df150735664275a60a7861e468c6ff3b152a14/core/Plugin/Controller.php#L676-L719
210,118
matomo-org/matomo
core/Plugin/Controller.php
Controller.checkTokenInUrl
protected function checkTokenInUrl() { $tokenRequest = Common::getRequestVar('token_auth', false); $tokenUser = Piwik::getCurrentUserTokenAuth(); if (empty($tokenRequest) && empty($tokenUser)) { return; // UI tests } if ($tokenRequest !== $tokenUser) { throw new NoAccessException(Piwik::translate('General_ExceptionInvalidToken')); } }
php
protected function checkTokenInUrl() { $tokenRequest = Common::getRequestVar('token_auth', false); $tokenUser = Piwik::getCurrentUserTokenAuth(); if (empty($tokenRequest) && empty($tokenUser)) { return; // UI tests } if ($tokenRequest !== $tokenUser) { throw new NoAccessException(Piwik::translate('General_ExceptionInvalidToken')); } }
[ "protected", "function", "checkTokenInUrl", "(", ")", "{", "$", "tokenRequest", "=", "Common", "::", "getRequestVar", "(", "'token_auth'", ",", "false", ")", ";", "$", "tokenUser", "=", "Piwik", "::", "getCurrentUserTokenAuth", "(", ")", ";", "if", "(", "empty", "(", "$", "tokenRequest", ")", "&&", "empty", "(", "$", "tokenUser", ")", ")", "{", "return", ";", "// UI tests", "}", "if", "(", "$", "tokenRequest", "!==", "$", "tokenUser", ")", "{", "throw", "new", "NoAccessException", "(", "Piwik", "::", "translate", "(", "'General_ExceptionInvalidToken'", ")", ")", ";", "}", "}" ]
Checks that the token_auth in the URL matches the currently logged-in user's token_auth. This is a protection against CSRF and should be used in all controller methods that modify Piwik or any user settings. If called from JavaScript by using the `ajaxHelper` you have to call `ajaxHelper.withTokenInUrl();` before `ajaxHandler.send();` to send the token along with the request. **The token_auth should never appear in the browser's address bar.** @throws \Piwik\NoAccessException If the token doesn't match. @api
[ "Checks", "that", "the", "token_auth", "in", "the", "URL", "matches", "the", "currently", "logged", "-", "in", "user", "s", "token_auth", "." ]
72df150735664275a60a7861e468c6ff3b152a14
https://github.com/matomo-org/matomo/blob/72df150735664275a60a7861e468c6ff3b152a14/core/Plugin/Controller.php#L940-L952
210,119
matomo-org/matomo
core/Plugin/Controller.php
Controller.getPrettyDate
public static function getPrettyDate($date, $period) { return self::getCalendarPrettyDate(Period\Factory::build($period, Date::factory($date))); }
php
public static function getPrettyDate($date, $period) { return self::getCalendarPrettyDate(Period\Factory::build($period, Date::factory($date))); }
[ "public", "static", "function", "getPrettyDate", "(", "$", "date", ",", "$", "period", ")", "{", "return", "self", "::", "getCalendarPrettyDate", "(", "Period", "\\", "Factory", "::", "build", "(", "$", "period", ",", "Date", "::", "factory", "(", "$", "date", ")", ")", ")", ";", "}" ]
Returns the pretty date representation @param $date string @param $period string @return string Pretty date
[ "Returns", "the", "pretty", "date", "representation" ]
72df150735664275a60a7861e468c6ff3b152a14
https://github.com/matomo-org/matomo/blob/72df150735664275a60a7861e468c6ff3b152a14/core/Plugin/Controller.php#L979-L982
210,120
matomo-org/matomo
core/DataTable/Filter/CalculateEvolutionFilter.php
CalculateEvolutionFilter.getDividend
protected function getDividend($row) { $currentValue = $row->getColumn($this->columnValueToRead); // if the site this is for doesn't support ecommerce & this is for the revenue_evolution column, // we don't add the new column if ($currentValue === false && $this->isRevenueEvolution && !Site::isEcommerceEnabledFor($row->getColumn('label')) ) { return false; } $pastRow = $this->getPastRowFromCurrent($row); if ($pastRow) { $pastValue = $pastRow->getColumn($this->columnValueToRead); } else { $pastValue = 0; } return $currentValue - $pastValue; }
php
protected function getDividend($row) { $currentValue = $row->getColumn($this->columnValueToRead); // if the site this is for doesn't support ecommerce & this is for the revenue_evolution column, // we don't add the new column if ($currentValue === false && $this->isRevenueEvolution && !Site::isEcommerceEnabledFor($row->getColumn('label')) ) { return false; } $pastRow = $this->getPastRowFromCurrent($row); if ($pastRow) { $pastValue = $pastRow->getColumn($this->columnValueToRead); } else { $pastValue = 0; } return $currentValue - $pastValue; }
[ "protected", "function", "getDividend", "(", "$", "row", ")", "{", "$", "currentValue", "=", "$", "row", "->", "getColumn", "(", "$", "this", "->", "columnValueToRead", ")", ";", "// if the site this is for doesn't support ecommerce & this is for the revenue_evolution column,", "// we don't add the new column", "if", "(", "$", "currentValue", "===", "false", "&&", "$", "this", "->", "isRevenueEvolution", "&&", "!", "Site", "::", "isEcommerceEnabledFor", "(", "$", "row", "->", "getColumn", "(", "'label'", ")", ")", ")", "{", "return", "false", ";", "}", "$", "pastRow", "=", "$", "this", "->", "getPastRowFromCurrent", "(", "$", "row", ")", ";", "if", "(", "$", "pastRow", ")", "{", "$", "pastValue", "=", "$", "pastRow", "->", "getColumn", "(", "$", "this", "->", "columnValueToRead", ")", ";", "}", "else", "{", "$", "pastValue", "=", "0", ";", "}", "return", "$", "currentValue", "-", "$", "pastValue", ";", "}" ]
Returns the difference between the column in the specific row and its sister column in the past DataTable. @param Row $row @return int|float
[ "Returns", "the", "difference", "between", "the", "column", "in", "the", "specific", "row", "and", "its", "sister", "column", "in", "the", "past", "DataTable", "." ]
72df150735664275a60a7861e468c6ff3b152a14
https://github.com/matomo-org/matomo/blob/72df150735664275a60a7861e468c6ff3b152a14/core/DataTable/Filter/CalculateEvolutionFilter.php#L73-L94
210,121
matomo-org/matomo
core/DataTable/Filter/CalculateEvolutionFilter.php
CalculateEvolutionFilter.formatValue
protected function formatValue($value, $divisor) { $value = self::getPercentageValue($value, $divisor, $this->quotientPrecision); $value = self::appendPercentSign($value); $value = Common::forceDotAsSeparatorForDecimalPoint($value); return $value; }
php
protected function formatValue($value, $divisor) { $value = self::getPercentageValue($value, $divisor, $this->quotientPrecision); $value = self::appendPercentSign($value); $value = Common::forceDotAsSeparatorForDecimalPoint($value); return $value; }
[ "protected", "function", "formatValue", "(", "$", "value", ",", "$", "divisor", ")", "{", "$", "value", "=", "self", "::", "getPercentageValue", "(", "$", "value", ",", "$", "divisor", ",", "$", "this", "->", "quotientPrecision", ")", ";", "$", "value", "=", "self", "::", "appendPercentSign", "(", "$", "value", ")", ";", "$", "value", "=", "Common", "::", "forceDotAsSeparatorForDecimalPoint", "(", "$", "value", ")", ";", "return", "$", "value", ";", "}" ]
Calculates and formats a quotient based on a divisor and dividend. Unlike ColumnCallbackAddColumnPercentage's, version of this method, this method will return 100% if the past value of a metric is 0, and the current value is not 0. For a value representative of an evolution, this makes sense. @param int|float $value The dividend. @param int|float $divisor @return string
[ "Calculates", "and", "formats", "a", "quotient", "based", "on", "a", "divisor", "and", "dividend", "." ]
72df150735664275a60a7861e468c6ff3b152a14
https://github.com/matomo-org/matomo/blob/72df150735664275a60a7861e468c6ff3b152a14/core/DataTable/Filter/CalculateEvolutionFilter.php#L125-L133
210,122
matomo-org/matomo
core/DataTable/Filter/CalculateEvolutionFilter.php
CalculateEvolutionFilter.calculate
public static function calculate($currentValue, $pastValue, $quotientPrecision = 0, $appendPercentSign = true) { $number = self::getPercentageValue($currentValue - $pastValue, $pastValue, $quotientPrecision); if ($appendPercentSign) { return NumberFormatter::getInstance()->formatPercent($number, $quotientPrecision); } return NumberFormatter::getInstance()->format($number, $quotientPrecision); }
php
public static function calculate($currentValue, $pastValue, $quotientPrecision = 0, $appendPercentSign = true) { $number = self::getPercentageValue($currentValue - $pastValue, $pastValue, $quotientPrecision); if ($appendPercentSign) { return NumberFormatter::getInstance()->formatPercent($number, $quotientPrecision); } return NumberFormatter::getInstance()->format($number, $quotientPrecision); }
[ "public", "static", "function", "calculate", "(", "$", "currentValue", ",", "$", "pastValue", ",", "$", "quotientPrecision", "=", "0", ",", "$", "appendPercentSign", "=", "true", ")", "{", "$", "number", "=", "self", "::", "getPercentageValue", "(", "$", "currentValue", "-", "$", "pastValue", ",", "$", "pastValue", ",", "$", "quotientPrecision", ")", ";", "if", "(", "$", "appendPercentSign", ")", "{", "return", "NumberFormatter", "::", "getInstance", "(", ")", "->", "formatPercent", "(", "$", "number", ",", "$", "quotientPrecision", ")", ";", "}", "return", "NumberFormatter", "::", "getInstance", "(", ")", "->", "format", "(", "$", "number", ",", "$", "quotientPrecision", ")", ";", "}" ]
Calculates the evolution percentage for two arbitrary values. @param float|int $currentValue The current metric value. @param float|int $pastValue The value of the metric in the past. We measure the % change from this value to $currentValue. @param float|int $quotientPrecision The quotient precision to round to. @param bool $appendPercentSign Whether to append a '%' sign to the end of the number or not. @return string The evolution percent, eg `'15%'`.
[ "Calculates", "the", "evolution", "percentage", "for", "two", "arbitrary", "values", "." ]
72df150735664275a60a7861e468c6ff3b152a14
https://github.com/matomo-org/matomo/blob/72df150735664275a60a7861e468c6ff3b152a14/core/DataTable/Filter/CalculateEvolutionFilter.php#L157-L165
210,123
matomo-org/matomo
core/DataTable/Filter/CalculateEvolutionFilter.php
CalculateEvolutionFilter.getPercentageValue
private static function getPercentageValue($value, $divisor, $quotientPrecision) { if ($value == 0) { $evolution = 0; } elseif ($divisor == 0) { $evolution = 100; } else { $evolution = ($value / $divisor) * 100; } $evolution = round($evolution, $quotientPrecision); return $evolution; }
php
private static function getPercentageValue($value, $divisor, $quotientPrecision) { if ($value == 0) { $evolution = 0; } elseif ($divisor == 0) { $evolution = 100; } else { $evolution = ($value / $divisor) * 100; } $evolution = round($evolution, $quotientPrecision); return $evolution; }
[ "private", "static", "function", "getPercentageValue", "(", "$", "value", ",", "$", "divisor", ",", "$", "quotientPrecision", ")", "{", "if", "(", "$", "value", "==", "0", ")", "{", "$", "evolution", "=", "0", ";", "}", "elseif", "(", "$", "divisor", "==", "0", ")", "{", "$", "evolution", "=", "100", ";", "}", "else", "{", "$", "evolution", "=", "(", "$", "value", "/", "$", "divisor", ")", "*", "100", ";", "}", "$", "evolution", "=", "round", "(", "$", "evolution", ",", "$", "quotientPrecision", ")", ";", "return", "$", "evolution", ";", "}" ]
Returns an evolution percent based on a value & divisor.
[ "Returns", "an", "evolution", "percent", "based", "on", "a", "value", "&", "divisor", "." ]
72df150735664275a60a7861e468c6ff3b152a14
https://github.com/matomo-org/matomo/blob/72df150735664275a60a7861e468c6ff3b152a14/core/DataTable/Filter/CalculateEvolutionFilter.php#L184-L196
210,124
matomo-org/matomo
libs/HTML/QuickForm2/Rule/Callback.php
HTML_QuickForm2_Rule_Callback.setConfig
public function setConfig($config) { if (!is_array($config) || !isset($config['callback'])) { $config = array('callback' => $config); } if (!is_callable($config['callback'], false, $callbackName)) { throw new HTML_QuickForm2_InvalidArgumentException( 'Callback Rule requires a valid callback, \'' . $callbackName . '\' was given' ); } return parent::setConfig($config + array('arguments' => array())); }
php
public function setConfig($config) { if (!is_array($config) || !isset($config['callback'])) { $config = array('callback' => $config); } if (!is_callable($config['callback'], false, $callbackName)) { throw new HTML_QuickForm2_InvalidArgumentException( 'Callback Rule requires a valid callback, \'' . $callbackName . '\' was given' ); } return parent::setConfig($config + array('arguments' => array())); }
[ "public", "function", "setConfig", "(", "$", "config", ")", "{", "if", "(", "!", "is_array", "(", "$", "config", ")", "||", "!", "isset", "(", "$", "config", "[", "'callback'", "]", ")", ")", "{", "$", "config", "=", "array", "(", "'callback'", "=>", "$", "config", ")", ";", "}", "if", "(", "!", "is_callable", "(", "$", "config", "[", "'callback'", "]", ",", "false", ",", "$", "callbackName", ")", ")", "{", "throw", "new", "HTML_QuickForm2_InvalidArgumentException", "(", "'Callback Rule requires a valid callback, \\''", ".", "$", "callbackName", ".", "'\\' was given'", ")", ";", "}", "return", "parent", "::", "setConfig", "(", "$", "config", "+", "array", "(", "'arguments'", "=>", "array", "(", ")", ")", ")", ";", "}" ]
Sets the callback to use for validation and its additional arguments @param callback|array Callback or array ('callback' => validation callback, 'arguments' => additional arguments) @return HTML_QuickForm2_Rule @throws HTML_QuickForm2_InvalidArgumentException if callback is missing or invalid
[ "Sets", "the", "callback", "to", "use", "for", "validation", "and", "its", "additional", "arguments" ]
72df150735664275a60a7861e468c6ff3b152a14
https://github.com/matomo-org/matomo/blob/72df150735664275a60a7861e468c6ff3b152a14/libs/HTML/QuickForm2/Rule/Callback.php#L158-L170
210,125
matomo-org/matomo
plugins/UserCountry/LocationProvider/GeoIp/ServerBased.php
ServerBased.isAvailable
public function isAvailable() { // check if apache module is installed if (function_exists('apache_get_modules')) { foreach (apache_get_modules() as $name) { if (strpos($name, 'geoip') !== false) { return true; } } } $available = !empty($_SERVER[self::TEST_SERVER_VAR]) || !empty($_SERVER[self::TEST_SERVER_VAR_ALT]) || !empty($_SERVER[self::TEST_SERVER_VAR_ALT_IPV6]) ; if ($available) { return true; } // if not available return message w/ extra info if (!function_exists('apache_get_modules')) { return Piwik::translate('General_Note') . ':&nbsp;' . Piwik::translate('UserCountry_AssumingNonApache'); } $message = "<strong>" . Piwik::translate('General_Note') . ':&nbsp;' . Piwik::translate('UserCountry_FoundApacheModules') . "</strong>:<br/><br/>\n<ul style=\"list-style:disc;margin-left:24px\">\n"; foreach (apache_get_modules() as $name) { $message .= "<li>$name</li>\n"; } $message .= "</ul>"; return $message; }
php
public function isAvailable() { // check if apache module is installed if (function_exists('apache_get_modules')) { foreach (apache_get_modules() as $name) { if (strpos($name, 'geoip') !== false) { return true; } } } $available = !empty($_SERVER[self::TEST_SERVER_VAR]) || !empty($_SERVER[self::TEST_SERVER_VAR_ALT]) || !empty($_SERVER[self::TEST_SERVER_VAR_ALT_IPV6]) ; if ($available) { return true; } // if not available return message w/ extra info if (!function_exists('apache_get_modules')) { return Piwik::translate('General_Note') . ':&nbsp;' . Piwik::translate('UserCountry_AssumingNonApache'); } $message = "<strong>" . Piwik::translate('General_Note') . ':&nbsp;' . Piwik::translate('UserCountry_FoundApacheModules') . "</strong>:<br/><br/>\n<ul style=\"list-style:disc;margin-left:24px\">\n"; foreach (apache_get_modules() as $name) { $message .= "<li>$name</li>\n"; } $message .= "</ul>"; return $message; }
[ "public", "function", "isAvailable", "(", ")", "{", "// check if apache module is installed", "if", "(", "function_exists", "(", "'apache_get_modules'", ")", ")", "{", "foreach", "(", "apache_get_modules", "(", ")", "as", "$", "name", ")", "{", "if", "(", "strpos", "(", "$", "name", ",", "'geoip'", ")", "!==", "false", ")", "{", "return", "true", ";", "}", "}", "}", "$", "available", "=", "!", "empty", "(", "$", "_SERVER", "[", "self", "::", "TEST_SERVER_VAR", "]", ")", "||", "!", "empty", "(", "$", "_SERVER", "[", "self", "::", "TEST_SERVER_VAR_ALT", "]", ")", "||", "!", "empty", "(", "$", "_SERVER", "[", "self", "::", "TEST_SERVER_VAR_ALT_IPV6", "]", ")", ";", "if", "(", "$", "available", ")", "{", "return", "true", ";", "}", "// if not available return message w/ extra info", "if", "(", "!", "function_exists", "(", "'apache_get_modules'", ")", ")", "{", "return", "Piwik", "::", "translate", "(", "'General_Note'", ")", ".", "':&nbsp;'", ".", "Piwik", "::", "translate", "(", "'UserCountry_AssumingNonApache'", ")", ";", "}", "$", "message", "=", "\"<strong>\"", ".", "Piwik", "::", "translate", "(", "'General_Note'", ")", ".", "':&nbsp;'", ".", "Piwik", "::", "translate", "(", "'UserCountry_FoundApacheModules'", ")", ".", "\"</strong>:<br/><br/>\\n<ul style=\\\"list-style:disc;margin-left:24px\\\">\\n\"", ";", "foreach", "(", "apache_get_modules", "(", ")", "as", "$", "name", ")", "{", "$", "message", ".=", "\"<li>$name</li>\\n\"", ";", "}", "$", "message", ".=", "\"</ul>\"", ";", "return", "$", "message", ";", "}" ]
Checks if an HTTP server module has been installed. It checks by looking for the GEOIP_ADDR server variable. There's a special check for the Apache module, but we can't check specifically for anything else. @return bool|string
[ "Checks", "if", "an", "HTTP", "server", "module", "has", "been", "installed", ".", "It", "checks", "by", "looking", "for", "the", "GEOIP_ADDR", "server", "variable", "." ]
72df150735664275a60a7861e468c6ff3b152a14
https://github.com/matomo-org/matomo/blob/72df150735664275a60a7861e468c6ff3b152a14/plugins/UserCountry/LocationProvider/GeoIp/ServerBased.php#L147-L180
210,126
matomo-org/matomo
plugins/UserCountry/LocationProvider/GeoIp/ServerBased.php
ServerBased.isWorking
public function isWorking() { if (empty($_SERVER[self::TEST_SERVER_VAR]) && empty($_SERVER[self::TEST_SERVER_VAR_ALT]) && empty($_SERVER[self::TEST_SERVER_VAR_ALT_IPV6]) ) { return Piwik::translate("UserCountry_CannotFindGeoIPServerVar", self::TEST_SERVER_VAR . ' $_SERVER'); } return true; // can't check for another IP }
php
public function isWorking() { if (empty($_SERVER[self::TEST_SERVER_VAR]) && empty($_SERVER[self::TEST_SERVER_VAR_ALT]) && empty($_SERVER[self::TEST_SERVER_VAR_ALT_IPV6]) ) { return Piwik::translate("UserCountry_CannotFindGeoIPServerVar", self::TEST_SERVER_VAR . ' $_SERVER'); } return true; // can't check for another IP }
[ "public", "function", "isWorking", "(", ")", "{", "if", "(", "empty", "(", "$", "_SERVER", "[", "self", "::", "TEST_SERVER_VAR", "]", ")", "&&", "empty", "(", "$", "_SERVER", "[", "self", "::", "TEST_SERVER_VAR_ALT", "]", ")", "&&", "empty", "(", "$", "_SERVER", "[", "self", "::", "TEST_SERVER_VAR_ALT_IPV6", "]", ")", ")", "{", "return", "Piwik", "::", "translate", "(", "\"UserCountry_CannotFindGeoIPServerVar\"", ",", "self", "::", "TEST_SERVER_VAR", ".", "' $_SERVER'", ")", ";", "}", "return", "true", ";", "// can't check for another IP", "}" ]
Returns true if the GEOIP_ADDR server variable is defined. @return bool
[ "Returns", "true", "if", "the", "GEOIP_ADDR", "server", "variable", "is", "defined", "." ]
72df150735664275a60a7861e468c6ff3b152a14
https://github.com/matomo-org/matomo/blob/72df150735664275a60a7861e468c6ff3b152a14/plugins/UserCountry/LocationProvider/GeoIp/ServerBased.php#L187-L197
210,127
matomo-org/matomo
plugins/GeoIp2/LocationProvider/GeoIp2.php
GeoIp2.getRegionNameFromCodes
public static function getRegionNameFromCodes($countryCode, $regionCode) { $regionNames = self::getRegionNames(); $countryCode = strtoupper($countryCode); $regionCode = strtoupper($regionCode); if (isset($regionNames[$countryCode][$regionCode])) { return $regionNames[$countryCode][$regionCode]; } else { return Piwik::translate('General_Unknown'); } }
php
public static function getRegionNameFromCodes($countryCode, $regionCode) { $regionNames = self::getRegionNames(); $countryCode = strtoupper($countryCode); $regionCode = strtoupper($regionCode); if (isset($regionNames[$countryCode][$regionCode])) { return $regionNames[$countryCode][$regionCode]; } else { return Piwik::translate('General_Unknown'); } }
[ "public", "static", "function", "getRegionNameFromCodes", "(", "$", "countryCode", ",", "$", "regionCode", ")", "{", "$", "regionNames", "=", "self", "::", "getRegionNames", "(", ")", ";", "$", "countryCode", "=", "strtoupper", "(", "$", "countryCode", ")", ";", "$", "regionCode", "=", "strtoupper", "(", "$", "regionCode", ")", ";", "if", "(", "isset", "(", "$", "regionNames", "[", "$", "countryCode", "]", "[", "$", "regionCode", "]", ")", ")", "{", "return", "$", "regionNames", "[", "$", "countryCode", "]", "[", "$", "regionCode", "]", ";", "}", "else", "{", "return", "Piwik", "::", "translate", "(", "'General_Unknown'", ")", ";", "}", "}" ]
Returns a region name for a country code + region code. @param string $countryCode @param string $regionCode @return string The region name or 'Unknown' (translated).
[ "Returns", "a", "region", "name", "for", "a", "country", "code", "+", "region", "code", "." ]
72df150735664275a60a7861e468c6ff3b152a14
https://github.com/matomo-org/matomo/blob/72df150735664275a60a7861e468c6ff3b152a14/plugins/GeoIp2/LocationProvider/GeoIp2.php#L192-L204
210,128
matomo-org/matomo
plugins/GeoIp2/LocationProvider/GeoIp2.php
GeoIp2.convertRegionCodeToIso
public static function convertRegionCodeToIso($countryCode, $fipsRegionCode, $returnOriginalIfNotFound = false) { static $mapping; if(empty($mapping)) { $mapping = include __DIR__ . '/../data/regionMapping.php'; } $countryCode = strtoupper($countryCode); if (empty($countryCode) || in_array($countryCode, ['EU', 'AP', 'A1', 'A2'])) { return ['', '']; } if (in_array($countryCode, ['US', 'CA'])) { // US and CA always haven been iso codes return [$countryCode, $fipsRegionCode]; } if ($countryCode == 'TI') { $countryCode = 'CN'; $fipsRegionCode = '14'; } $isoRegionCode = $returnOriginalIfNotFound ? $fipsRegionCode : ''; if (!empty($fipsRegionCode) && !empty($mapping[$countryCode][$fipsRegionCode])) { $isoRegionCode = $mapping[$countryCode][$fipsRegionCode]; } return [$countryCode, $isoRegionCode]; }
php
public static function convertRegionCodeToIso($countryCode, $fipsRegionCode, $returnOriginalIfNotFound = false) { static $mapping; if(empty($mapping)) { $mapping = include __DIR__ . '/../data/regionMapping.php'; } $countryCode = strtoupper($countryCode); if (empty($countryCode) || in_array($countryCode, ['EU', 'AP', 'A1', 'A2'])) { return ['', '']; } if (in_array($countryCode, ['US', 'CA'])) { // US and CA always haven been iso codes return [$countryCode, $fipsRegionCode]; } if ($countryCode == 'TI') { $countryCode = 'CN'; $fipsRegionCode = '14'; } $isoRegionCode = $returnOriginalIfNotFound ? $fipsRegionCode : ''; if (!empty($fipsRegionCode) && !empty($mapping[$countryCode][$fipsRegionCode])) { $isoRegionCode = $mapping[$countryCode][$fipsRegionCode]; } return [$countryCode, $isoRegionCode]; }
[ "public", "static", "function", "convertRegionCodeToIso", "(", "$", "countryCode", ",", "$", "fipsRegionCode", ",", "$", "returnOriginalIfNotFound", "=", "false", ")", "{", "static", "$", "mapping", ";", "if", "(", "empty", "(", "$", "mapping", ")", ")", "{", "$", "mapping", "=", "include", "__DIR__", ".", "'/../data/regionMapping.php'", ";", "}", "$", "countryCode", "=", "strtoupper", "(", "$", "countryCode", ")", ";", "if", "(", "empty", "(", "$", "countryCode", ")", "||", "in_array", "(", "$", "countryCode", ",", "[", "'EU'", ",", "'AP'", ",", "'A1'", ",", "'A2'", "]", ")", ")", "{", "return", "[", "''", ",", "''", "]", ";", "}", "if", "(", "in_array", "(", "$", "countryCode", ",", "[", "'US'", ",", "'CA'", "]", ")", ")", "{", "// US and CA always haven been iso codes", "return", "[", "$", "countryCode", ",", "$", "fipsRegionCode", "]", ";", "}", "if", "(", "$", "countryCode", "==", "'TI'", ")", "{", "$", "countryCode", "=", "'CN'", ";", "$", "fipsRegionCode", "=", "'14'", ";", "}", "$", "isoRegionCode", "=", "$", "returnOriginalIfNotFound", "?", "$", "fipsRegionCode", ":", "''", ";", "if", "(", "!", "empty", "(", "$", "fipsRegionCode", ")", "&&", "!", "empty", "(", "$", "mapping", "[", "$", "countryCode", "]", "[", "$", "fipsRegionCode", "]", ")", ")", "{", "$", "isoRegionCode", "=", "$", "mapping", "[", "$", "countryCode", "]", "[", "$", "fipsRegionCode", "]", ";", "}", "return", "[", "$", "countryCode", ",", "$", "isoRegionCode", "]", ";", "}" ]
Converts an old FIPS region code to ISO @param string $countryCode @param string $fipsRegionCode @param bool $returnOriginalIfNotFound return given region code if no mapping was found @return array
[ "Converts", "an", "old", "FIPS", "region", "code", "to", "ISO" ]
72df150735664275a60a7861e468c6ff3b152a14
https://github.com/matomo-org/matomo/blob/72df150735664275a60a7861e468c6ff3b152a14/plugins/GeoIp2/LocationProvider/GeoIp2.php#L228-L250
210,129
matomo-org/matomo
plugins/Referrers/Controller.php
Controller.getReferrerSparklineParams
private function getReferrerSparklineParams($referrerType) { $totalRow = $this->translator->translate('General_Total'); return array( 'columns' => array('nb_visits'), 'rows' => array(self::getTranslatedReferrerTypeLabel($referrerType), $totalRow), 'typeReferrer' => $referrerType, 'module' => $this->pluginName, 'action' => 'getReferrerType' ); }
php
private function getReferrerSparklineParams($referrerType) { $totalRow = $this->translator->translate('General_Total'); return array( 'columns' => array('nb_visits'), 'rows' => array(self::getTranslatedReferrerTypeLabel($referrerType), $totalRow), 'typeReferrer' => $referrerType, 'module' => $this->pluginName, 'action' => 'getReferrerType' ); }
[ "private", "function", "getReferrerSparklineParams", "(", "$", "referrerType", ")", "{", "$", "totalRow", "=", "$", "this", "->", "translator", "->", "translate", "(", "'General_Total'", ")", ";", "return", "array", "(", "'columns'", "=>", "array", "(", "'nb_visits'", ")", ",", "'rows'", "=>", "array", "(", "self", "::", "getTranslatedReferrerTypeLabel", "(", "$", "referrerType", ")", ",", "$", "totalRow", ")", ",", "'typeReferrer'", "=>", "$", "referrerType", ",", "'module'", "=>", "$", "this", "->", "pluginName", ",", "'action'", "=>", "'getReferrerType'", ")", ";", "}" ]
Returns the URL for the sparkline of visits with a specific referrer type. @param int $referrerType The referrer type. Referrer types are defined in Common class. @return string The URL that can be used to get a sparkline image.
[ "Returns", "the", "URL", "for", "the", "sparkline", "of", "visits", "with", "a", "specific", "referrer", "type", "." ]
72df150735664275a60a7861e468c6ff3b152a14
https://github.com/matomo-org/matomo/blob/72df150735664275a60a7861e468c6ff3b152a14/plugins/Referrers/Controller.php#L378-L389
210,130
matomo-org/matomo
plugins/Referrers/Controller.php
Controller.getDistinctReferrersMetrics
private function getDistinctReferrersMetrics($date = false) { $propertyToAccessorMapping = array( 'numberDistinctSearchEngines' => 'getNumberOfDistinctSearchEngines', 'numberDistinctSocialNetworks' => 'getNumberOfDistinctSocialNetworks', 'numberDistinctKeywords' => 'getNumberOfDistinctKeywords', 'numberDistinctWebsites' => 'getNumberOfDistinctWebsites', 'numberDistinctWebsitesUrls' => 'getNumberOfDistinctWebsitesUrls', 'numberDistinctCampaigns' => 'getNumberOfDistinctCampaigns', ); $result = array(); foreach ($propertyToAccessorMapping as $property => $method) { $result[$property] = $this->getNumericValue('Referrers.' . $method, $date); } return $result; }
php
private function getDistinctReferrersMetrics($date = false) { $propertyToAccessorMapping = array( 'numberDistinctSearchEngines' => 'getNumberOfDistinctSearchEngines', 'numberDistinctSocialNetworks' => 'getNumberOfDistinctSocialNetworks', 'numberDistinctKeywords' => 'getNumberOfDistinctKeywords', 'numberDistinctWebsites' => 'getNumberOfDistinctWebsites', 'numberDistinctWebsitesUrls' => 'getNumberOfDistinctWebsitesUrls', 'numberDistinctCampaigns' => 'getNumberOfDistinctCampaigns', ); $result = array(); foreach ($propertyToAccessorMapping as $property => $method) { $result[$property] = $this->getNumericValue('Referrers.' . $method, $date); } return $result; }
[ "private", "function", "getDistinctReferrersMetrics", "(", "$", "date", "=", "false", ")", "{", "$", "propertyToAccessorMapping", "=", "array", "(", "'numberDistinctSearchEngines'", "=>", "'getNumberOfDistinctSearchEngines'", ",", "'numberDistinctSocialNetworks'", "=>", "'getNumberOfDistinctSocialNetworks'", ",", "'numberDistinctKeywords'", "=>", "'getNumberOfDistinctKeywords'", ",", "'numberDistinctWebsites'", "=>", "'getNumberOfDistinctWebsites'", ",", "'numberDistinctWebsitesUrls'", "=>", "'getNumberOfDistinctWebsitesUrls'", ",", "'numberDistinctCampaigns'", "=>", "'getNumberOfDistinctCampaigns'", ",", ")", ";", "$", "result", "=", "array", "(", ")", ";", "foreach", "(", "$", "propertyToAccessorMapping", "as", "$", "property", "=>", "$", "method", ")", "{", "$", "result", "[", "$", "property", "]", "=", "$", "this", "->", "getNumericValue", "(", "'Referrers.'", ".", "$", "method", ",", "$", "date", ")", ";", "}", "return", "$", "result", ";", "}" ]
Returns an array containing the number of distinct referrers for each referrer type. @param bool|string $date The date to use when getting metrics. If false, the date query param is used. @return array The metrics.
[ "Returns", "an", "array", "containing", "the", "number", "of", "distinct", "referrers", "for", "each", "referrer", "type", "." ]
72df150735664275a60a7861e468c6ff3b152a14
https://github.com/matomo-org/matomo/blob/72df150735664275a60a7861e468c6ff3b152a14/plugins/Referrers/Controller.php#L399-L415
210,131
matomo-org/matomo
plugins/Diagnostics/Diagnostic/PhpFunctionsCheck.php
PhpFunctionsCheck.functionExists
public static function functionExists($function) { // eval() is a language construct if ($function == 'eval') { // does not check suhosin.executor.eval.whitelist (or blacklist) if (extension_loaded('suhosin')) { return @ini_get("suhosin.executor.disable_eval") != "1"; } return true; } $exists = function_exists($function); if (extension_loaded('suhosin')) { $blacklist = @ini_get("suhosin.executor.func.blacklist"); if (!empty($blacklist)) { $blacklistFunctions = array_map('strtolower', array_map('trim', explode(',', $blacklist))); return $exists && !in_array($function, $blacklistFunctions); } } return $exists; }
php
public static function functionExists($function) { // eval() is a language construct if ($function == 'eval') { // does not check suhosin.executor.eval.whitelist (or blacklist) if (extension_loaded('suhosin')) { return @ini_get("suhosin.executor.disable_eval") != "1"; } return true; } $exists = function_exists($function); if (extension_loaded('suhosin')) { $blacklist = @ini_get("suhosin.executor.func.blacklist"); if (!empty($blacklist)) { $blacklistFunctions = array_map('strtolower', array_map('trim', explode(',', $blacklist))); return $exists && !in_array($function, $blacklistFunctions); } } return $exists; }
[ "public", "static", "function", "functionExists", "(", "$", "function", ")", "{", "// eval() is a language construct", "if", "(", "$", "function", "==", "'eval'", ")", "{", "// does not check suhosin.executor.eval.whitelist (or blacklist)", "if", "(", "extension_loaded", "(", "'suhosin'", ")", ")", "{", "return", "@", "ini_get", "(", "\"suhosin.executor.disable_eval\"", ")", "!=", "\"1\"", ";", "}", "return", "true", ";", "}", "$", "exists", "=", "function_exists", "(", "$", "function", ")", ";", "if", "(", "extension_loaded", "(", "'suhosin'", ")", ")", "{", "$", "blacklist", "=", "@", "ini_get", "(", "\"suhosin.executor.func.blacklist\"", ")", ";", "if", "(", "!", "empty", "(", "$", "blacklist", ")", ")", "{", "$", "blacklistFunctions", "=", "array_map", "(", "'strtolower'", ",", "array_map", "(", "'trim'", ",", "explode", "(", "','", ",", "$", "blacklist", ")", ")", ")", ";", "return", "$", "exists", "&&", "!", "in_array", "(", "$", "function", ",", "$", "blacklistFunctions", ")", ";", "}", "}", "return", "$", "exists", ";", "}" ]
Tests if a function exists. Also handles the case where a function is disabled via Suhosin. @param string $function @return bool
[ "Tests", "if", "a", "function", "exists", ".", "Also", "handles", "the", "case", "where", "a", "function", "is", "disabled", "via", "Suhosin", "." ]
72df150735664275a60a7861e468c6ff3b152a14
https://github.com/matomo-org/matomo/blob/72df150735664275a60a7861e468c6ff3b152a14/plugins/Diagnostics/Diagnostic/PhpFunctionsCheck.php#L75-L97
210,132
matomo-org/matomo
libs/Authenticator/TwoFactorAuthenticator.php
TwoFactorAuthenticator._base32Encode
protected function _base32Encode($secret, $padding = true) { if (empty($secret)) return ''; $base32chars = $this->_getBase32LookupTable(); $secret = str_split($secret); $binaryString = ""; for ($i = 0; $i < count($secret); $i++) { $binaryString .= str_pad(base_convert(ord($secret[$i]), 10, 2), 8, '0', STR_PAD_LEFT); } $fiveBitBinaryArray = str_split($binaryString, 5); $base32 = ""; $i = 0; while ($i < count($fiveBitBinaryArray)) { $base32 .= $base32chars[base_convert(str_pad($fiveBitBinaryArray[$i], 5, '0'), 2, 10)]; $i++; } if ($padding && ($x = strlen($binaryString) % 40) != 0) { if ($x == 8) $base32 .= str_repeat($base32chars[32], 6); elseif ($x == 16) $base32 .= str_repeat($base32chars[32], 4); elseif ($x == 24) $base32 .= str_repeat($base32chars[32], 3); elseif ($x == 32) $base32 .= $base32chars[32]; } return $base32; }
php
protected function _base32Encode($secret, $padding = true) { if (empty($secret)) return ''; $base32chars = $this->_getBase32LookupTable(); $secret = str_split($secret); $binaryString = ""; for ($i = 0; $i < count($secret); $i++) { $binaryString .= str_pad(base_convert(ord($secret[$i]), 10, 2), 8, '0', STR_PAD_LEFT); } $fiveBitBinaryArray = str_split($binaryString, 5); $base32 = ""; $i = 0; while ($i < count($fiveBitBinaryArray)) { $base32 .= $base32chars[base_convert(str_pad($fiveBitBinaryArray[$i], 5, '0'), 2, 10)]; $i++; } if ($padding && ($x = strlen($binaryString) % 40) != 0) { if ($x == 8) $base32 .= str_repeat($base32chars[32], 6); elseif ($x == 16) $base32 .= str_repeat($base32chars[32], 4); elseif ($x == 24) $base32 .= str_repeat($base32chars[32], 3); elseif ($x == 32) $base32 .= $base32chars[32]; } return $base32; }
[ "protected", "function", "_base32Encode", "(", "$", "secret", ",", "$", "padding", "=", "true", ")", "{", "if", "(", "empty", "(", "$", "secret", ")", ")", "return", "''", ";", "$", "base32chars", "=", "$", "this", "->", "_getBase32LookupTable", "(", ")", ";", "$", "secret", "=", "str_split", "(", "$", "secret", ")", ";", "$", "binaryString", "=", "\"\"", ";", "for", "(", "$", "i", "=", "0", ";", "$", "i", "<", "count", "(", "$", "secret", ")", ";", "$", "i", "++", ")", "{", "$", "binaryString", ".=", "str_pad", "(", "base_convert", "(", "ord", "(", "$", "secret", "[", "$", "i", "]", ")", ",", "10", ",", "2", ")", ",", "8", ",", "'0'", ",", "STR_PAD_LEFT", ")", ";", "}", "$", "fiveBitBinaryArray", "=", "str_split", "(", "$", "binaryString", ",", "5", ")", ";", "$", "base32", "=", "\"\"", ";", "$", "i", "=", "0", ";", "while", "(", "$", "i", "<", "count", "(", "$", "fiveBitBinaryArray", ")", ")", "{", "$", "base32", ".=", "$", "base32chars", "[", "base_convert", "(", "str_pad", "(", "$", "fiveBitBinaryArray", "[", "$", "i", "]", ",", "5", ",", "'0'", ")", ",", "2", ",", "10", ")", "]", ";", "$", "i", "++", ";", "}", "if", "(", "$", "padding", "&&", "(", "$", "x", "=", "strlen", "(", "$", "binaryString", ")", "%", "40", ")", "!=", "0", ")", "{", "if", "(", "$", "x", "==", "8", ")", "$", "base32", ".=", "str_repeat", "(", "$", "base32chars", "[", "32", "]", ",", "6", ")", ";", "elseif", "(", "$", "x", "==", "16", ")", "$", "base32", ".=", "str_repeat", "(", "$", "base32chars", "[", "32", "]", ",", "4", ")", ";", "elseif", "(", "$", "x", "==", "24", ")", "$", "base32", ".=", "str_repeat", "(", "$", "base32chars", "[", "32", "]", ",", "3", ")", ";", "elseif", "(", "$", "x", "==", "32", ")", "$", "base32", ".=", "$", "base32chars", "[", "32", "]", ";", "}", "return", "$", "base32", ";", "}" ]
Helper class to encode base32 @param string $secret @param bool $padding @return string
[ "Helper", "class", "to", "encode", "base32" ]
72df150735664275a60a7861e468c6ff3b152a14
https://github.com/matomo-org/matomo/blob/72df150735664275a60a7861e468c6ff3b152a14/libs/Authenticator/TwoFactorAuthenticator.php#L152-L177
210,133
matomo-org/matomo
core/Common.php
Common.prefixTables
public static function prefixTables() { $result = array(); foreach (func_get_args() as $table) { $result[] = self::prefixTable($table); } return $result; }
php
public static function prefixTables() { $result = array(); foreach (func_get_args() as $table) { $result[] = self::prefixTable($table); } return $result; }
[ "public", "static", "function", "prefixTables", "(", ")", "{", "$", "result", "=", "array", "(", ")", ";", "foreach", "(", "func_get_args", "(", ")", "as", "$", "table", ")", "{", "$", "result", "[", "]", "=", "self", "::", "prefixTable", "(", "$", "table", ")", ";", "}", "return", "$", "result", ";", "}" ]
Returns an array containing the prefixed table names of every passed argument. @param string ... The table names to prefix, ie "log_visit" @return array The prefixed names in an array.
[ "Returns", "an", "array", "containing", "the", "prefixed", "table", "names", "of", "every", "passed", "argument", "." ]
72df150735664275a60a7861e468c6ff3b152a14
https://github.com/matomo-org/matomo/blob/72df150735664275a60a7861e468c6ff3b152a14/core/Common.php#L75-L82
210,134
matomo-org/matomo
core/Common.php
Common.unprefixTable
public static function unprefixTable($table) { static $prefixTable = null; if (is_null($prefixTable)) { $prefixTable = Config::getInstance()->database['tables_prefix']; } if (empty($prefixTable) || strpos($table, $prefixTable) !== 0 ) { return $table; } $count = 1; return str_replace($prefixTable, '', $table, $count); }
php
public static function unprefixTable($table) { static $prefixTable = null; if (is_null($prefixTable)) { $prefixTable = Config::getInstance()->database['tables_prefix']; } if (empty($prefixTable) || strpos($table, $prefixTable) !== 0 ) { return $table; } $count = 1; return str_replace($prefixTable, '', $table, $count); }
[ "public", "static", "function", "unprefixTable", "(", "$", "table", ")", "{", "static", "$", "prefixTable", "=", "null", ";", "if", "(", "is_null", "(", "$", "prefixTable", ")", ")", "{", "$", "prefixTable", "=", "Config", "::", "getInstance", "(", ")", "->", "database", "[", "'tables_prefix'", "]", ";", "}", "if", "(", "empty", "(", "$", "prefixTable", ")", "||", "strpos", "(", "$", "table", ",", "$", "prefixTable", ")", "!==", "0", ")", "{", "return", "$", "table", ";", "}", "$", "count", "=", "1", ";", "return", "str_replace", "(", "$", "prefixTable", ",", "''", ",", "$", "table", ",", "$", "count", ")", ";", "}" ]
Removes the prefix from a table name and returns the result. The table prefix is determined by the `[database] tables_prefix` INI config option. @param string $table The prefixed table name, eg "piwik-production_log_visit". @return string The unprefixed table name, eg "log_visit". @api
[ "Removes", "the", "prefix", "from", "a", "table", "name", "and", "returns", "the", "result", "." ]
72df150735664275a60a7861e468c6ff3b152a14
https://github.com/matomo-org/matomo/blob/72df150735664275a60a7861e468c6ff3b152a14/core/Common.php#L94-L107
210,135
matomo-org/matomo
core/Common.php
Common.safe_unserialize
public static function safe_unserialize($string, $allowedClasses = [], $rethrow = false) { if (PHP_MAJOR_VERSION >= 7) { try { return unserialize($string, ['allowed_classes' => empty($allowedClasses) ? false : $allowedClasses]); } catch (\Throwable $e) { if ($rethrow) { throw $e; } $logger = StaticContainer::get('Psr\Log\LoggerInterface'); $logger->debug('Unable to unserialize a string: {message} (string = {string})', [ 'message' => $e->getMessage(), 'backtrace' => $e->getTraceAsString(), 'string' => $string, ]); return false; } } return @unserialize($string); }
php
public static function safe_unserialize($string, $allowedClasses = [], $rethrow = false) { if (PHP_MAJOR_VERSION >= 7) { try { return unserialize($string, ['allowed_classes' => empty($allowedClasses) ? false : $allowedClasses]); } catch (\Throwable $e) { if ($rethrow) { throw $e; } $logger = StaticContainer::get('Psr\Log\LoggerInterface'); $logger->debug('Unable to unserialize a string: {message} (string = {string})', [ 'message' => $e->getMessage(), 'backtrace' => $e->getTraceAsString(), 'string' => $string, ]); return false; } } return @unserialize($string); }
[ "public", "static", "function", "safe_unserialize", "(", "$", "string", ",", "$", "allowedClasses", "=", "[", "]", ",", "$", "rethrow", "=", "false", ")", "{", "if", "(", "PHP_MAJOR_VERSION", ">=", "7", ")", "{", "try", "{", "return", "unserialize", "(", "$", "string", ",", "[", "'allowed_classes'", "=>", "empty", "(", "$", "allowedClasses", ")", "?", "false", ":", "$", "allowedClasses", "]", ")", ";", "}", "catch", "(", "\\", "Throwable", "$", "e", ")", "{", "if", "(", "$", "rethrow", ")", "{", "throw", "$", "e", ";", "}", "$", "logger", "=", "StaticContainer", "::", "get", "(", "'Psr\\Log\\LoggerInterface'", ")", ";", "$", "logger", "->", "debug", "(", "'Unable to unserialize a string: {message} (string = {string})'", ",", "[", "'message'", "=>", "$", "e", "->", "getMessage", "(", ")", ",", "'backtrace'", "=>", "$", "e", "->", "getTraceAsString", "(", ")", ",", "'string'", "=>", "$", "string", ",", "]", ")", ";", "return", "false", ";", "}", "}", "return", "@", "unserialize", "(", "$", "string", ")", ";", "}" ]
Secure wrapper for unserialize, which by default disallows unserializing classes @param string $string String to unserialize @param array $allowedClasses Class names that should be allowed to unserialize @param bool $rethrow Whether to rethrow exceptions or not. @return mixed
[ "Secure", "wrapper", "for", "unserialize", "which", "by", "default", "disallows", "unserializing", "classes" ]
72df150735664275a60a7861e468c6ff3b152a14
https://github.com/matomo-org/matomo/blob/72df150735664275a60a7861e468c6ff3b152a14/core/Common.php#L267-L288
210,136
matomo-org/matomo
core/Common.php
Common.sanitizeInputValues
public static function sanitizeInputValues($value, $alreadyStripslashed = false) { if (is_numeric($value)) { return $value; } elseif (is_string($value)) { $value = self::sanitizeString($value); } elseif (is_array($value)) { foreach (array_keys($value) as $key) { $newKey = $key; $newKey = self::sanitizeInputValues($newKey, $alreadyStripslashed); if ($key != $newKey) { $value[$newKey] = $value[$key]; unset($value[$key]); } $value[$newKey] = self::sanitizeInputValues($value[$newKey], $alreadyStripslashed); } } elseif (!is_null($value) && !is_bool($value) ) { throw new Exception("The value to escape has not a supported type. Value = " . var_export($value, true)); } return $value; }
php
public static function sanitizeInputValues($value, $alreadyStripslashed = false) { if (is_numeric($value)) { return $value; } elseif (is_string($value)) { $value = self::sanitizeString($value); } elseif (is_array($value)) { foreach (array_keys($value) as $key) { $newKey = $key; $newKey = self::sanitizeInputValues($newKey, $alreadyStripslashed); if ($key != $newKey) { $value[$newKey] = $value[$key]; unset($value[$key]); } $value[$newKey] = self::sanitizeInputValues($value[$newKey], $alreadyStripslashed); } } elseif (!is_null($value) && !is_bool($value) ) { throw new Exception("The value to escape has not a supported type. Value = " . var_export($value, true)); } return $value; }
[ "public", "static", "function", "sanitizeInputValues", "(", "$", "value", ",", "$", "alreadyStripslashed", "=", "false", ")", "{", "if", "(", "is_numeric", "(", "$", "value", ")", ")", "{", "return", "$", "value", ";", "}", "elseif", "(", "is_string", "(", "$", "value", ")", ")", "{", "$", "value", "=", "self", "::", "sanitizeString", "(", "$", "value", ")", ";", "}", "elseif", "(", "is_array", "(", "$", "value", ")", ")", "{", "foreach", "(", "array_keys", "(", "$", "value", ")", "as", "$", "key", ")", "{", "$", "newKey", "=", "$", "key", ";", "$", "newKey", "=", "self", "::", "sanitizeInputValues", "(", "$", "newKey", ",", "$", "alreadyStripslashed", ")", ";", "if", "(", "$", "key", "!=", "$", "newKey", ")", "{", "$", "value", "[", "$", "newKey", "]", "=", "$", "value", "[", "$", "key", "]", ";", "unset", "(", "$", "value", "[", "$", "key", "]", ")", ";", "}", "$", "value", "[", "$", "newKey", "]", "=", "self", "::", "sanitizeInputValues", "(", "$", "value", "[", "$", "newKey", "]", ",", "$", "alreadyStripslashed", ")", ";", "}", "}", "elseif", "(", "!", "is_null", "(", "$", "value", ")", "&&", "!", "is_bool", "(", "$", "value", ")", ")", "{", "throw", "new", "Exception", "(", "\"The value to escape has not a supported type. Value = \"", ".", "var_export", "(", "$", "value", ",", "true", ")", ")", ";", "}", "return", "$", "value", ";", "}" ]
Sanitizes a string to help avoid XSS vulnerabilities. This function is automatically called when {@link getRequestVar()} is called, so you should not normally have to use it. This function should be used when outputting data that isn't escaped and was obtained from the user (for example when using the `|raw` twig filter on goal names). _NOTE: Sanitized input should not be used directly in an SQL query; SQL placeholders should still be used._ **Implementation Details** - [htmlspecialchars](http://php.net/manual/en/function.htmlspecialchars.php) is used to escape text. - Single quotes are not escaped so **Piwik's amazing community** will still be **Piwik's amazing community**. - Use of the `magic_quotes` setting will not break this method. - Boolean, numeric and null values are not modified. @param mixed $value The variable to be sanitized. If an array is supplied, the contents of the array will be sanitized recursively. The keys of the array will also be sanitized. @param bool $alreadyStripslashed Implementation detail, ignore. @throws Exception If `$value` is of an incorrect type. @return mixed The sanitized value. @api
[ "Sanitizes", "a", "string", "to", "help", "avoid", "XSS", "vulnerabilities", "." ]
72df150735664275a60a7861e468c6ff3b152a14
https://github.com/matomo-org/matomo/blob/72df150735664275a60a7861e468c6ff3b152a14/core/Common.php#L322-L345
210,137
matomo-org/matomo
core/Common.php
Common.sanitizeInputValue
public static function sanitizeInputValue($value) { $value = self::sanitizeLineBreaks($value); $value = self::sanitizeString($value); return $value; }
php
public static function sanitizeInputValue($value) { $value = self::sanitizeLineBreaks($value); $value = self::sanitizeString($value); return $value; }
[ "public", "static", "function", "sanitizeInputValue", "(", "$", "value", ")", "{", "$", "value", "=", "self", "::", "sanitizeLineBreaks", "(", "$", "value", ")", ";", "$", "value", "=", "self", "::", "sanitizeString", "(", "$", "value", ")", ";", "return", "$", "value", ";", "}" ]
Sanitize a single input value and removes line breaks, tabs and null characters. @param string $value @return string sanitized input
[ "Sanitize", "a", "single", "input", "value", "and", "removes", "line", "breaks", "tabs", "and", "null", "characters", "." ]
72df150735664275a60a7861e468c6ff3b152a14
https://github.com/matomo-org/matomo/blob/72df150735664275a60a7861e468c6ff3b152a14/core/Common.php#L353-L358
210,138
matomo-org/matomo
core/Common.php
Common.sanitizeString
private static function sanitizeString($value) { // $_GET and $_REQUEST already urldecode()'d // decode // note: before php 5.2.7, htmlspecialchars() double encodes &#x hex items $value = html_entity_decode($value, self::HTML_ENCODING_QUOTE_STYLE, 'UTF-8'); $value = self::sanitizeNullBytes($value); // escape $tmp = @htmlspecialchars($value, self::HTML_ENCODING_QUOTE_STYLE, 'UTF-8'); // note: php 5.2.5 and above, htmlspecialchars is destructive if input is not UTF-8 if ($value != '' && $tmp == '') { // convert and escape $value = utf8_encode($value); $tmp = htmlspecialchars($value, self::HTML_ENCODING_QUOTE_STYLE, 'UTF-8'); return $tmp; } return $tmp; }
php
private static function sanitizeString($value) { // $_GET and $_REQUEST already urldecode()'d // decode // note: before php 5.2.7, htmlspecialchars() double encodes &#x hex items $value = html_entity_decode($value, self::HTML_ENCODING_QUOTE_STYLE, 'UTF-8'); $value = self::sanitizeNullBytes($value); // escape $tmp = @htmlspecialchars($value, self::HTML_ENCODING_QUOTE_STYLE, 'UTF-8'); // note: php 5.2.5 and above, htmlspecialchars is destructive if input is not UTF-8 if ($value != '' && $tmp == '') { // convert and escape $value = utf8_encode($value); $tmp = htmlspecialchars($value, self::HTML_ENCODING_QUOTE_STYLE, 'UTF-8'); return $tmp; } return $tmp; }
[ "private", "static", "function", "sanitizeString", "(", "$", "value", ")", "{", "// $_GET and $_REQUEST already urldecode()'d", "// decode", "// note: before php 5.2.7, htmlspecialchars() double encodes &#x hex items", "$", "value", "=", "html_entity_decode", "(", "$", "value", ",", "self", "::", "HTML_ENCODING_QUOTE_STYLE", ",", "'UTF-8'", ")", ";", "$", "value", "=", "self", "::", "sanitizeNullBytes", "(", "$", "value", ")", ";", "// escape", "$", "tmp", "=", "@", "htmlspecialchars", "(", "$", "value", ",", "self", "::", "HTML_ENCODING_QUOTE_STYLE", ",", "'UTF-8'", ")", ";", "// note: php 5.2.5 and above, htmlspecialchars is destructive if input is not UTF-8", "if", "(", "$", "value", "!=", "''", "&&", "$", "tmp", "==", "''", ")", "{", "// convert and escape", "$", "value", "=", "utf8_encode", "(", "$", "value", ")", ";", "$", "tmp", "=", "htmlspecialchars", "(", "$", "value", ",", "self", "::", "HTML_ENCODING_QUOTE_STYLE", ",", "'UTF-8'", ")", ";", "return", "$", "tmp", ";", "}", "return", "$", "tmp", ";", "}" ]
Sanitize a single input value @param $value @return string
[ "Sanitize", "a", "single", "input", "value" ]
72df150735664275a60a7861e468c6ff3b152a14
https://github.com/matomo-org/matomo/blob/72df150735664275a60a7861e468c6ff3b152a14/core/Common.php#L366-L386
210,139
matomo-org/matomo
core/Common.php
Common.unsanitizeInputValues
public static function unsanitizeInputValues($value) { if (is_array($value)) { $result = array(); foreach ($value as $key => $arrayValue) { $result[$key] = self::unsanitizeInputValues($arrayValue); } return $result; } else { return self::unsanitizeInputValue($value); } }
php
public static function unsanitizeInputValues($value) { if (is_array($value)) { $result = array(); foreach ($value as $key => $arrayValue) { $result[$key] = self::unsanitizeInputValues($arrayValue); } return $result; } else { return self::unsanitizeInputValue($value); } }
[ "public", "static", "function", "unsanitizeInputValues", "(", "$", "value", ")", "{", "if", "(", "is_array", "(", "$", "value", ")", ")", "{", "$", "result", "=", "array", "(", ")", ";", "foreach", "(", "$", "value", "as", "$", "key", "=>", "$", "arrayValue", ")", "{", "$", "result", "[", "$", "key", "]", "=", "self", "::", "unsanitizeInputValues", "(", "$", "arrayValue", ")", ";", "}", "return", "$", "result", ";", "}", "else", "{", "return", "self", "::", "unsanitizeInputValue", "(", "$", "value", ")", ";", "}", "}" ]
Unsanitizes one or more values and returns the result. This method should be used when you need to unescape data that was obtained from the user. Some data in Piwik is stored sanitized (such as site name). In this case you may have to use this method to unsanitize it in order to, for example, output it in JSON. @param string|array $value The data to unsanitize. If an array is passed, the array is sanitized recursively. Key values are not unsanitized. @return string|array The unsanitized data. @api
[ "Unsanitizes", "one", "or", "more", "values", "and", "returns", "the", "result", "." ]
72df150735664275a60a7861e468c6ff3b152a14
https://github.com/matomo-org/matomo/blob/72df150735664275a60a7861e468c6ff3b152a14/core/Common.php#L414-L425
210,140
matomo-org/matomo
core/Common.php
Common.getRandomInt
public static function getRandomInt($min = 0, $max = null) { $rand = null; if (function_exists('random_int')) { try { if (!isset($max)) { $max = PHP_INT_MAX; } $rand = random_int($min, $max); } catch (Exception $e) { // If none of the crypto sources are available, an Exception will be thrown. $rand = null; } } if (!isset($rand)) { if (function_exists('mt_rand')) { if (!isset($max)) { $max = mt_getrandmax(); } $rand = mt_rand($min, $max); } else { if (!isset($max)) { $max = getrandmax(); } $rand = rand($min, $max); } } return $rand; }
php
public static function getRandomInt($min = 0, $max = null) { $rand = null; if (function_exists('random_int')) { try { if (!isset($max)) { $max = PHP_INT_MAX; } $rand = random_int($min, $max); } catch (Exception $e) { // If none of the crypto sources are available, an Exception will be thrown. $rand = null; } } if (!isset($rand)) { if (function_exists('mt_rand')) { if (!isset($max)) { $max = mt_getrandmax(); } $rand = mt_rand($min, $max); } else { if (!isset($max)) { $max = getrandmax(); } $rand = rand($min, $max); } } return $rand; }
[ "public", "static", "function", "getRandomInt", "(", "$", "min", "=", "0", ",", "$", "max", "=", "null", ")", "{", "$", "rand", "=", "null", ";", "if", "(", "function_exists", "(", "'random_int'", ")", ")", "{", "try", "{", "if", "(", "!", "isset", "(", "$", "max", ")", ")", "{", "$", "max", "=", "PHP_INT_MAX", ";", "}", "$", "rand", "=", "random_int", "(", "$", "min", ",", "$", "max", ")", ";", "}", "catch", "(", "Exception", "$", "e", ")", "{", "// If none of the crypto sources are available, an Exception will be thrown.", "$", "rand", "=", "null", ";", "}", "}", "if", "(", "!", "isset", "(", "$", "rand", ")", ")", "{", "if", "(", "function_exists", "(", "'mt_rand'", ")", ")", "{", "if", "(", "!", "isset", "(", "$", "max", ")", ")", "{", "$", "max", "=", "mt_getrandmax", "(", ")", ";", "}", "$", "rand", "=", "mt_rand", "(", "$", "min", ",", "$", "max", ")", ";", "}", "else", "{", "if", "(", "!", "isset", "(", "$", "max", ")", ")", "{", "$", "max", "=", "getrandmax", "(", ")", ";", "}", "$", "rand", "=", "rand", "(", "$", "min", ",", "$", "max", ")", ";", "}", "}", "return", "$", "rand", ";", "}" ]
Generates a random integer @param int $min @param null|int $max Defaults to max int value @return int|null
[ "Generates", "a", "random", "integer" ]
72df150735664275a60a7861e468c6ff3b152a14
https://github.com/matomo-org/matomo/blob/72df150735664275a60a7861e468c6ff3b152a14/core/Common.php#L565-L597
210,141
matomo-org/matomo
core/Common.php
Common.convertVisitorIdToBin
public static function convertVisitorIdToBin($id) { if (strlen($id) !== Tracker::LENGTH_HEX_ID_STRING || @bin2hex(self::hex2bin($id)) != $id ) { throw new Exception("visitorId is expected to be a " . Tracker::LENGTH_HEX_ID_STRING . " hex char string"); } return self::hex2bin($id); }
php
public static function convertVisitorIdToBin($id) { if (strlen($id) !== Tracker::LENGTH_HEX_ID_STRING || @bin2hex(self::hex2bin($id)) != $id ) { throw new Exception("visitorId is expected to be a " . Tracker::LENGTH_HEX_ID_STRING . " hex char string"); } return self::hex2bin($id); }
[ "public", "static", "function", "convertVisitorIdToBin", "(", "$", "id", ")", "{", "if", "(", "strlen", "(", "$", "id", ")", "!==", "Tracker", "::", "LENGTH_HEX_ID_STRING", "||", "@", "bin2hex", "(", "self", "::", "hex2bin", "(", "$", "id", ")", ")", "!=", "$", "id", ")", "{", "throw", "new", "Exception", "(", "\"visitorId is expected to be a \"", ".", "Tracker", "::", "LENGTH_HEX_ID_STRING", ".", "\" hex char string\"", ")", ";", "}", "return", "self", "::", "hex2bin", "(", "$", "id", ")", ";", "}" ]
This function will convert the input string to the binary representation of the ID but it will throw an Exception if the specified input ID is not correct This is used when building segments containing visitorId which could be an invalid string therefore throwing Unexpected PHP error [pack(): Type H: illegal hex digit i] severity [E_WARNING] It would be simply to silent fail the pack() call above but in all other cases, we don't expect an error, so better be safe and get the php error when something unexpected is happening @param string $id @throws Exception @return string binary string
[ "This", "function", "will", "convert", "the", "input", "string", "to", "the", "binary", "representation", "of", "the", "ID", "but", "it", "will", "throw", "an", "Exception", "if", "the", "specified", "input", "ID", "is", "not", "correct" ]
72df150735664275a60a7861e468c6ff3b152a14
https://github.com/matomo-org/matomo/blob/72df150735664275a60a7861e468c6ff3b152a14/core/Common.php#L687-L696
210,142
matomo-org/matomo
core/Common.php
Common.convertUserIdToVisitorIdBin
public static function convertUserIdToVisitorIdBin($userId) { require_once PIWIK_INCLUDE_PATH . '/libs/PiwikTracker/PiwikTracker.php'; $userIdHashed = \PiwikTracker::getUserIdHashed($userId); return self::convertVisitorIdToBin($userIdHashed); }
php
public static function convertUserIdToVisitorIdBin($userId) { require_once PIWIK_INCLUDE_PATH . '/libs/PiwikTracker/PiwikTracker.php'; $userIdHashed = \PiwikTracker::getUserIdHashed($userId); return self::convertVisitorIdToBin($userIdHashed); }
[ "public", "static", "function", "convertUserIdToVisitorIdBin", "(", "$", "userId", ")", "{", "require_once", "PIWIK_INCLUDE_PATH", ".", "'/libs/PiwikTracker/PiwikTracker.php'", ";", "$", "userIdHashed", "=", "\\", "PiwikTracker", "::", "getUserIdHashed", "(", "$", "userId", ")", ";", "return", "self", "::", "convertVisitorIdToBin", "(", "$", "userIdHashed", ")", ";", "}" ]
Converts a User ID string to the Visitor ID Binary representation. @param $userId @return string
[ "Converts", "a", "User", "ID", "string", "to", "the", "Visitor", "ID", "Binary", "representation", "." ]
72df150735664275a60a7861e468c6ff3b152a14
https://github.com/matomo-org/matomo/blob/72df150735664275a60a7861e468c6ff3b152a14/core/Common.php#L704-L710
210,143
matomo-org/matomo
core/Common.php
Common.getBrowserLanguage
public static function getBrowserLanguage($browserLang = null) { static $replacementPatterns = array( // extraneous bits of RFC 3282 that we ignore '/(\\\\.)/', // quoted-pairs '/(\s+)/', // CFWcS white space '/(\([^)]*\))/', // CFWS comments '/(;q=[0-9.]+)/', // quality // found in the LANG environment variable '/\.(.*)/', // charset (e.g., en_CA.UTF-8) '/^C$/', // POSIX 'C' locale ); if (is_null($browserLang)) { $browserLang = self::sanitizeInputValues(@$_SERVER['HTTP_ACCEPT_LANGUAGE']); if (empty($browserLang) && self::isPhpCliMode()) { $browserLang = @getenv('LANG'); } } if (empty($browserLang)) { // a fallback might be to infer the language in HTTP_USER_AGENT (i.e., localized build) $browserLang = ""; } else { // language tags are case-insensitive per HTTP/1.1 s3.10 but the region may be capitalized per ISO3166-1; // underscores are not permitted per RFC 4646 or 4647 (which obsolete RFC 1766 and 3066), // but we guard against a bad user agent which naively uses its locale $browserLang = strtolower(str_replace('_', '-', $browserLang)); // filters $browserLang = preg_replace($replacementPatterns, '', $browserLang); $browserLang = preg_replace('/((^|,)chrome:.*)/', '', $browserLang, 1); // Firefox bug $browserLang = preg_replace('/(,)(?:en-securid,)|(?:(^|,)en-securid(,|$))/', '$1', $browserLang, 1); // unregistered language tag $browserLang = str_replace('sr-sp', 'sr-rs', $browserLang); // unofficial (proposed) code in the wild } return $browserLang; }
php
public static function getBrowserLanguage($browserLang = null) { static $replacementPatterns = array( // extraneous bits of RFC 3282 that we ignore '/(\\\\.)/', // quoted-pairs '/(\s+)/', // CFWcS white space '/(\([^)]*\))/', // CFWS comments '/(;q=[0-9.]+)/', // quality // found in the LANG environment variable '/\.(.*)/', // charset (e.g., en_CA.UTF-8) '/^C$/', // POSIX 'C' locale ); if (is_null($browserLang)) { $browserLang = self::sanitizeInputValues(@$_SERVER['HTTP_ACCEPT_LANGUAGE']); if (empty($browserLang) && self::isPhpCliMode()) { $browserLang = @getenv('LANG'); } } if (empty($browserLang)) { // a fallback might be to infer the language in HTTP_USER_AGENT (i.e., localized build) $browserLang = ""; } else { // language tags are case-insensitive per HTTP/1.1 s3.10 but the region may be capitalized per ISO3166-1; // underscores are not permitted per RFC 4646 or 4647 (which obsolete RFC 1766 and 3066), // but we guard against a bad user agent which naively uses its locale $browserLang = strtolower(str_replace('_', '-', $browserLang)); // filters $browserLang = preg_replace($replacementPatterns, '', $browserLang); $browserLang = preg_replace('/((^|,)chrome:.*)/', '', $browserLang, 1); // Firefox bug $browserLang = preg_replace('/(,)(?:en-securid,)|(?:(^|,)en-securid(,|$))/', '$1', $browserLang, 1); // unregistered language tag $browserLang = str_replace('sr-sp', 'sr-rs', $browserLang); // unofficial (proposed) code in the wild } return $browserLang; }
[ "public", "static", "function", "getBrowserLanguage", "(", "$", "browserLang", "=", "null", ")", "{", "static", "$", "replacementPatterns", "=", "array", "(", "// extraneous bits of RFC 3282 that we ignore", "'/(\\\\\\\\.)/'", ",", "// quoted-pairs", "'/(\\s+)/'", ",", "// CFWcS white space", "'/(\\([^)]*\\))/'", ",", "// CFWS comments", "'/(;q=[0-9.]+)/'", ",", "// quality", "// found in the LANG environment variable", "'/\\.(.*)/'", ",", "// charset (e.g., en_CA.UTF-8)", "'/^C$/'", ",", "// POSIX 'C' locale", ")", ";", "if", "(", "is_null", "(", "$", "browserLang", ")", ")", "{", "$", "browserLang", "=", "self", "::", "sanitizeInputValues", "(", "@", "$", "_SERVER", "[", "'HTTP_ACCEPT_LANGUAGE'", "]", ")", ";", "if", "(", "empty", "(", "$", "browserLang", ")", "&&", "self", "::", "isPhpCliMode", "(", ")", ")", "{", "$", "browserLang", "=", "@", "getenv", "(", "'LANG'", ")", ";", "}", "}", "if", "(", "empty", "(", "$", "browserLang", ")", ")", "{", "// a fallback might be to infer the language in HTTP_USER_AGENT (i.e., localized build)", "$", "browserLang", "=", "\"\"", ";", "}", "else", "{", "// language tags are case-insensitive per HTTP/1.1 s3.10 but the region may be capitalized per ISO3166-1;", "// underscores are not permitted per RFC 4646 or 4647 (which obsolete RFC 1766 and 3066),", "// but we guard against a bad user agent which naively uses its locale", "$", "browserLang", "=", "strtolower", "(", "str_replace", "(", "'_'", ",", "'-'", ",", "$", "browserLang", ")", ")", ";", "// filters", "$", "browserLang", "=", "preg_replace", "(", "$", "replacementPatterns", ",", "''", ",", "$", "browserLang", ")", ";", "$", "browserLang", "=", "preg_replace", "(", "'/((^|,)chrome:.*)/'", ",", "''", ",", "$", "browserLang", ",", "1", ")", ";", "// Firefox bug", "$", "browserLang", "=", "preg_replace", "(", "'/(,)(?:en-securid,)|(?:(^|,)en-securid(,|$))/'", ",", "'$1'", ",", "$", "browserLang", ",", "1", ")", ";", "// unregistered language tag", "$", "browserLang", "=", "str_replace", "(", "'sr-sp'", ",", "'sr-rs'", ",", "$", "browserLang", ")", ";", "// unofficial (proposed) code in the wild", "}", "return", "$", "browserLang", ";", "}" ]
Returns the browser language code, eg. "en-gb,en;q=0.5" @param string|null $browserLang Optional browser language, otherwise taken from the request header @return string
[ "Returns", "the", "browser", "language", "code", "eg", ".", "en", "-", "gb", "en", ";", "q", "=", "0", ".", "5" ]
72df150735664275a60a7861e468c6ff3b152a14
https://github.com/matomo-org/matomo/blob/72df150735664275a60a7861e468c6ff3b152a14/core/Common.php#L900-L940
210,144
matomo-org/matomo
core/Common.php
Common.getCountry
public static function getCountry($lang, $enableLanguageToCountryGuess, $ip) { if (empty($lang) || strlen($lang) < 2 || $lang == self::LANGUAGE_CODE_INVALID) { return self::LANGUAGE_CODE_INVALID; } /** @var RegionDataProvider $dataProvider */ $dataProvider = StaticContainer::get('Piwik\Intl\Data\Provider\RegionDataProvider'); $validCountries = $dataProvider->getCountryList(); return self::extractCountryCodeFromBrowserLanguage($lang, $validCountries, $enableLanguageToCountryGuess); }
php
public static function getCountry($lang, $enableLanguageToCountryGuess, $ip) { if (empty($lang) || strlen($lang) < 2 || $lang == self::LANGUAGE_CODE_INVALID) { return self::LANGUAGE_CODE_INVALID; } /** @var RegionDataProvider $dataProvider */ $dataProvider = StaticContainer::get('Piwik\Intl\Data\Provider\RegionDataProvider'); $validCountries = $dataProvider->getCountryList(); return self::extractCountryCodeFromBrowserLanguage($lang, $validCountries, $enableLanguageToCountryGuess); }
[ "public", "static", "function", "getCountry", "(", "$", "lang", ",", "$", "enableLanguageToCountryGuess", ",", "$", "ip", ")", "{", "if", "(", "empty", "(", "$", "lang", ")", "||", "strlen", "(", "$", "lang", ")", "<", "2", "||", "$", "lang", "==", "self", "::", "LANGUAGE_CODE_INVALID", ")", "{", "return", "self", "::", "LANGUAGE_CODE_INVALID", ";", "}", "/** @var RegionDataProvider $dataProvider */", "$", "dataProvider", "=", "StaticContainer", "::", "get", "(", "'Piwik\\Intl\\Data\\Provider\\RegionDataProvider'", ")", ";", "$", "validCountries", "=", "$", "dataProvider", "->", "getCountryList", "(", ")", ";", "return", "self", "::", "extractCountryCodeFromBrowserLanguage", "(", "$", "lang", ",", "$", "validCountries", ",", "$", "enableLanguageToCountryGuess", ")", ";", "}" ]
Returns the visitor country based on the Browser 'accepted language' information, but provides a hook for geolocation via IP address. @param string $lang browser lang @param bool $enableLanguageToCountryGuess If set to true, some assumption will be made and detection guessed more often, but accuracy could be affected @param string $ip @return string 2 letter ISO code
[ "Returns", "the", "visitor", "country", "based", "on", "the", "Browser", "accepted", "language", "information", "but", "provides", "a", "hook", "for", "geolocation", "via", "IP", "address", "." ]
72df150735664275a60a7861e468c6ff3b152a14
https://github.com/matomo-org/matomo/blob/72df150735664275a60a7861e468c6ff3b152a14/core/Common.php#L951-L963
210,145
matomo-org/matomo
core/Common.php
Common.extractCountryCodeFromBrowserLanguage
public static function extractCountryCodeFromBrowserLanguage($browserLanguage, $validCountries, $enableLanguageToCountryGuess) { /** @var LanguageDataProvider $dataProvider */ $dataProvider = StaticContainer::get('Piwik\Intl\Data\Provider\LanguageDataProvider'); $langToCountry = $dataProvider->getLanguageToCountryList(); if ($enableLanguageToCountryGuess) { if (preg_match('/^([a-z]{2,3})(?:,|;|$)/', $browserLanguage, $matches)) { // match language (without region) to infer the country of origin if (array_key_exists($matches[1], $langToCountry)) { return $langToCountry[$matches[1]]; } } } if (!empty($validCountries) && preg_match_all('/[-]([a-z]{2})/', $browserLanguage, $matches, PREG_SET_ORDER)) { foreach ($matches as $parts) { // match location; we don't make any inferences from the language if (array_key_exists($parts[1], $validCountries)) { return $parts[1]; } } } return self::LANGUAGE_CODE_INVALID; }
php
public static function extractCountryCodeFromBrowserLanguage($browserLanguage, $validCountries, $enableLanguageToCountryGuess) { /** @var LanguageDataProvider $dataProvider */ $dataProvider = StaticContainer::get('Piwik\Intl\Data\Provider\LanguageDataProvider'); $langToCountry = $dataProvider->getLanguageToCountryList(); if ($enableLanguageToCountryGuess) { if (preg_match('/^([a-z]{2,3})(?:,|;|$)/', $browserLanguage, $matches)) { // match language (without region) to infer the country of origin if (array_key_exists($matches[1], $langToCountry)) { return $langToCountry[$matches[1]]; } } } if (!empty($validCountries) && preg_match_all('/[-]([a-z]{2})/', $browserLanguage, $matches, PREG_SET_ORDER)) { foreach ($matches as $parts) { // match location; we don't make any inferences from the language if (array_key_exists($parts[1], $validCountries)) { return $parts[1]; } } } return self::LANGUAGE_CODE_INVALID; }
[ "public", "static", "function", "extractCountryCodeFromBrowserLanguage", "(", "$", "browserLanguage", ",", "$", "validCountries", ",", "$", "enableLanguageToCountryGuess", ")", "{", "/** @var LanguageDataProvider $dataProvider */", "$", "dataProvider", "=", "StaticContainer", "::", "get", "(", "'Piwik\\Intl\\Data\\Provider\\LanguageDataProvider'", ")", ";", "$", "langToCountry", "=", "$", "dataProvider", "->", "getLanguageToCountryList", "(", ")", ";", "if", "(", "$", "enableLanguageToCountryGuess", ")", "{", "if", "(", "preg_match", "(", "'/^([a-z]{2,3})(?:,|;|$)/'", ",", "$", "browserLanguage", ",", "$", "matches", ")", ")", "{", "// match language (without region) to infer the country of origin", "if", "(", "array_key_exists", "(", "$", "matches", "[", "1", "]", ",", "$", "langToCountry", ")", ")", "{", "return", "$", "langToCountry", "[", "$", "matches", "[", "1", "]", "]", ";", "}", "}", "}", "if", "(", "!", "empty", "(", "$", "validCountries", ")", "&&", "preg_match_all", "(", "'/[-]([a-z]{2})/'", ",", "$", "browserLanguage", ",", "$", "matches", ",", "PREG_SET_ORDER", ")", ")", "{", "foreach", "(", "$", "matches", "as", "$", "parts", ")", "{", "// match location; we don't make any inferences from the language", "if", "(", "array_key_exists", "(", "$", "parts", "[", "1", "]", ",", "$", "validCountries", ")", ")", "{", "return", "$", "parts", "[", "1", "]", ";", "}", "}", "}", "return", "self", "::", "LANGUAGE_CODE_INVALID", ";", "}" ]
Returns list of valid country codes @param string $browserLanguage @param array $validCountries Array of valid countries @param bool $enableLanguageToCountryGuess (if true, will guess country based on language that lacks region information) @return array Array of 2 letter ISO codes
[ "Returns", "list", "of", "valid", "country", "codes" ]
72df150735664275a60a7861e468c6ff3b152a14
https://github.com/matomo-org/matomo/blob/72df150735664275a60a7861e468c6ff3b152a14/core/Common.php#L973-L998
210,146
matomo-org/matomo
core/Common.php
Common.getContinent
public static function getContinent($country) { /** @var RegionDataProvider $dataProvider */ $dataProvider = StaticContainer::get('Piwik\Intl\Data\Provider\RegionDataProvider'); $countryList = $dataProvider->getCountryList(); if ($country == 'ti') { $country = 'cn'; } return isset($countryList[$country]) ? $countryList[$country] : 'unk'; }
php
public static function getContinent($country) { /** @var RegionDataProvider $dataProvider */ $dataProvider = StaticContainer::get('Piwik\Intl\Data\Provider\RegionDataProvider'); $countryList = $dataProvider->getCountryList(); if ($country == 'ti') { $country = 'cn'; } return isset($countryList[$country]) ? $countryList[$country] : 'unk'; }
[ "public", "static", "function", "getContinent", "(", "$", "country", ")", "{", "/** @var RegionDataProvider $dataProvider */", "$", "dataProvider", "=", "StaticContainer", "::", "get", "(", "'Piwik\\Intl\\Data\\Provider\\RegionDataProvider'", ")", ";", "$", "countryList", "=", "$", "dataProvider", "->", "getCountryList", "(", ")", ";", "if", "(", "$", "country", "==", "'ti'", ")", "{", "$", "country", "=", "'cn'", ";", "}", "return", "isset", "(", "$", "countryList", "[", "$", "country", "]", ")", "?", "$", "countryList", "[", "$", "country", "]", ":", "'unk'", ";", "}" ]
Returns the continent of a given country @param string $country 2 letters iso code @return string Continent (3 letters code : afr, asi, eur, amn, ams, oce)
[ "Returns", "the", "continent", "of", "a", "given", "country" ]
72df150735664275a60a7861e468c6ff3b152a14
https://github.com/matomo-org/matomo/blob/72df150735664275a60a7861e468c6ff3b152a14/core/Common.php#L1073-L1085
210,147
matomo-org/matomo
core/Common.php
Common.getCampaignParameters
public static function getCampaignParameters() { $return = array( Config::getInstance()->Tracker['campaign_var_name'], Config::getInstance()->Tracker['campaign_keyword_var_name'], ); foreach ($return as &$list) { if (strpos($list, ',') !== false) { $list = explode(',', $list); } else { $list = array($list); } $list = array_map('trim', $list); } return $return; }
php
public static function getCampaignParameters() { $return = array( Config::getInstance()->Tracker['campaign_var_name'], Config::getInstance()->Tracker['campaign_keyword_var_name'], ); foreach ($return as &$list) { if (strpos($list, ',') !== false) { $list = explode(',', $list); } else { $list = array($list); } $list = array_map('trim', $list); } return $return; }
[ "public", "static", "function", "getCampaignParameters", "(", ")", "{", "$", "return", "=", "array", "(", "Config", "::", "getInstance", "(", ")", "->", "Tracker", "[", "'campaign_var_name'", "]", ",", "Config", "::", "getInstance", "(", ")", "->", "Tracker", "[", "'campaign_keyword_var_name'", "]", ",", ")", ";", "foreach", "(", "$", "return", "as", "&", "$", "list", ")", "{", "if", "(", "strpos", "(", "$", "list", ",", "','", ")", "!==", "false", ")", "{", "$", "list", "=", "explode", "(", "','", ",", "$", "list", ")", ";", "}", "else", "{", "$", "list", "=", "array", "(", "$", "list", ")", ";", "}", "$", "list", "=", "array_map", "(", "'trim'", ",", "$", "list", ")", ";", "}", "return", "$", "return", ";", "}" ]
Returns the list of Campaign parameter names that will be read to classify a visit as coming from a Campaign @return array array( 0 => array( ... ) // campaign names parameters 1 => array( ... ) // campaign keyword parameters );
[ "Returns", "the", "list", "of", "Campaign", "parameter", "names", "that", "will", "be", "read", "to", "classify", "a", "visit", "as", "coming", "from", "a", "Campaign" ]
72df150735664275a60a7861e468c6ff3b152a14
https://github.com/matomo-org/matomo/blob/72df150735664275a60a7861e468c6ff3b152a14/core/Common.php#L1100-L1117
210,148
matomo-org/matomo
core/Common.php
Common.sendHeader
public static function sendHeader($header, $replace = true) { // don't send header in CLI mode if (!Common::isPhpCliMode() and !headers_sent()) { header($header, $replace); } }
php
public static function sendHeader($header, $replace = true) { // don't send header in CLI mode if (!Common::isPhpCliMode() and !headers_sent()) { header($header, $replace); } }
[ "public", "static", "function", "sendHeader", "(", "$", "header", ",", "$", "replace", "=", "true", ")", "{", "// don't send header in CLI mode", "if", "(", "!", "Common", "::", "isPhpCliMode", "(", ")", "and", "!", "headers_sent", "(", ")", ")", "{", "header", "(", "$", "header", ",", "$", "replace", ")", ";", "}", "}" ]
Sets outgoing header. @param string $header The header. @param bool $replace Whether to replace existing or not.
[ "Sets", "outgoing", "header", "." ]
72df150735664275a60a7861e468c6ff3b152a14
https://github.com/matomo-org/matomo/blob/72df150735664275a60a7861e468c6ff3b152a14/core/Common.php#L1168-L1174
210,149
matomo-org/matomo
core/Common.php
Common.sendResponseCode
public static function sendResponseCode($code) { $messages = array( 200 => 'Ok', 204 => 'No Response', 301 => 'Moved Permanently', 302 => 'Found', 304 => 'Not Modified', 400 => 'Bad Request', 401 => 'Unauthorized', 403 => 'Forbidden', 404 => 'Not Found', 500 => 'Internal Server Error', 503 => 'Service Unavailable', ); if (!array_key_exists($code, $messages)) { throw new Exception('Response code not supported: ' . $code); } if (strpos(PHP_SAPI, '-fcgi') === false) { $key = 'HTTP/1.1'; if (array_key_exists('SERVER_PROTOCOL', $_SERVER) && strlen($_SERVER['SERVER_PROTOCOL']) < 15 && strlen($_SERVER['SERVER_PROTOCOL']) > 1) { $key = $_SERVER['SERVER_PROTOCOL']; } } else { // FastCGI $key = 'Status:'; } $message = $messages[$code]; Common::sendHeader($key . ' ' . $code . ' ' . $message); }
php
public static function sendResponseCode($code) { $messages = array( 200 => 'Ok', 204 => 'No Response', 301 => 'Moved Permanently', 302 => 'Found', 304 => 'Not Modified', 400 => 'Bad Request', 401 => 'Unauthorized', 403 => 'Forbidden', 404 => 'Not Found', 500 => 'Internal Server Error', 503 => 'Service Unavailable', ); if (!array_key_exists($code, $messages)) { throw new Exception('Response code not supported: ' . $code); } if (strpos(PHP_SAPI, '-fcgi') === false) { $key = 'HTTP/1.1'; if (array_key_exists('SERVER_PROTOCOL', $_SERVER) && strlen($_SERVER['SERVER_PROTOCOL']) < 15 && strlen($_SERVER['SERVER_PROTOCOL']) > 1) { $key = $_SERVER['SERVER_PROTOCOL']; } } else { // FastCGI $key = 'Status:'; } $message = $messages[$code]; Common::sendHeader($key . ' ' . $code . ' ' . $message); }
[ "public", "static", "function", "sendResponseCode", "(", "$", "code", ")", "{", "$", "messages", "=", "array", "(", "200", "=>", "'Ok'", ",", "204", "=>", "'No Response'", ",", "301", "=>", "'Moved Permanently'", ",", "302", "=>", "'Found'", ",", "304", "=>", "'Not Modified'", ",", "400", "=>", "'Bad Request'", ",", "401", "=>", "'Unauthorized'", ",", "403", "=>", "'Forbidden'", ",", "404", "=>", "'Not Found'", ",", "500", "=>", "'Internal Server Error'", ",", "503", "=>", "'Service Unavailable'", ",", ")", ";", "if", "(", "!", "array_key_exists", "(", "$", "code", ",", "$", "messages", ")", ")", "{", "throw", "new", "Exception", "(", "'Response code not supported: '", ".", "$", "code", ")", ";", "}", "if", "(", "strpos", "(", "PHP_SAPI", ",", "'-fcgi'", ")", "===", "false", ")", "{", "$", "key", "=", "'HTTP/1.1'", ";", "if", "(", "array_key_exists", "(", "'SERVER_PROTOCOL'", ",", "$", "_SERVER", ")", "&&", "strlen", "(", "$", "_SERVER", "[", "'SERVER_PROTOCOL'", "]", ")", "<", "15", "&&", "strlen", "(", "$", "_SERVER", "[", "'SERVER_PROTOCOL'", "]", ")", ">", "1", ")", "{", "$", "key", "=", "$", "_SERVER", "[", "'SERVER_PROTOCOL'", "]", ";", "}", "}", "else", "{", "// FastCGI", "$", "key", "=", "'Status:'", ";", "}", "$", "message", "=", "$", "messages", "[", "$", "code", "]", ";", "Common", "::", "sendHeader", "(", "$", "key", ".", "' '", ".", "$", "code", ".", "' '", ".", "$", "message", ")", ";", "}" ]
Sends the given response code if supported. @param int $code Eg 204 @throws Exception
[ "Sends", "the", "given", "response", "code", "if", "supported", "." ]
72df150735664275a60a7861e468c6ff3b152a14
https://github.com/matomo-org/matomo/blob/72df150735664275a60a7861e468c6ff3b152a14/core/Common.php#L1196-L1231
210,150
matomo-org/matomo
core/Period/Year.php
Year.toString
public function toString($format = 'ignored') { $this->generate(); $stringMonth = array(); foreach ($this->subperiods as $month) { $stringMonth[] = $month->getDateStart()->toString("Y") . "-" . $month->getDateStart()->toString("m") . "-01"; } return $stringMonth; }
php
public function toString($format = 'ignored') { $this->generate(); $stringMonth = array(); foreach ($this->subperiods as $month) { $stringMonth[] = $month->getDateStart()->toString("Y") . "-" . $month->getDateStart()->toString("m") . "-01"; } return $stringMonth; }
[ "public", "function", "toString", "(", "$", "format", "=", "'ignored'", ")", "{", "$", "this", "->", "generate", "(", ")", ";", "$", "stringMonth", "=", "array", "(", ")", ";", "foreach", "(", "$", "this", "->", "subperiods", "as", "$", "month", ")", "{", "$", "stringMonth", "[", "]", "=", "$", "month", "->", "getDateStart", "(", ")", "->", "toString", "(", "\"Y\"", ")", ".", "\"-\"", ".", "$", "month", "->", "getDateStart", "(", ")", "->", "toString", "(", "\"m\"", ")", ".", "\"-01\"", ";", "}", "return", "$", "stringMonth", ";", "}" ]
Returns the current period as a string @param string $format @return array
[ "Returns", "the", "current", "period", "as", "a", "string" ]
72df150735664275a60a7861e468c6ff3b152a14
https://github.com/matomo-org/matomo/blob/72df150735664275a60a7861e468c6ff3b152a14/core/Period/Year.php#L81-L91
210,151
matomo-org/matomo
plugins/UserId/API.php
API.getUsers
public function getUsers($idSite, $period, $date, $segment = false) { Piwik::checkUserHasViewAccess($idSite); $archive = Archive::build($idSite, $period, $date, $segment); $dataTable = $archive->getDataTable(Archiver::USERID_ARCHIVE_RECORD); $dataTable->queueFilter('ReplaceColumnNames'); $dataTable->queueFilter('ReplaceSummaryRowLabel'); return $dataTable; }
php
public function getUsers($idSite, $period, $date, $segment = false) { Piwik::checkUserHasViewAccess($idSite); $archive = Archive::build($idSite, $period, $date, $segment); $dataTable = $archive->getDataTable(Archiver::USERID_ARCHIVE_RECORD); $dataTable->queueFilter('ReplaceColumnNames'); $dataTable->queueFilter('ReplaceSummaryRowLabel'); return $dataTable; }
[ "public", "function", "getUsers", "(", "$", "idSite", ",", "$", "period", ",", "$", "date", ",", "$", "segment", "=", "false", ")", "{", "Piwik", "::", "checkUserHasViewAccess", "(", "$", "idSite", ")", ";", "$", "archive", "=", "Archive", "::", "build", "(", "$", "idSite", ",", "$", "period", ",", "$", "date", ",", "$", "segment", ")", ";", "$", "dataTable", "=", "$", "archive", "->", "getDataTable", "(", "Archiver", "::", "USERID_ARCHIVE_RECORD", ")", ";", "$", "dataTable", "->", "queueFilter", "(", "'ReplaceColumnNames'", ")", ";", "$", "dataTable", "->", "queueFilter", "(", "'ReplaceSummaryRowLabel'", ")", ";", "return", "$", "dataTable", ";", "}" ]
Get a report of all User Ids. @param int $idSite @param string $period @param int $date @param string|bool $segment @return DataTable
[ "Get", "a", "report", "of", "all", "User", "Ids", "." ]
72df150735664275a60a7861e468c6ff3b152a14
https://github.com/matomo-org/matomo/blob/72df150735664275a60a7861e468c6ff3b152a14/plugins/UserId/API.php#L35-L45
210,152
matomo-org/matomo
core/Tracker/Db/Mysqli.php
Mysqli.fetchAll
public function fetchAll($query, $parameters = array()) { try { if (self::$profiling) { $timer = $this->initProfiler(); } $rows = array(); $query = $this->prepare($query, $parameters); $rs = mysqli_query($this->connection, $query); if (is_bool($rs)) { throw new DbException('fetchAll() failed: ' . mysqli_error($this->connection) . ' : ' . $query); } while ($row = mysqli_fetch_array($rs, MYSQLI_ASSOC)) { $rows[] = $row; } mysqli_free_result($rs); if (self::$profiling && isset($timer)) { $this->recordQueryProfile($query, $timer); } return $rows; } catch (Exception $e) { throw new DbException("Error query: " . $e->getMessage()); } }
php
public function fetchAll($query, $parameters = array()) { try { if (self::$profiling) { $timer = $this->initProfiler(); } $rows = array(); $query = $this->prepare($query, $parameters); $rs = mysqli_query($this->connection, $query); if (is_bool($rs)) { throw new DbException('fetchAll() failed: ' . mysqli_error($this->connection) . ' : ' . $query); } while ($row = mysqli_fetch_array($rs, MYSQLI_ASSOC)) { $rows[] = $row; } mysqli_free_result($rs); if (self::$profiling && isset($timer)) { $this->recordQueryProfile($query, $timer); } return $rows; } catch (Exception $e) { throw new DbException("Error query: " . $e->getMessage()); } }
[ "public", "function", "fetchAll", "(", "$", "query", ",", "$", "parameters", "=", "array", "(", ")", ")", "{", "try", "{", "if", "(", "self", "::", "$", "profiling", ")", "{", "$", "timer", "=", "$", "this", "->", "initProfiler", "(", ")", ";", "}", "$", "rows", "=", "array", "(", ")", ";", "$", "query", "=", "$", "this", "->", "prepare", "(", "$", "query", ",", "$", "parameters", ")", ";", "$", "rs", "=", "mysqli_query", "(", "$", "this", "->", "connection", ",", "$", "query", ")", ";", "if", "(", "is_bool", "(", "$", "rs", ")", ")", "{", "throw", "new", "DbException", "(", "'fetchAll() failed: '", ".", "mysqli_error", "(", "$", "this", "->", "connection", ")", ".", "' : '", ".", "$", "query", ")", ";", "}", "while", "(", "$", "row", "=", "mysqli_fetch_array", "(", "$", "rs", ",", "MYSQLI_ASSOC", ")", ")", "{", "$", "rows", "[", "]", "=", "$", "row", ";", "}", "mysqli_free_result", "(", "$", "rs", ")", ";", "if", "(", "self", "::", "$", "profiling", "&&", "isset", "(", "$", "timer", ")", ")", "{", "$", "this", "->", "recordQueryProfile", "(", "$", "query", ",", "$", "timer", ")", ";", "}", "return", "$", "rows", ";", "}", "catch", "(", "Exception", "$", "e", ")", "{", "throw", "new", "DbException", "(", "\"Error query: \"", ".", "$", "e", "->", "getMessage", "(", ")", ")", ";", "}", "}" ]
Returns an array containing all the rows of a query result, using optional bound parameters. @see query() @param string $query Query @param array $parameters Parameters to bind @return array @throws Exception|DbException if an exception occurred
[ "Returns", "an", "array", "containing", "all", "the", "rows", "of", "a", "query", "result", "using", "optional", "bound", "parameters", "." ]
72df150735664275a60a7861e468c6ff3b152a14
https://github.com/matomo-org/matomo/blob/72df150735664275a60a7861e468c6ff3b152a14/core/Tracker/Db/Mysqli.php#L161-L187
210,153
matomo-org/matomo
core/Tracker/Db/Mysqli.php
Mysqli.prepare
private function prepare($query, $parameters) { if (!$parameters) { $parameters = array(); } elseif (!is_array($parameters)) { $parameters = array($parameters); } $this->paramNb = 0; $this->params = & $parameters; $query = preg_replace_callback('/\?/', array($this, 'replaceParam'), $query); return $query; }
php
private function prepare($query, $parameters) { if (!$parameters) { $parameters = array(); } elseif (!is_array($parameters)) { $parameters = array($parameters); } $this->paramNb = 0; $this->params = & $parameters; $query = preg_replace_callback('/\?/', array($this, 'replaceParam'), $query); return $query; }
[ "private", "function", "prepare", "(", "$", "query", ",", "$", "parameters", ")", "{", "if", "(", "!", "$", "parameters", ")", "{", "$", "parameters", "=", "array", "(", ")", ";", "}", "elseif", "(", "!", "is_array", "(", "$", "parameters", ")", ")", "{", "$", "parameters", "=", "array", "(", "$", "parameters", ")", ";", "}", "$", "this", "->", "paramNb", "=", "0", ";", "$", "this", "->", "params", "=", "&", "$", "parameters", ";", "$", "query", "=", "preg_replace_callback", "(", "'/\\?/'", ",", "array", "(", "$", "this", ",", "'replaceParam'", ")", ",", "$", "query", ")", ";", "return", "$", "query", ";", "}" ]
Input is a prepared SQL statement and parameters Returns the SQL statement @param string $query @param array $parameters @return string
[ "Input", "is", "a", "prepared", "SQL", "statement", "and", "parameters", "Returns", "the", "SQL", "statement" ]
72df150735664275a60a7861e468c6ff3b152a14
https://github.com/matomo-org/matomo/blob/72df150735664275a60a7861e468c6ff3b152a14/core/Tracker/Db/Mysqli.php#L281-L294
210,154
matomo-org/matomo
plugins/CustomVariables/CustomVariables.php
CustomVariables.getNumUsableCustomVariables
public static function getNumUsableCustomVariables() { $cache = Cache::getCacheGeneral(); $cacheKey = self::MAX_NUM_CUSTOMVARS_CACHEKEY; if (!array_key_exists($cacheKey, $cache)) { $minCustomVar = null; foreach (Model::getScopes() as $scope) { $model = new Model($scope); $highestIndex = $model->getHighestCustomVarIndex(); if (!isset($minCustomVar)) { $minCustomVar = $highestIndex; } if ($highestIndex < $minCustomVar) { $minCustomVar = $highestIndex; } } if (!isset($minCustomVar)) { $minCustomVar = 0; } $cache[$cacheKey] = $minCustomVar; Cache::setCacheGeneral($cache); } return $cache[$cacheKey]; }
php
public static function getNumUsableCustomVariables() { $cache = Cache::getCacheGeneral(); $cacheKey = self::MAX_NUM_CUSTOMVARS_CACHEKEY; if (!array_key_exists($cacheKey, $cache)) { $minCustomVar = null; foreach (Model::getScopes() as $scope) { $model = new Model($scope); $highestIndex = $model->getHighestCustomVarIndex(); if (!isset($minCustomVar)) { $minCustomVar = $highestIndex; } if ($highestIndex < $minCustomVar) { $minCustomVar = $highestIndex; } } if (!isset($minCustomVar)) { $minCustomVar = 0; } $cache[$cacheKey] = $minCustomVar; Cache::setCacheGeneral($cache); } return $cache[$cacheKey]; }
[ "public", "static", "function", "getNumUsableCustomVariables", "(", ")", "{", "$", "cache", "=", "Cache", "::", "getCacheGeneral", "(", ")", ";", "$", "cacheKey", "=", "self", "::", "MAX_NUM_CUSTOMVARS_CACHEKEY", ";", "if", "(", "!", "array_key_exists", "(", "$", "cacheKey", ",", "$", "cache", ")", ")", "{", "$", "minCustomVar", "=", "null", ";", "foreach", "(", "Model", "::", "getScopes", "(", ")", "as", "$", "scope", ")", "{", "$", "model", "=", "new", "Model", "(", "$", "scope", ")", ";", "$", "highestIndex", "=", "$", "model", "->", "getHighestCustomVarIndex", "(", ")", ";", "if", "(", "!", "isset", "(", "$", "minCustomVar", ")", ")", "{", "$", "minCustomVar", "=", "$", "highestIndex", ";", "}", "if", "(", "$", "highestIndex", "<", "$", "minCustomVar", ")", "{", "$", "minCustomVar", "=", "$", "highestIndex", ";", "}", "}", "if", "(", "!", "isset", "(", "$", "minCustomVar", ")", ")", "{", "$", "minCustomVar", "=", "0", ";", "}", "$", "cache", "[", "$", "cacheKey", "]", "=", "$", "minCustomVar", ";", "Cache", "::", "setCacheGeneral", "(", "$", "cache", ")", ";", "}", "return", "$", "cache", "[", "$", "cacheKey", "]", ";", "}" ]
Returns the number of available custom variables that can be used. "Can be used" is identifed by the minimum number of available custom variables across all relevant tables. Eg if there are 6 custom variables installed in log_visit but only 5 in log_conversion, we consider only 5 custom variables as usable. @return int
[ "Returns", "the", "number", "of", "available", "custom", "variables", "that", "can", "be", "used", "." ]
72df150735664275a60a7861e468c6ff3b152a14
https://github.com/matomo-org/matomo/blob/72df150735664275a60a7861e468c6ff3b152a14/plugins/CustomVariables/CustomVariables.php#L76-L107
210,155
matomo-org/matomo
core/DeviceDetectorCache.php
DeviceDetectorCache.fetch
public function fetch($id) { if (empty($id)) { return false; } if (array_key_exists($id, self::$staticCache)) { return self::$staticCache[$id]; } if (!$this->cache->contains($id)) { return false; } return $this->cache->fetch($id); }
php
public function fetch($id) { if (empty($id)) { return false; } if (array_key_exists($id, self::$staticCache)) { return self::$staticCache[$id]; } if (!$this->cache->contains($id)) { return false; } return $this->cache->fetch($id); }
[ "public", "function", "fetch", "(", "$", "id", ")", "{", "if", "(", "empty", "(", "$", "id", ")", ")", "{", "return", "false", ";", "}", "if", "(", "array_key_exists", "(", "$", "id", ",", "self", "::", "$", "staticCache", ")", ")", "{", "return", "self", "::", "$", "staticCache", "[", "$", "id", "]", ";", "}", "if", "(", "!", "$", "this", "->", "cache", "->", "contains", "(", "$", "id", ")", ")", "{", "return", "false", ";", "}", "return", "$", "this", "->", "cache", "->", "fetch", "(", "$", "id", ")", ";", "}" ]
Function to fetch a cache entry @param string $id The cache entry ID @return array|bool False on error, or array the cache content
[ "Function", "to", "fetch", "a", "cache", "entry" ]
72df150735664275a60a7861e468c6ff3b152a14
https://github.com/matomo-org/matomo/blob/72df150735664275a60a7861e468c6ff3b152a14/core/DeviceDetectorCache.php#L39-L54
210,156
matomo-org/matomo
core/DeviceDetectorCache.php
DeviceDetectorCache.save
public function save($id, $content, $ttl=0) { if (empty($id)) { return false; } self::$staticCache[$id] = $content; return $this->cache->save($id, $content, $this->ttl); }
php
public function save($id, $content, $ttl=0) { if (empty($id)) { return false; } self::$staticCache[$id] = $content; return $this->cache->save($id, $content, $this->ttl); }
[ "public", "function", "save", "(", "$", "id", ",", "$", "content", ",", "$", "ttl", "=", "0", ")", "{", "if", "(", "empty", "(", "$", "id", ")", ")", "{", "return", "false", ";", "}", "self", "::", "$", "staticCache", "[", "$", "id", "]", "=", "$", "content", ";", "return", "$", "this", "->", "cache", "->", "save", "(", "$", "id", ",", "$", "content", ",", "$", "this", "->", "ttl", ")", ";", "}" ]
A function to store content a cache entry. @param string $id The cache entry ID @param array $content The cache content @throws \Exception @return bool True if the entry was successfully stored
[ "A", "function", "to", "store", "content", "a", "cache", "entry", "." ]
72df150735664275a60a7861e468c6ff3b152a14
https://github.com/matomo-org/matomo/blob/72df150735664275a60a7861e468c6ff3b152a14/core/DeviceDetectorCache.php#L64-L73
210,157
matomo-org/matomo
core/Site.php
Site.setSites
public static function setSites($sites) { self::triggerSetSitesEvent($sites); foreach ($sites as $idsite => $site) { self::setSiteFromArray($idsite, $site); } }
php
public static function setSites($sites) { self::triggerSetSitesEvent($sites); foreach ($sites as $idsite => $site) { self::setSiteFromArray($idsite, $site); } }
[ "public", "static", "function", "setSites", "(", "$", "sites", ")", "{", "self", "::", "triggerSetSitesEvent", "(", "$", "sites", ")", ";", "foreach", "(", "$", "sites", "as", "$", "idsite", "=>", "$", "site", ")", "{", "self", "::", "setSiteFromArray", "(", "$", "idsite", ",", "$", "site", ")", ";", "}", "}" ]
Sets the cached site data with an array that associates site IDs with individual site data. @param array $sites The array of sites data. Indexed by site ID. eg, array('1' => array('name' => 'Site 1', ...), '2' => array('name' => 'Site 2', ...))`
[ "Sets", "the", "cached", "site", "data", "with", "an", "array", "that", "associates", "site", "IDs", "with", "individual", "site", "data", "." ]
72df150735664275a60a7861e468c6ff3b152a14
https://github.com/matomo-org/matomo/blob/72df150735664275a60a7861e468c6ff3b152a14/core/Site.php#L109-L116
210,158
matomo-org/matomo
core/Site.php
Site.setSitesFromArray
public static function setSitesFromArray($sites) { self::triggerSetSitesEvent($sites); foreach ($sites as $site) { $idSite = null; if (!empty($site['idsite'])) { $idSite = $site['idsite']; } self::setSiteFromArray($idSite, $site); } return $sites; }
php
public static function setSitesFromArray($sites) { self::triggerSetSitesEvent($sites); foreach ($sites as $site) { $idSite = null; if (!empty($site['idsite'])) { $idSite = $site['idsite']; } self::setSiteFromArray($idSite, $site); } return $sites; }
[ "public", "static", "function", "setSitesFromArray", "(", "$", "sites", ")", "{", "self", "::", "triggerSetSitesEvent", "(", "$", "sites", ")", ";", "foreach", "(", "$", "sites", "as", "$", "site", ")", "{", "$", "idSite", "=", "null", ";", "if", "(", "!", "empty", "(", "$", "site", "[", "'idsite'", "]", ")", ")", "{", "$", "idSite", "=", "$", "site", "[", "'idsite'", "]", ";", "}", "self", "::", "setSiteFromArray", "(", "$", "idSite", ",", "$", "site", ")", ";", "}", "return", "$", "sites", ";", "}" ]
Sets the cached Site data with a non-associated array of site data. This method will trigger the `Sites.setSites` event modifying `$sites` before setting cached site data. In other words, this method will change the site data before it is cached and then return the modified array. @param array $sites The array of sites data. eg, array( array('idsite' => '1', 'name' => 'Site 1', ...), array('idsite' => '2', 'name' => 'Site 2', ...), ) @return array The modified array. @deprecated @internal
[ "Sets", "the", "cached", "Site", "data", "with", "a", "non", "-", "associated", "array", "of", "site", "data", "." ]
72df150735664275a60a7861e468c6ff3b152a14
https://github.com/matomo-org/matomo/blob/72df150735664275a60a7861e468c6ff3b152a14/core/Site.php#L180-L194
210,159
matomo-org/matomo
core/Site.php
Site.getMinMaxDateAcrossWebsites
public static function getMinMaxDateAcrossWebsites($siteIds) { $siteIds = self::getIdSitesFromIdSitesString($siteIds); $now = Date::now(); $minDate = null; $maxDate = $now->subDay(1)->getTimestamp(); foreach ($siteIds as $idsite) { // look for 'now' in the website's timezone $timezone = Site::getTimezoneFor($idsite); $date = Date::adjustForTimezone($now->getTimestamp(), $timezone); if ($date > $maxDate) { $maxDate = $date; } // look for the absolute minimum date $creationDate = Site::getCreationDateFor($idsite); $date = Date::adjustForTimezone(strtotime($creationDate), $timezone); if (is_null($minDate) || $date < $minDate) { $minDate = $date; } } return array(Date::factory($minDate), Date::factory($maxDate)); }
php
public static function getMinMaxDateAcrossWebsites($siteIds) { $siteIds = self::getIdSitesFromIdSitesString($siteIds); $now = Date::now(); $minDate = null; $maxDate = $now->subDay(1)->getTimestamp(); foreach ($siteIds as $idsite) { // look for 'now' in the website's timezone $timezone = Site::getTimezoneFor($idsite); $date = Date::adjustForTimezone($now->getTimestamp(), $timezone); if ($date > $maxDate) { $maxDate = $date; } // look for the absolute minimum date $creationDate = Site::getCreationDateFor($idsite); $date = Date::adjustForTimezone(strtotime($creationDate), $timezone); if (is_null($minDate) || $date < $minDate) { $minDate = $date; } } return array(Date::factory($minDate), Date::factory($maxDate)); }
[ "public", "static", "function", "getMinMaxDateAcrossWebsites", "(", "$", "siteIds", ")", "{", "$", "siteIds", "=", "self", "::", "getIdSitesFromIdSitesString", "(", "$", "siteIds", ")", ";", "$", "now", "=", "Date", "::", "now", "(", ")", ";", "$", "minDate", "=", "null", ";", "$", "maxDate", "=", "$", "now", "->", "subDay", "(", "1", ")", "->", "getTimestamp", "(", ")", ";", "foreach", "(", "$", "siteIds", "as", "$", "idsite", ")", "{", "// look for 'now' in the website's timezone", "$", "timezone", "=", "Site", "::", "getTimezoneFor", "(", "$", "idsite", ")", ";", "$", "date", "=", "Date", "::", "adjustForTimezone", "(", "$", "now", "->", "getTimestamp", "(", ")", ",", "$", "timezone", ")", ";", "if", "(", "$", "date", ">", "$", "maxDate", ")", "{", "$", "maxDate", "=", "$", "date", ";", "}", "// look for the absolute minimum date", "$", "creationDate", "=", "Site", "::", "getCreationDateFor", "(", "$", "idsite", ")", ";", "$", "date", "=", "Date", "::", "adjustForTimezone", "(", "strtotime", "(", "$", "creationDate", ")", ",", "$", "timezone", ")", ";", "if", "(", "is_null", "(", "$", "minDate", ")", "||", "$", "date", "<", "$", "minDate", ")", "{", "$", "minDate", "=", "$", "date", ";", "}", "}", "return", "array", "(", "Date", "::", "factory", "(", "$", "minDate", ")", ",", "Date", "::", "factory", "(", "$", "maxDate", ")", ")", ";", "}" ]
The Multisites reports displays the first calendar date as the earliest day available for all websites. Also, today is the later "today" available across all timezones. @param array $siteIds Array of IDs for each site being displayed. @return Date[] of two Date instances. First is the min-date & the second is the max date. @ignore
[ "The", "Multisites", "reports", "displays", "the", "first", "calendar", "date", "as", "the", "earliest", "day", "available", "for", "all", "websites", ".", "Also", "today", "is", "the", "later", "today", "available", "across", "all", "timezones", "." ]
72df150735664275a60a7861e468c6ff3b152a14
https://github.com/matomo-org/matomo/blob/72df150735664275a60a7861e468c6ff3b152a14/core/Site.php#L204-L228
210,160
matomo-org/matomo
core/Site.php
Site.get
protected function get($name) { if (isset($this->site[$name])) { return $this->site[$name]; } throw new Exception("The property $name could not be found on the website ID " . (int)$this->id); }
php
protected function get($name) { if (isset($this->site[$name])) { return $this->site[$name]; } throw new Exception("The property $name could not be found on the website ID " . (int)$this->id); }
[ "protected", "function", "get", "(", "$", "name", ")", "{", "if", "(", "isset", "(", "$", "this", "->", "site", "[", "$", "name", "]", ")", ")", "{", "return", "$", "this", "->", "site", "[", "$", "name", "]", ";", "}", "throw", "new", "Exception", "(", "\"The property $name could not be found on the website ID \"", ".", "(", "int", ")", "$", "this", "->", "id", ")", ";", "}" ]
Returns a site property by name. @param string $name Name of the property to return (eg, `'main_url'` or `'name'`). @return mixed @throws Exception
[ "Returns", "a", "site", "property", "by", "name", "." ]
72df150735664275a60a7861e468c6ff3b152a14
https://github.com/matomo-org/matomo/blob/72df150735664275a60a7861e468c6ff3b152a14/core/Site.php#L288-L295
210,161
matomo-org/matomo
core/Site.php
Site.getIdSitesFromIdSitesString
public static function getIdSitesFromIdSitesString($ids, $_restrictSitesToLogin = false) { if ($ids === 'all') { return API::getInstance()->getSitesIdWithAtLeastViewAccess($_restrictSitesToLogin); } if (is_bool($ids)) { return array(); } if (!is_array($ids)) { $ids = explode(',', $ids); } $validIds = array(); foreach ($ids as $id) { $id = trim($id); if (!empty($id) && is_numeric($id) && $id > 0) { $validIds[] = $id; } } $validIds = array_filter($validIds); $validIds = array_unique($validIds); return $validIds; }
php
public static function getIdSitesFromIdSitesString($ids, $_restrictSitesToLogin = false) { if ($ids === 'all') { return API::getInstance()->getSitesIdWithAtLeastViewAccess($_restrictSitesToLogin); } if (is_bool($ids)) { return array(); } if (!is_array($ids)) { $ids = explode(',', $ids); } $validIds = array(); foreach ($ids as $id) { $id = trim($id); if (!empty($id) && is_numeric($id) && $id > 0) { $validIds[] = $id; } } $validIds = array_filter($validIds); $validIds = array_unique($validIds); return $validIds; }
[ "public", "static", "function", "getIdSitesFromIdSitesString", "(", "$", "ids", ",", "$", "_restrictSitesToLogin", "=", "false", ")", "{", "if", "(", "$", "ids", "===", "'all'", ")", "{", "return", "API", "::", "getInstance", "(", ")", "->", "getSitesIdWithAtLeastViewAccess", "(", "$", "_restrictSitesToLogin", ")", ";", "}", "if", "(", "is_bool", "(", "$", "ids", ")", ")", "{", "return", "array", "(", ")", ";", "}", "if", "(", "!", "is_array", "(", "$", "ids", ")", ")", "{", "$", "ids", "=", "explode", "(", "','", ",", "$", "ids", ")", ";", "}", "$", "validIds", "=", "array", "(", ")", ";", "foreach", "(", "$", "ids", "as", "$", "id", ")", "{", "$", "id", "=", "trim", "(", "$", "id", ")", ";", "if", "(", "!", "empty", "(", "$", "id", ")", "&&", "is_numeric", "(", "$", "id", ")", "&&", "$", "id", ">", "0", ")", "{", "$", "validIds", "[", "]", "=", "$", "id", ";", "}", "}", "$", "validIds", "=", "array_filter", "(", "$", "validIds", ")", ";", "$", "validIds", "=", "array_unique", "(", "$", "validIds", ")", ";", "return", "$", "validIds", ";", "}" ]
Checks the given string for valid site IDs and returns them as an array. @param string|array $ids Comma separated idSite list, eg, `'1,2,3,4'` or an array of IDs, eg, `array(1, 2, 3, 4)`. @param bool|string $_restrictSitesToLogin Implementation detail. Used only when running as a scheduled task. @return array An array of valid, unique integers.
[ "Checks", "the", "given", "string", "for", "valid", "site", "IDs", "and", "returns", "them", "as", "an", "array", "." ]
72df150735664275a60a7861e468c6ff3b152a14
https://github.com/matomo-org/matomo/blob/72df150735664275a60a7861e468c6ff3b152a14/core/Site.php#L426-L449
210,162
matomo-org/matomo
core/Site.php
Site.getFor
protected static function getFor($idsite, $field) { if (!isset(self::$infoSites[$idsite])) { $site = API::getInstance()->getSiteFromId($idsite); self::setSiteFromArray($idsite, $site); } return self::$infoSites[$idsite][$field]; }
php
protected static function getFor($idsite, $field) { if (!isset(self::$infoSites[$idsite])) { $site = API::getInstance()->getSiteFromId($idsite); self::setSiteFromArray($idsite, $site); } return self::$infoSites[$idsite][$field]; }
[ "protected", "static", "function", "getFor", "(", "$", "idsite", ",", "$", "field", ")", "{", "if", "(", "!", "isset", "(", "self", "::", "$", "infoSites", "[", "$", "idsite", "]", ")", ")", "{", "$", "site", "=", "API", "::", "getInstance", "(", ")", "->", "getSiteFromId", "(", "$", "idsite", ")", ";", "self", "::", "setSiteFromArray", "(", "$", "idsite", ",", "$", "site", ")", ";", "}", "return", "self", "::", "$", "infoSites", "[", "$", "idsite", "]", "[", "$", "field", "]", ";", "}" ]
Utility function. Returns the value of the specified field for the site with the specified ID. @param int $idsite The ID of the site whose data is being accessed. @param string $field The name of the field to get. @return string
[ "Utility", "function", ".", "Returns", "the", "value", "of", "the", "specified", "field", "for", "the", "site", "with", "the", "specified", "ID", "." ]
72df150735664275a60a7861e468c6ff3b152a14
https://github.com/matomo-org/matomo/blob/72df150735664275a60a7861e468c6ff3b152a14/core/Site.php#L480-L488
210,163
matomo-org/matomo
core/Site.php
Site.getCurrencySymbolFor
public static function getCurrencySymbolFor($idsite) { $currencyCode = self::getCurrencyFor($idsite); $key = 'Intl_CurrencySymbol_' . $currencyCode; $symbol = Piwik::translate($key); if ($key === $symbol) { return $currencyCode; } return $symbol; }
php
public static function getCurrencySymbolFor($idsite) { $currencyCode = self::getCurrencyFor($idsite); $key = 'Intl_CurrencySymbol_' . $currencyCode; $symbol = Piwik::translate($key); if ($key === $symbol) { return $currencyCode; } return $symbol; }
[ "public", "static", "function", "getCurrencySymbolFor", "(", "$", "idsite", ")", "{", "$", "currencyCode", "=", "self", "::", "getCurrencyFor", "(", "$", "idsite", ")", ";", "$", "key", "=", "'Intl_CurrencySymbol_'", ".", "$", "currencyCode", ";", "$", "symbol", "=", "Piwik", "::", "translate", "(", "$", "key", ")", ";", "if", "(", "$", "key", "===", "$", "symbol", ")", "{", "return", "$", "currencyCode", ";", "}", "return", "$", "symbol", ";", "}" ]
Returns the currency of the site with the specified ID. @param int $idsite The site ID. @return string
[ "Returns", "the", "currency", "of", "the", "site", "with", "the", "specified", "ID", "." ]
72df150735664275a60a7861e468c6ff3b152a14
https://github.com/matomo-org/matomo/blob/72df150735664275a60a7861e468c6ff3b152a14/core/Site.php#L620-L631
210,164
matomo-org/matomo
plugins/UserCountry/API.php
API.getCountryCodeMapping
public function getCountryCodeMapping() { $regionDataProvider = StaticContainer::get('Piwik\Intl\Data\Provider\RegionDataProvider'); $countryCodeList = $regionDataProvider->getCountryList(); array_walk($countryCodeList, function(&$item, $key) { $item = Piwik::translate('Intl_Country_'.strtoupper($key)); }); return $countryCodeList; }
php
public function getCountryCodeMapping() { $regionDataProvider = StaticContainer::get('Piwik\Intl\Data\Provider\RegionDataProvider'); $countryCodeList = $regionDataProvider->getCountryList(); array_walk($countryCodeList, function(&$item, $key) { $item = Piwik::translate('Intl_Country_'.strtoupper($key)); }); return $countryCodeList; }
[ "public", "function", "getCountryCodeMapping", "(", ")", "{", "$", "regionDataProvider", "=", "StaticContainer", "::", "get", "(", "'Piwik\\Intl\\Data\\Provider\\RegionDataProvider'", ")", ";", "$", "countryCodeList", "=", "$", "regionDataProvider", "->", "getCountryList", "(", ")", ";", "array_walk", "(", "$", "countryCodeList", ",", "function", "(", "&", "$", "item", ",", "$", "key", ")", "{", "$", "item", "=", "Piwik", "::", "translate", "(", "'Intl_Country_'", ".", "strtoupper", "(", "$", "key", ")", ")", ";", "}", ")", ";", "return", "$", "countryCodeList", ";", "}" ]
Returns a simple mapping from country code to country name @return \string[]
[ "Returns", "a", "simple", "mapping", "from", "country", "code", "to", "country", "name" ]
72df150735664275a60a7861e468c6ff3b152a14
https://github.com/matomo-org/matomo/blob/72df150735664275a60a7861e468c6ff3b152a14/plugins/UserCountry/API.php#L336-L347
210,165
matomo-org/matomo
plugins/UserCountry/API.php
API.setLocationProvider
public function setLocationProvider($providerId) { Piwik::checkUserHasSuperUserAccess(); if (!UserCountry::isGeoLocationAdminEnabled()) { throw new \Exception('Setting geo location has been disabled in config.'); } $provider = LocationProvider::setCurrentProvider($providerId); if ($provider === false) { throw new Exception("Invalid provider ID: '$providerId'."); } }
php
public function setLocationProvider($providerId) { Piwik::checkUserHasSuperUserAccess(); if (!UserCountry::isGeoLocationAdminEnabled()) { throw new \Exception('Setting geo location has been disabled in config.'); } $provider = LocationProvider::setCurrentProvider($providerId); if ($provider === false) { throw new Exception("Invalid provider ID: '$providerId'."); } }
[ "public", "function", "setLocationProvider", "(", "$", "providerId", ")", "{", "Piwik", "::", "checkUserHasSuperUserAccess", "(", ")", ";", "if", "(", "!", "UserCountry", "::", "isGeoLocationAdminEnabled", "(", ")", ")", "{", "throw", "new", "\\", "Exception", "(", "'Setting geo location has been disabled in config.'", ")", ";", "}", "$", "provider", "=", "LocationProvider", "::", "setCurrentProvider", "(", "$", "providerId", ")", ";", "if", "(", "$", "provider", "===", "false", ")", "{", "throw", "new", "Exception", "(", "\"Invalid provider ID: '$providerId'.\"", ")", ";", "}", "}" ]
Set the location provider @param string $providerId The ID of the provider to use eg 'default', 'geoip2_php', ... @throws Exception if ID is invalid
[ "Set", "the", "location", "provider" ]
72df150735664275a60a7861e468c6ff3b152a14
https://github.com/matomo-org/matomo/blob/72df150735664275a60a7861e468c6ff3b152a14/plugins/UserCountry/API.php#L389-L401
210,166
matomo-org/matomo
core/Period/Day.php
Day.getLocalizedShortString
public function getLocalizedShortString() { //"Mon 15 Aug" $date = $this->getDateStart(); $out = $date->getLocalized(Date::DATE_FORMAT_DAY_MONTH); return $out; }
php
public function getLocalizedShortString() { //"Mon 15 Aug" $date = $this->getDateStart(); $out = $date->getLocalized(Date::DATE_FORMAT_DAY_MONTH); return $out; }
[ "public", "function", "getLocalizedShortString", "(", ")", "{", "//\"Mon 15 Aug\"", "$", "date", "=", "$", "this", "->", "getDateStart", "(", ")", ";", "$", "out", "=", "$", "date", "->", "getLocalized", "(", "Date", "::", "DATE_FORMAT_DAY_MONTH", ")", ";", "return", "$", "out", ";", "}" ]
Returns the day of the period as a localized short string @return string
[ "Returns", "the", "day", "of", "the", "period", "as", "a", "localized", "short", "string" ]
72df150735664275a60a7861e468c6ff3b152a14
https://github.com/matomo-org/matomo/blob/72df150735664275a60a7861e468c6ff3b152a14/core/Period/Day.php#L39-L45
210,167
matomo-org/matomo
core/Period/Day.php
Day.getLocalizedLongString
public function getLocalizedLongString() { //"Mon 15 Aug" $date = $this->getDateStart(); $out = $date->getLocalized(Date::DATE_FORMAT_LONG); return $out; }
php
public function getLocalizedLongString() { //"Mon 15 Aug" $date = $this->getDateStart(); $out = $date->getLocalized(Date::DATE_FORMAT_LONG); return $out; }
[ "public", "function", "getLocalizedLongString", "(", ")", "{", "//\"Mon 15 Aug\"", "$", "date", "=", "$", "this", "->", "getDateStart", "(", ")", ";", "$", "out", "=", "$", "date", "->", "getLocalized", "(", "Date", "::", "DATE_FORMAT_LONG", ")", ";", "return", "$", "out", ";", "}" ]
Returns the day of the period as a localized long string @return string
[ "Returns", "the", "day", "of", "the", "period", "as", "a", "localized", "long", "string" ]
72df150735664275a60a7861e468c6ff3b152a14
https://github.com/matomo-org/matomo/blob/72df150735664275a60a7861e468c6ff3b152a14/core/Period/Day.php#L52-L58
210,168
matomo-org/matomo
core/Tracker/Db.php
Db.recordQueryProfile
protected function recordQueryProfile($query, $timer) { if (!isset($this->queriesProfiling[$query])) { $this->queriesProfiling[$query] = array('sum_time_ms' => 0, 'count' => 0); } $time = $timer->getTimeMs(2); $time += $this->queriesProfiling[$query]['sum_time_ms']; $count = $this->queriesProfiling[$query]['count'] + 1; $this->queriesProfiling[$query] = array('sum_time_ms' => $time, 'count' => $count); }
php
protected function recordQueryProfile($query, $timer) { if (!isset($this->queriesProfiling[$query])) { $this->queriesProfiling[$query] = array('sum_time_ms' => 0, 'count' => 0); } $time = $timer->getTimeMs(2); $time += $this->queriesProfiling[$query]['sum_time_ms']; $count = $this->queriesProfiling[$query]['count'] + 1; $this->queriesProfiling[$query] = array('sum_time_ms' => $time, 'count' => $count); }
[ "protected", "function", "recordQueryProfile", "(", "$", "query", ",", "$", "timer", ")", "{", "if", "(", "!", "isset", "(", "$", "this", "->", "queriesProfiling", "[", "$", "query", "]", ")", ")", "{", "$", "this", "->", "queriesProfiling", "[", "$", "query", "]", "=", "array", "(", "'sum_time_ms'", "=>", "0", ",", "'count'", "=>", "0", ")", ";", "}", "$", "time", "=", "$", "timer", "->", "getTimeMs", "(", "2", ")", ";", "$", "time", "+=", "$", "this", "->", "queriesProfiling", "[", "$", "query", "]", "[", "'sum_time_ms'", "]", ";", "$", "count", "=", "$", "this", "->", "queriesProfiling", "[", "$", "query", "]", "[", "'count'", "]", "+", "1", ";", "$", "this", "->", "queriesProfiling", "[", "$", "query", "]", "=", "array", "(", "'sum_time_ms'", "=>", "$", "time", ",", "'count'", "=>", "$", "count", ")", ";", "}" ]
Record query profile @param string $query @param Timer $timer
[ "Record", "query", "profile" ]
72df150735664275a60a7861e468c6ff3b152a14
https://github.com/matomo-org/matomo/blob/72df150735664275a60a7861e468c6ff3b152a14/core/Tracker/Db.php#L83-L94
210,169
matomo-org/matomo
core/Tracker/Db.php
Db.recordProfiling
public function recordProfiling() { if (is_null($this->connection)) { return; } // turn off the profiler so we don't profile the following queries self::$profiling = false; foreach ($this->queriesProfiling as $query => $info) { $time = $info['sum_time_ms']; $time = Common::forceDotAsSeparatorForDecimalPoint($time); $count = $info['count']; $queryProfiling = "INSERT INTO " . Common::prefixTable('log_profiling') . " (query,count,sum_time_ms) VALUES (?,$count,$time) ON DUPLICATE KEY UPDATE count=count+$count,sum_time_ms=sum_time_ms+$time"; $this->query($queryProfiling, array($query)); } // turn back on profiling self::$profiling = true; }
php
public function recordProfiling() { if (is_null($this->connection)) { return; } // turn off the profiler so we don't profile the following queries self::$profiling = false; foreach ($this->queriesProfiling as $query => $info) { $time = $info['sum_time_ms']; $time = Common::forceDotAsSeparatorForDecimalPoint($time); $count = $info['count']; $queryProfiling = "INSERT INTO " . Common::prefixTable('log_profiling') . " (query,count,sum_time_ms) VALUES (?,$count,$time) ON DUPLICATE KEY UPDATE count=count+$count,sum_time_ms=sum_time_ms+$time"; $this->query($queryProfiling, array($query)); } // turn back on profiling self::$profiling = true; }
[ "public", "function", "recordProfiling", "(", ")", "{", "if", "(", "is_null", "(", "$", "this", "->", "connection", ")", ")", "{", "return", ";", "}", "// turn off the profiler so we don't profile the following queries", "self", "::", "$", "profiling", "=", "false", ";", "foreach", "(", "$", "this", "->", "queriesProfiling", "as", "$", "query", "=>", "$", "info", ")", "{", "$", "time", "=", "$", "info", "[", "'sum_time_ms'", "]", ";", "$", "time", "=", "Common", "::", "forceDotAsSeparatorForDecimalPoint", "(", "$", "time", ")", ";", "$", "count", "=", "$", "info", "[", "'count'", "]", ";", "$", "queryProfiling", "=", "\"INSERT INTO \"", ".", "Common", "::", "prefixTable", "(", "'log_profiling'", ")", ".", "\"\n\t\t\t\t\t\t(query,count,sum_time_ms) VALUES (?,$count,$time)\n\t\t\t\t\t\tON DUPLICATE KEY UPDATE count=count+$count,sum_time_ms=sum_time_ms+$time\"", ";", "$", "this", "->", "query", "(", "$", "queryProfiling", ",", "array", "(", "$", "query", ")", ")", ";", "}", "// turn back on profiling", "self", "::", "$", "profiling", "=", "true", ";", "}" ]
When destroyed, if SQL profiled enabled, logs the SQL profiling information
[ "When", "destroyed", "if", "SQL", "profiled", "enabled", "logs", "the", "SQL", "profiling", "information" ]
72df150735664275a60a7861e468c6ff3b152a14
https://github.com/matomo-org/matomo/blob/72df150735664275a60a7861e468c6ff3b152a14/core/Tracker/Db.php#L99-L121
210,170
matomo-org/matomo
core/Tracker/Db.php
Db.factory
public static function factory($configDb) { /** * Triggered before a connection to the database is established by the Tracker. * * This event can be used to change the database connection settings used by the Tracker. * * @param array $dbInfos Reference to an array containing database connection info, * including: * * - **host**: The host name or IP address to the MySQL database. * - **username**: The username to use when connecting to the * database. * - **password**: The password to use when connecting to the * database. * - **dbname**: The name of the Piwik MySQL database. * - **port**: The MySQL database port to use. * - **adapter**: either `'PDO\MYSQL'` or `'MYSQLI'` * - **type**: The MySQL engine to use, for instance 'InnoDB' */ Piwik::postEvent('Tracker.getDatabaseConfig', array(&$configDb)); switch ($configDb['adapter']) { case 'PDO\MYSQL': case 'PDO_MYSQL': // old format pre Piwik 2 require_once PIWIK_INCLUDE_PATH . '/core/Tracker/Db/Pdo/Mysql.php'; return new Mysql($configDb); case 'MYSQLI': require_once PIWIK_INCLUDE_PATH . '/core/Tracker/Db/Mysqli.php'; return new Mysqli($configDb); } throw new Exception('Unsupported database adapter ' . $configDb['adapter']); }
php
public static function factory($configDb) { /** * Triggered before a connection to the database is established by the Tracker. * * This event can be used to change the database connection settings used by the Tracker. * * @param array $dbInfos Reference to an array containing database connection info, * including: * * - **host**: The host name or IP address to the MySQL database. * - **username**: The username to use when connecting to the * database. * - **password**: The password to use when connecting to the * database. * - **dbname**: The name of the Piwik MySQL database. * - **port**: The MySQL database port to use. * - **adapter**: either `'PDO\MYSQL'` or `'MYSQLI'` * - **type**: The MySQL engine to use, for instance 'InnoDB' */ Piwik::postEvent('Tracker.getDatabaseConfig', array(&$configDb)); switch ($configDb['adapter']) { case 'PDO\MYSQL': case 'PDO_MYSQL': // old format pre Piwik 2 require_once PIWIK_INCLUDE_PATH . '/core/Tracker/Db/Pdo/Mysql.php'; return new Mysql($configDb); case 'MYSQLI': require_once PIWIK_INCLUDE_PATH . '/core/Tracker/Db/Mysqli.php'; return new Mysqli($configDb); } throw new Exception('Unsupported database adapter ' . $configDb['adapter']); }
[ "public", "static", "function", "factory", "(", "$", "configDb", ")", "{", "/**\n * Triggered before a connection to the database is established by the Tracker.\n *\n * This event can be used to change the database connection settings used by the Tracker.\n *\n * @param array $dbInfos Reference to an array containing database connection info,\n * including:\n *\n * - **host**: The host name or IP address to the MySQL database.\n * - **username**: The username to use when connecting to the\n * database.\n * - **password**: The password to use when connecting to the\n * database.\n * - **dbname**: The name of the Piwik MySQL database.\n * - **port**: The MySQL database port to use.\n * - **adapter**: either `'PDO\\MYSQL'` or `'MYSQLI'`\n * - **type**: The MySQL engine to use, for instance 'InnoDB'\n */", "Piwik", "::", "postEvent", "(", "'Tracker.getDatabaseConfig'", ",", "array", "(", "&", "$", "configDb", ")", ")", ";", "switch", "(", "$", "configDb", "[", "'adapter'", "]", ")", "{", "case", "'PDO\\MYSQL'", ":", "case", "'PDO_MYSQL'", ":", "// old format pre Piwik 2", "require_once", "PIWIK_INCLUDE_PATH", ".", "'/core/Tracker/Db/Pdo/Mysql.php'", ";", "return", "new", "Mysql", "(", "$", "configDb", ")", ";", "case", "'MYSQLI'", ":", "require_once", "PIWIK_INCLUDE_PATH", ".", "'/core/Tracker/Db/Mysqli.php'", ";", "return", "new", "Mysqli", "(", "$", "configDb", ")", ";", "}", "throw", "new", "Exception", "(", "'Unsupported database adapter '", ".", "$", "configDb", "[", "'adapter'", "]", ")", ";", "}" ]
Factory to create database objects @param array $configDb Database configuration @throws Exception @return \Piwik\Tracker\Db\Mysqli|\Piwik\Tracker\Db\Pdo\Mysql
[ "Factory", "to", "create", "database", "objects" ]
72df150735664275a60a7861e468c6ff3b152a14
https://github.com/matomo-org/matomo/blob/72df150735664275a60a7861e468c6ff3b152a14/core/Tracker/Db.php#L242-L276
210,171
matomo-org/matomo
plugins/CoreVisualizations/Visualizations/JqplotGraph/Evolution.php
Evolution.getDateRangeAndLastN
public static function getDateRangeAndLastN($period, $endDate, $defaultLastN = null) { if ($defaultLastN === null) { $defaultLastN = self::getDefaultLastN($period); } $lastNParamName = self::getLastNParamName($period); $lastN = Common::getRequestVar($lastNParamName, $defaultLastN, 'int'); $site = new Site(Common::getRequestVar('idSite')); $dateRange = Range::getRelativeToEndDate($period, 'last' . $lastN, $endDate, $site); return array($dateRange, $lastN); }
php
public static function getDateRangeAndLastN($period, $endDate, $defaultLastN = null) { if ($defaultLastN === null) { $defaultLastN = self::getDefaultLastN($period); } $lastNParamName = self::getLastNParamName($period); $lastN = Common::getRequestVar($lastNParamName, $defaultLastN, 'int'); $site = new Site(Common::getRequestVar('idSite')); $dateRange = Range::getRelativeToEndDate($period, 'last' . $lastN, $endDate, $site); return array($dateRange, $lastN); }
[ "public", "static", "function", "getDateRangeAndLastN", "(", "$", "period", ",", "$", "endDate", ",", "$", "defaultLastN", "=", "null", ")", "{", "if", "(", "$", "defaultLastN", "===", "null", ")", "{", "$", "defaultLastN", "=", "self", "::", "getDefaultLastN", "(", "$", "period", ")", ";", "}", "$", "lastNParamName", "=", "self", "::", "getLastNParamName", "(", "$", "period", ")", ";", "$", "lastN", "=", "Common", "::", "getRequestVar", "(", "$", "lastNParamName", ",", "$", "defaultLastN", ",", "'int'", ")", ";", "$", "site", "=", "new", "Site", "(", "Common", "::", "getRequestVar", "(", "'idSite'", ")", ")", ";", "$", "dateRange", "=", "Range", "::", "getRelativeToEndDate", "(", "$", "period", ",", "'last'", ".", "$", "lastN", ",", "$", "endDate", ",", "$", "site", ")", ";", "return", "array", "(", "$", "dateRange", ",", "$", "lastN", ")", ";", "}" ]
Returns the entire date range and lastN value for the current request, based on a period type and end date. @param string $period The period type, 'day', 'week', 'month' or 'year' @param string $endDate The end date. @param int|null $defaultLastN The default lastN to use. If null, the result of getDefaultLastN is used. @return array An array w/ two elements. The first is a whole date range and the second is the lastN number used, ie, array('2010-01-01,2012-01-02', 2).
[ "Returns", "the", "entire", "date", "range", "and", "lastN", "value", "for", "the", "current", "request", "based", "on", "a", "period", "type", "and", "end", "date", "." ]
72df150735664275a60a7861e468c6ff3b152a14
https://github.com/matomo-org/matomo/blob/72df150735664275a60a7861e468c6ff3b152a14/plugins/CoreVisualizations/Visualizations/JqplotGraph/Evolution.php#L119-L133
210,172
matomo-org/matomo
libs/Zend/Config/Writer/Ini.php
Zend_Config_Writer_Ini.render
public function render() { $iniString = ''; $extends = $this->_config->getExtends(); $sectionName = $this->_config->getSectionName(); if($this->_renderWithoutSections == true) { $iniString .= $this->_addBranch($this->_config); } else if (is_string($sectionName)) { $iniString .= '[' . $sectionName . ']' . "\n" . $this->_addBranch($this->_config) . "\n"; } else { $config = $this->_sortRootElements($this->_config); foreach ($config as $sectionName => $data) { if (!($data instanceof Zend_Config)) { $iniString .= $sectionName . ' = ' . $this->_prepareValue($data) . "\n"; } else { if (isset($extends[$sectionName])) { $sectionName .= ' : ' . $extends[$sectionName]; } $iniString .= '[' . $sectionName . ']' . "\n" . $this->_addBranch($data) . "\n"; } } } return $iniString; }
php
public function render() { $iniString = ''; $extends = $this->_config->getExtends(); $sectionName = $this->_config->getSectionName(); if($this->_renderWithoutSections == true) { $iniString .= $this->_addBranch($this->_config); } else if (is_string($sectionName)) { $iniString .= '[' . $sectionName . ']' . "\n" . $this->_addBranch($this->_config) . "\n"; } else { $config = $this->_sortRootElements($this->_config); foreach ($config as $sectionName => $data) { if (!($data instanceof Zend_Config)) { $iniString .= $sectionName . ' = ' . $this->_prepareValue($data) . "\n"; } else { if (isset($extends[$sectionName])) { $sectionName .= ' : ' . $extends[$sectionName]; } $iniString .= '[' . $sectionName . ']' . "\n" . $this->_addBranch($data) . "\n"; } } } return $iniString; }
[ "public", "function", "render", "(", ")", "{", "$", "iniString", "=", "''", ";", "$", "extends", "=", "$", "this", "->", "_config", "->", "getExtends", "(", ")", ";", "$", "sectionName", "=", "$", "this", "->", "_config", "->", "getSectionName", "(", ")", ";", "if", "(", "$", "this", "->", "_renderWithoutSections", "==", "true", ")", "{", "$", "iniString", ".=", "$", "this", "->", "_addBranch", "(", "$", "this", "->", "_config", ")", ";", "}", "else", "if", "(", "is_string", "(", "$", "sectionName", ")", ")", "{", "$", "iniString", ".=", "'['", ".", "$", "sectionName", ".", "']'", ".", "\"\\n\"", ".", "$", "this", "->", "_addBranch", "(", "$", "this", "->", "_config", ")", ".", "\"\\n\"", ";", "}", "else", "{", "$", "config", "=", "$", "this", "->", "_sortRootElements", "(", "$", "this", "->", "_config", ")", ";", "foreach", "(", "$", "config", "as", "$", "sectionName", "=>", "$", "data", ")", "{", "if", "(", "!", "(", "$", "data", "instanceof", "Zend_Config", ")", ")", "{", "$", "iniString", ".=", "$", "sectionName", ".", "' = '", ".", "$", "this", "->", "_prepareValue", "(", "$", "data", ")", ".", "\"\\n\"", ";", "}", "else", "{", "if", "(", "isset", "(", "$", "extends", "[", "$", "sectionName", "]", ")", ")", "{", "$", "sectionName", ".=", "' : '", ".", "$", "extends", "[", "$", "sectionName", "]", ";", "}", "$", "iniString", ".=", "'['", ".", "$", "sectionName", ".", "']'", ".", "\"\\n\"", ".", "$", "this", "->", "_addBranch", "(", "$", "data", ")", ".", "\"\\n\"", ";", "}", "}", "}", "return", "$", "iniString", ";", "}" ]
Render a Zend_Config into a INI config string. @since 1.10 @return string
[ "Render", "a", "Zend_Config", "into", "a", "INI", "config", "string", "." ]
72df150735664275a60a7861e468c6ff3b152a14
https://github.com/matomo-org/matomo/blob/72df150735664275a60a7861e468c6ff3b152a14/libs/Zend/Config/Writer/Ini.php#L83-L116
210,173
matomo-org/matomo
libs/Zend/Config/Writer/Ini.php
Zend_Config_Writer_Ini._addBranch
protected function _addBranch(Zend_Config $config, $parents = array()) { $iniString = ''; foreach ($config as $key => $value) { $group = array_merge($parents, array($key)); if ($value instanceof Zend_Config) { $iniString .= $this->_addBranch($value, $group); } else { $iniString .= implode($this->_nestSeparator, $group) . ' = ' . $this->_prepareValue($value) . "\n"; } } return $iniString; }
php
protected function _addBranch(Zend_Config $config, $parents = array()) { $iniString = ''; foreach ($config as $key => $value) { $group = array_merge($parents, array($key)); if ($value instanceof Zend_Config) { $iniString .= $this->_addBranch($value, $group); } else { $iniString .= implode($this->_nestSeparator, $group) . ' = ' . $this->_prepareValue($value) . "\n"; } } return $iniString; }
[ "protected", "function", "_addBranch", "(", "Zend_Config", "$", "config", ",", "$", "parents", "=", "array", "(", ")", ")", "{", "$", "iniString", "=", "''", ";", "foreach", "(", "$", "config", "as", "$", "key", "=>", "$", "value", ")", "{", "$", "group", "=", "array_merge", "(", "$", "parents", ",", "array", "(", "$", "key", ")", ")", ";", "if", "(", "$", "value", "instanceof", "Zend_Config", ")", "{", "$", "iniString", ".=", "$", "this", "->", "_addBranch", "(", "$", "value", ",", "$", "group", ")", ";", "}", "else", "{", "$", "iniString", ".=", "implode", "(", "$", "this", "->", "_nestSeparator", ",", "$", "group", ")", ".", "' = '", ".", "$", "this", "->", "_prepareValue", "(", "$", "value", ")", ".", "\"\\n\"", ";", "}", "}", "return", "$", "iniString", ";", "}" ]
Add a branch to an INI string recursively @param Zend_Config $config @return void
[ "Add", "a", "branch", "to", "an", "INI", "string", "recursively" ]
72df150735664275a60a7861e468c6ff3b152a14
https://github.com/matomo-org/matomo/blob/72df150735664275a60a7861e468c6ff3b152a14/libs/Zend/Config/Writer/Ini.php#L124-L142
210,174
matomo-org/matomo
libs/Zend/Config/Writer/Ini.php
Zend_Config_Writer_Ini._sortRootElements
protected function _sortRootElements(Zend_Config $config) { $configArray = $config->toArray(); $sections = array(); // remove sections from config array foreach ($configArray as $key => $value) { if (is_array($value)) { $sections[$key] = $value; unset($configArray[$key]); } } // readd sections to the end foreach ($sections as $key => $value) { $configArray[$key] = $value; } return new Zend_Config($configArray); }
php
protected function _sortRootElements(Zend_Config $config) { $configArray = $config->toArray(); $sections = array(); // remove sections from config array foreach ($configArray as $key => $value) { if (is_array($value)) { $sections[$key] = $value; unset($configArray[$key]); } } // readd sections to the end foreach ($sections as $key => $value) { $configArray[$key] = $value; } return new Zend_Config($configArray); }
[ "protected", "function", "_sortRootElements", "(", "Zend_Config", "$", "config", ")", "{", "$", "configArray", "=", "$", "config", "->", "toArray", "(", ")", ";", "$", "sections", "=", "array", "(", ")", ";", "// remove sections from config array", "foreach", "(", "$", "configArray", "as", "$", "key", "=>", "$", "value", ")", "{", "if", "(", "is_array", "(", "$", "value", ")", ")", "{", "$", "sections", "[", "$", "key", "]", "=", "$", "value", ";", "unset", "(", "$", "configArray", "[", "$", "key", "]", ")", ";", "}", "}", "// readd sections to the end", "foreach", "(", "$", "sections", "as", "$", "key", "=>", "$", "value", ")", "{", "$", "configArray", "[", "$", "key", "]", "=", "$", "value", ";", "}", "return", "new", "Zend_Config", "(", "$", "configArray", ")", ";", "}" ]
Root elements that are not assigned to any section needs to be on the top of config. @see http://framework.zend.com/issues/browse/ZF-6289 @param Zend_Config @return Zend_Config
[ "Root", "elements", "that", "are", "not", "assigned", "to", "any", "section", "needs", "to", "be", "on", "the", "top", "of", "config", "." ]
72df150735664275a60a7861e468c6ff3b152a14
https://github.com/matomo-org/matomo/blob/72df150735664275a60a7861e468c6ff3b152a14/libs/Zend/Config/Writer/Ini.php#L173-L192
210,175
matomo-org/matomo
plugins/CustomVariables/Archiver.php
Archiver.removeVisitsMetricsFromActionsAggregate
protected function removeVisitsMetricsFromActionsAggregate() { $dataArray = & $this->dataArray->getDataArray(); foreach ($dataArray as $key => &$row) { if (!self::isReservedKey($key) && DataArray::isRowActions($row) ) { unset($row[Metrics::INDEX_NB_UNIQ_VISITORS]); unset($row[Metrics::INDEX_NB_VISITS]); unset($row[Metrics::INDEX_NB_USERS]); } } }
php
protected function removeVisitsMetricsFromActionsAggregate() { $dataArray = & $this->dataArray->getDataArray(); foreach ($dataArray as $key => &$row) { if (!self::isReservedKey($key) && DataArray::isRowActions($row) ) { unset($row[Metrics::INDEX_NB_UNIQ_VISITORS]); unset($row[Metrics::INDEX_NB_VISITS]); unset($row[Metrics::INDEX_NB_USERS]); } } }
[ "protected", "function", "removeVisitsMetricsFromActionsAggregate", "(", ")", "{", "$", "dataArray", "=", "&", "$", "this", "->", "dataArray", "->", "getDataArray", "(", ")", ";", "foreach", "(", "$", "dataArray", "as", "$", "key", "=>", "&", "$", "row", ")", "{", "if", "(", "!", "self", "::", "isReservedKey", "(", "$", "key", ")", "&&", "DataArray", "::", "isRowActions", "(", "$", "row", ")", ")", "{", "unset", "(", "$", "row", "[", "Metrics", "::", "INDEX_NB_UNIQ_VISITORS", "]", ")", ";", "unset", "(", "$", "row", "[", "Metrics", "::", "INDEX_NB_VISITS", "]", ")", ";", "unset", "(", "$", "row", "[", "Metrics", "::", "INDEX_NB_USERS", "]", ")", ";", "}", "}", "}" ]
Delete Visit, Unique Visitor and Users metric from 'page' scope custom variables. - Custom variables of 'visit' scope: it is expected that these ones have the "visit" column set. - Custom variables of 'page' scope: we cannot process "Visits" count for these. Why? "Actions" column is processed with a SELECT count(*). A same visit can set the same custom variable of 'page' scope multiple times. We cannot sum the values of count(*) as it would be incorrect. The way we could process "Visits" Metric for 'page' scope variable is to issue a count(Distinct *) or so, but it is no implemented yet (this would likely be very slow for high traffic sites).
[ "Delete", "Visit", "Unique", "Visitor", "and", "Users", "metric", "from", "page", "scope", "custom", "variables", "." ]
72df150735664275a60a7861e468c6ff3b152a14
https://github.com/matomo-org/matomo/blob/72df150735664275a60a7861e468c6ff3b152a14/plugins/CustomVariables/Archiver.php#L261-L273
210,176
matomo-org/matomo
core/Settings/Storage/Factory.php
Factory.getPluginStorage
public function getPluginStorage($pluginName, $userLogin) { $id = $pluginName . '#' . $userLogin; if (!isset($this->cache[$id])) { $backend = new Backend\PluginSettingsTable($pluginName, $userLogin); $this->cache[$id] = $this->makeStorage($backend); } return $this->cache[$id]; }
php
public function getPluginStorage($pluginName, $userLogin) { $id = $pluginName . '#' . $userLogin; if (!isset($this->cache[$id])) { $backend = new Backend\PluginSettingsTable($pluginName, $userLogin); $this->cache[$id] = $this->makeStorage($backend); } return $this->cache[$id]; }
[ "public", "function", "getPluginStorage", "(", "$", "pluginName", ",", "$", "userLogin", ")", "{", "$", "id", "=", "$", "pluginName", ".", "'#'", ".", "$", "userLogin", ";", "if", "(", "!", "isset", "(", "$", "this", "->", "cache", "[", "$", "id", "]", ")", ")", "{", "$", "backend", "=", "new", "Backend", "\\", "PluginSettingsTable", "(", "$", "pluginName", ",", "$", "userLogin", ")", ";", "$", "this", "->", "cache", "[", "$", "id", "]", "=", "$", "this", "->", "makeStorage", "(", "$", "backend", ")", ";", "}", "return", "$", "this", "->", "cache", "[", "$", "id", "]", ";", "}" ]
Get a storage instance for plugin settings. The storage will hold values that belong to the given plugin name and user login. Be aware that instances for a specific plugin and login will be cached during one request for better performance. @param string $pluginName @param string $userLogin Use an empty string if settings should be not for a specific login @return Storage
[ "Get", "a", "storage", "instance", "for", "plugin", "settings", "." ]
72df150735664275a60a7861e468c6ff3b152a14
https://github.com/matomo-org/matomo/blob/72df150735664275a60a7861e468c6ff3b152a14/core/Settings/Storage/Factory.php#L35-L45
210,177
matomo-org/matomo
core/Settings/Storage/Factory.php
Factory.getMeasurableSettingsStorage
public function getMeasurableSettingsStorage($idSite, $pluginName) { $id = 'measurableSettings' . (int) $idSite . '#' . $pluginName; if (empty($idSite)) { return $this->getNonPersistentStorage($id . '#nonpersistent'); } if (!isset($this->cache[$id])) { $backend = new Backend\MeasurableSettingsTable($idSite, $pluginName); $this->cache[$id] = $this->makeStorage($backend); } return $this->cache[$id]; }
php
public function getMeasurableSettingsStorage($idSite, $pluginName) { $id = 'measurableSettings' . (int) $idSite . '#' . $pluginName; if (empty($idSite)) { return $this->getNonPersistentStorage($id . '#nonpersistent'); } if (!isset($this->cache[$id])) { $backend = new Backend\MeasurableSettingsTable($idSite, $pluginName); $this->cache[$id] = $this->makeStorage($backend); } return $this->cache[$id]; }
[ "public", "function", "getMeasurableSettingsStorage", "(", "$", "idSite", ",", "$", "pluginName", ")", "{", "$", "id", "=", "'measurableSettings'", ".", "(", "int", ")", "$", "idSite", ".", "'#'", ".", "$", "pluginName", ";", "if", "(", "empty", "(", "$", "idSite", ")", ")", "{", "return", "$", "this", "->", "getNonPersistentStorage", "(", "$", "id", ".", "'#nonpersistent'", ")", ";", "}", "if", "(", "!", "isset", "(", "$", "this", "->", "cache", "[", "$", "id", "]", ")", ")", "{", "$", "backend", "=", "new", "Backend", "\\", "MeasurableSettingsTable", "(", "$", "idSite", ",", "$", "pluginName", ")", ";", "$", "this", "->", "cache", "[", "$", "id", "]", "=", "$", "this", "->", "makeStorage", "(", "$", "backend", ")", ";", "}", "return", "$", "this", "->", "cache", "[", "$", "id", "]", ";", "}" ]
Get a storage instance for measurable settings. The storage will hold values that belong to the given idSite and plugin name. Be aware that a storage instance for a specific site and plugin will be cached during one request for better performance. @param int $idSite If idSite is empty it will use a backend that never actually persists any value. Pass $idSite = 0 to create a storage for a site that is about to be created. @param string $pluginName @return Storage
[ "Get", "a", "storage", "instance", "for", "measurable", "settings", "." ]
72df150735664275a60a7861e468c6ff3b152a14
https://github.com/matomo-org/matomo/blob/72df150735664275a60a7861e468c6ff3b152a14/core/Settings/Storage/Factory.php#L73-L87
210,178
matomo-org/matomo
core/Settings/Storage/Factory.php
Factory.getSitesTable
public function getSitesTable($idSite) { $id = 'sitesTable#' . $idSite; if (empty($idSite)) { return $this->getNonPersistentStorage($id . '#nonpersistent'); } if (!isset($this->cache[$id])) { $backend = new Backend\SitesTable($idSite); $this->cache[$id] = $this->makeStorage($backend); } return $this->cache[$id]; }
php
public function getSitesTable($idSite) { $id = 'sitesTable#' . $idSite; if (empty($idSite)) { return $this->getNonPersistentStorage($id . '#nonpersistent'); } if (!isset($this->cache[$id])) { $backend = new Backend\SitesTable($idSite); $this->cache[$id] = $this->makeStorage($backend); } return $this->cache[$id]; }
[ "public", "function", "getSitesTable", "(", "$", "idSite", ")", "{", "$", "id", "=", "'sitesTable#'", ".", "$", "idSite", ";", "if", "(", "empty", "(", "$", "idSite", ")", ")", "{", "return", "$", "this", "->", "getNonPersistentStorage", "(", "$", "id", ".", "'#nonpersistent'", ")", ";", "}", "if", "(", "!", "isset", "(", "$", "this", "->", "cache", "[", "$", "id", "]", ")", ")", "{", "$", "backend", "=", "new", "Backend", "\\", "SitesTable", "(", "$", "idSite", ")", ";", "$", "this", "->", "cache", "[", "$", "id", "]", "=", "$", "this", "->", "makeStorage", "(", "$", "backend", ")", ";", "}", "return", "$", "this", "->", "cache", "[", "$", "id", "]", ";", "}" ]
Get a storage instance for settings that will be saved in the "site" table. The storage will hold values that belong to the given idSite. Be aware that a storage instance for a specific site will be cached during one request for better performance. @param int $idSite If idSite is empty it will use a backend that never actually persists any value. Pass $idSite = 0 to create a storage for a site that is about to be created. @param int $idSite @return Storage
[ "Get", "a", "storage", "instance", "for", "settings", "that", "will", "be", "saved", "in", "the", "site", "table", "." ]
72df150735664275a60a7861e468c6ff3b152a14
https://github.com/matomo-org/matomo/blob/72df150735664275a60a7861e468c6ff3b152a14/core/Settings/Storage/Factory.php#L101-L115
210,179
matomo-org/matomo
core/Settings/Storage/Factory.php
Factory.makeStorage
public function makeStorage(BackendInterface $backend) { if (SettingsServer::isTrackerApiRequest()) { $backend = new Backend\Cache($backend); } return new Storage($backend); }
php
public function makeStorage(BackendInterface $backend) { if (SettingsServer::isTrackerApiRequest()) { $backend = new Backend\Cache($backend); } return new Storage($backend); }
[ "public", "function", "makeStorage", "(", "BackendInterface", "$", "backend", ")", "{", "if", "(", "SettingsServer", "::", "isTrackerApiRequest", "(", ")", ")", "{", "$", "backend", "=", "new", "Backend", "\\", "Cache", "(", "$", "backend", ")", ";", "}", "return", "new", "Storage", "(", "$", "backend", ")", ";", "}" ]
Makes a new storage object based on a custom backend interface. @param BackendInterface $backend @return Storage
[ "Makes", "a", "new", "storage", "object", "based", "on", "a", "custom", "backend", "interface", "." ]
72df150735664275a60a7861e468c6ff3b152a14
https://github.com/matomo-org/matomo/blob/72df150735664275a60a7861e468c6ff3b152a14/core/Settings/Storage/Factory.php#L134-L141
210,180
matomo-org/matomo
plugins/Live/VisitorFactory.php
VisitorFactory.create
public function create(array $visitorRawData = array()) { $visitor = null; /** * Triggered while visit is filtering in live plugin. Subscribers to this * event can force the use of a custom visitor object that extends from * {@link Piwik\Plugins\Live\VisitorInterface}. * * @param \Piwik\Plugins\Live\VisitorInterface &$visitor Initialized to null, but can be set to * a new visitor object. If it isn't modified * Piwik uses the default class. * @param array $visitorRawData Raw data using in Visitor object constructor. */ Piwik::postEvent('Live.makeNewVisitorObject', array(&$visitor, $visitorRawData)); if (is_null($visitor)) { $visitor = new Visitor($visitorRawData); } elseif (!($visitor instanceof VisitorInterface)) { throw new Exception("The Visitor object set in the plugin must implement VisitorInterface"); } return $visitor; }
php
public function create(array $visitorRawData = array()) { $visitor = null; /** * Triggered while visit is filtering in live plugin. Subscribers to this * event can force the use of a custom visitor object that extends from * {@link Piwik\Plugins\Live\VisitorInterface}. * * @param \Piwik\Plugins\Live\VisitorInterface &$visitor Initialized to null, but can be set to * a new visitor object. If it isn't modified * Piwik uses the default class. * @param array $visitorRawData Raw data using in Visitor object constructor. */ Piwik::postEvent('Live.makeNewVisitorObject', array(&$visitor, $visitorRawData)); if (is_null($visitor)) { $visitor = new Visitor($visitorRawData); } elseif (!($visitor instanceof VisitorInterface)) { throw new Exception("The Visitor object set in the plugin must implement VisitorInterface"); } return $visitor; }
[ "public", "function", "create", "(", "array", "$", "visitorRawData", "=", "array", "(", ")", ")", "{", "$", "visitor", "=", "null", ";", "/**\n * Triggered while visit is filtering in live plugin. Subscribers to this\n * event can force the use of a custom visitor object that extends from\n * {@link Piwik\\Plugins\\Live\\VisitorInterface}.\n *\n * @param \\Piwik\\Plugins\\Live\\VisitorInterface &$visitor Initialized to null, but can be set to\n * a new visitor object. If it isn't modified\n * Piwik uses the default class.\n * @param array $visitorRawData Raw data using in Visitor object constructor.\n */", "Piwik", "::", "postEvent", "(", "'Live.makeNewVisitorObject'", ",", "array", "(", "&", "$", "visitor", ",", "$", "visitorRawData", ")", ")", ";", "if", "(", "is_null", "(", "$", "visitor", ")", ")", "{", "$", "visitor", "=", "new", "Visitor", "(", "$", "visitorRawData", ")", ";", "}", "elseif", "(", "!", "(", "$", "visitor", "instanceof", "VisitorInterface", ")", ")", "{", "throw", "new", "Exception", "(", "\"The Visitor object set in the plugin must implement VisitorInterface\"", ")", ";", "}", "return", "$", "visitor", ";", "}" ]
Returns Visitor object. This method can be overwritten to use a different Visitor object @param array $visitorRawData @throws \Exception @return \Piwik\Plugins\Live\VisitorInterface @ignore
[ "Returns", "Visitor", "object", ".", "This", "method", "can", "be", "overwritten", "to", "use", "a", "different", "Visitor", "object" ]
72df150735664275a60a7861e468c6ff3b152a14
https://github.com/matomo-org/matomo/blob/72df150735664275a60a7861e468c6ff3b152a14/plugins/Live/VisitorFactory.php#L25-L48
210,181
matomo-org/matomo
libs/HTML/QuickForm2/Renderer/Smarty.php
HTML_QuickForm2_Renderer_Smarty.linkToLevelAbove
private function linkToLevelAbove(&$top, $elements, $inGroup = false) { $key = $this->options['key_id'] ? 'id' : 'name'; foreach($elements as &$elem) { $top_key = $elem[$key]; // If in a group, convert something like inGrp[F4grp][F4_1] to F4_1 // Don't do if key_id as the value is a straight id. if( !$this->options['key_id'] && $inGroup && $top_key != '') { if(!(preg_match("/\[?([\w_]+)\]?$/i", $top_key, $match))) throw new HTML_QuickForm2_InvalidArgumentException( "linkToLevelAbove can't obtain the name from '$top_key'"); $top_key = $match[1]; } // Radio buttons: several elements with the same name, make an array if(isset($elem['type']) && $elem['type'] == 'radio') { if( ! isset($top[$top_key])) $top[$top_key] = array('id' => $top_key, 'type' => 'radio', 'elements' => array(0)); $top[$top_key][$elem['id']] = &$elem; } else // Normal field, just link into the level above. if( ! isset($top[$top_key])) $top[$top_key] = &$elem; // Link into the level above // If we have a group link its fields up to this level: if(isset($elem['elements']['0'])) $this->linkToLevelAbove($elem, $elem['elements'], true); // Link errors to the top level: if(isset($elem['error']) && isset($this->array[$elem['error']])) $this->array['errors'][$top_key] = $this->array[$elem['error']]; } }
php
private function linkToLevelAbove(&$top, $elements, $inGroup = false) { $key = $this->options['key_id'] ? 'id' : 'name'; foreach($elements as &$elem) { $top_key = $elem[$key]; // If in a group, convert something like inGrp[F4grp][F4_1] to F4_1 // Don't do if key_id as the value is a straight id. if( !$this->options['key_id'] && $inGroup && $top_key != '') { if(!(preg_match("/\[?([\w_]+)\]?$/i", $top_key, $match))) throw new HTML_QuickForm2_InvalidArgumentException( "linkToLevelAbove can't obtain the name from '$top_key'"); $top_key = $match[1]; } // Radio buttons: several elements with the same name, make an array if(isset($elem['type']) && $elem['type'] == 'radio') { if( ! isset($top[$top_key])) $top[$top_key] = array('id' => $top_key, 'type' => 'radio', 'elements' => array(0)); $top[$top_key][$elem['id']] = &$elem; } else // Normal field, just link into the level above. if( ! isset($top[$top_key])) $top[$top_key] = &$elem; // Link into the level above // If we have a group link its fields up to this level: if(isset($elem['elements']['0'])) $this->linkToLevelAbove($elem, $elem['elements'], true); // Link errors to the top level: if(isset($elem['error']) && isset($this->array[$elem['error']])) $this->array['errors'][$top_key] = $this->array[$elem['error']]; } }
[ "private", "function", "linkToLevelAbove", "(", "&", "$", "top", ",", "$", "elements", ",", "$", "inGroup", "=", "false", ")", "{", "$", "key", "=", "$", "this", "->", "options", "[", "'key_id'", "]", "?", "'id'", ":", "'name'", ";", "foreach", "(", "$", "elements", "as", "&", "$", "elem", ")", "{", "$", "top_key", "=", "$", "elem", "[", "$", "key", "]", ";", "// If in a group, convert something like inGrp[F4grp][F4_1] to F4_1", "// Don't do if key_id as the value is a straight id.", "if", "(", "!", "$", "this", "->", "options", "[", "'key_id'", "]", "&&", "$", "inGroup", "&&", "$", "top_key", "!=", "''", ")", "{", "if", "(", "!", "(", "preg_match", "(", "\"/\\[?([\\w_]+)\\]?$/i\"", ",", "$", "top_key", ",", "$", "match", ")", ")", ")", "throw", "new", "HTML_QuickForm2_InvalidArgumentException", "(", "\"linkToLevelAbove can't obtain the name from '$top_key'\"", ")", ";", "$", "top_key", "=", "$", "match", "[", "1", "]", ";", "}", "// Radio buttons: several elements with the same name, make an array", "if", "(", "isset", "(", "$", "elem", "[", "'type'", "]", ")", "&&", "$", "elem", "[", "'type'", "]", "==", "'radio'", ")", "{", "if", "(", "!", "isset", "(", "$", "top", "[", "$", "top_key", "]", ")", ")", "$", "top", "[", "$", "top_key", "]", "=", "array", "(", "'id'", "=>", "$", "top_key", ",", "'type'", "=>", "'radio'", ",", "'elements'", "=>", "array", "(", "0", ")", ")", ";", "$", "top", "[", "$", "top_key", "]", "[", "$", "elem", "[", "'id'", "]", "]", "=", "&", "$", "elem", ";", "}", "else", "// Normal field, just link into the level above.", "if", "(", "!", "isset", "(", "$", "top", "[", "$", "top_key", "]", ")", ")", "$", "top", "[", "$", "top_key", "]", "=", "&", "$", "elem", ";", "// Link into the level above", "// If we have a group link its fields up to this level:", "if", "(", "isset", "(", "$", "elem", "[", "'elements'", "]", "[", "'0'", "]", ")", ")", "$", "this", "->", "linkToLevelAbove", "(", "$", "elem", ",", "$", "elem", "[", "'elements'", "]", ",", "true", ")", ";", "// Link errors to the top level:", "if", "(", "isset", "(", "$", "elem", "[", "'error'", "]", ")", "&&", "isset", "(", "$", "this", "->", "array", "[", "$", "elem", "[", "'error'", "]", "]", ")", ")", "$", "this", "->", "array", "[", "'errors'", "]", "[", "$", "top_key", "]", "=", "$", "this", "->", "array", "[", "$", "elem", "[", "'error'", "]", "]", ";", "}", "}" ]
Key is 'name' or 'id'.
[ "Key", "is", "name", "or", "id", "." ]
72df150735664275a60a7861e468c6ff3b152a14
https://github.com/matomo-org/matomo/blob/72df150735664275a60a7861e468c6ff3b152a14/libs/HTML/QuickForm2/Renderer/Smarty.php#L256-L289
210,182
matomo-org/matomo
plugins/Insights/InsightReport.php
InsightReport.markMoversAndShakers
public function markMoversAndShakers(DataTable $insight, $currentReport, $lastReport, $totalValue, $lastTotalValue) { if (!$insight->getRowsCount()) { return; } $limitIncreaser = max($insight->getRowsCount(), 3); $limitDecreaser = max($insight->getRowsCount(), 3); $lastDate = $insight->getMetadata('lastDate'); $date = $insight->getMetadata('date'); $period = $insight->getMetadata('period'); $metric = $insight->getMetadata('metric'); $orderBy = $insight->getMetadata('orderBy'); $reportMetadata = $insight->getMetadata('report'); $shakers = $this->generateMoverAndShaker($reportMetadata, $period, $date, $lastDate, $metric, $currentReport, $lastReport, $totalValue, $lastTotalValue, $orderBy, $limitIncreaser, $limitDecreaser); foreach ($insight->getRows() as $row) { $label = $row->getColumn('label'); if ($shakers->getRowFromLabel($label)) { $row->setColumn('isMoverAndShaker', true); } else { $row->setColumn('isMoverAndShaker', false); } } $this->addMoversAndShakersMetadata($insight, $totalValue, $lastTotalValue); }
php
public function markMoversAndShakers(DataTable $insight, $currentReport, $lastReport, $totalValue, $lastTotalValue) { if (!$insight->getRowsCount()) { return; } $limitIncreaser = max($insight->getRowsCount(), 3); $limitDecreaser = max($insight->getRowsCount(), 3); $lastDate = $insight->getMetadata('lastDate'); $date = $insight->getMetadata('date'); $period = $insight->getMetadata('period'); $metric = $insight->getMetadata('metric'); $orderBy = $insight->getMetadata('orderBy'); $reportMetadata = $insight->getMetadata('report'); $shakers = $this->generateMoverAndShaker($reportMetadata, $period, $date, $lastDate, $metric, $currentReport, $lastReport, $totalValue, $lastTotalValue, $orderBy, $limitIncreaser, $limitDecreaser); foreach ($insight->getRows() as $row) { $label = $row->getColumn('label'); if ($shakers->getRowFromLabel($label)) { $row->setColumn('isMoverAndShaker', true); } else { $row->setColumn('isMoverAndShaker', false); } } $this->addMoversAndShakersMetadata($insight, $totalValue, $lastTotalValue); }
[ "public", "function", "markMoversAndShakers", "(", "DataTable", "$", "insight", ",", "$", "currentReport", ",", "$", "lastReport", ",", "$", "totalValue", ",", "$", "lastTotalValue", ")", "{", "if", "(", "!", "$", "insight", "->", "getRowsCount", "(", ")", ")", "{", "return", ";", "}", "$", "limitIncreaser", "=", "max", "(", "$", "insight", "->", "getRowsCount", "(", ")", ",", "3", ")", ";", "$", "limitDecreaser", "=", "max", "(", "$", "insight", "->", "getRowsCount", "(", ")", ",", "3", ")", ";", "$", "lastDate", "=", "$", "insight", "->", "getMetadata", "(", "'lastDate'", ")", ";", "$", "date", "=", "$", "insight", "->", "getMetadata", "(", "'date'", ")", ";", "$", "period", "=", "$", "insight", "->", "getMetadata", "(", "'period'", ")", ";", "$", "metric", "=", "$", "insight", "->", "getMetadata", "(", "'metric'", ")", ";", "$", "orderBy", "=", "$", "insight", "->", "getMetadata", "(", "'orderBy'", ")", ";", "$", "reportMetadata", "=", "$", "insight", "->", "getMetadata", "(", "'report'", ")", ";", "$", "shakers", "=", "$", "this", "->", "generateMoverAndShaker", "(", "$", "reportMetadata", ",", "$", "period", ",", "$", "date", ",", "$", "lastDate", ",", "$", "metric", ",", "$", "currentReport", ",", "$", "lastReport", ",", "$", "totalValue", ",", "$", "lastTotalValue", ",", "$", "orderBy", ",", "$", "limitIncreaser", ",", "$", "limitDecreaser", ")", ";", "foreach", "(", "$", "insight", "->", "getRows", "(", ")", "as", "$", "row", ")", "{", "$", "label", "=", "$", "row", "->", "getColumn", "(", "'label'", ")", ";", "if", "(", "$", "shakers", "->", "getRowFromLabel", "(", "$", "label", ")", ")", "{", "$", "row", "->", "setColumn", "(", "'isMoverAndShaker'", ",", "true", ")", ";", "}", "else", "{", "$", "row", "->", "setColumn", "(", "'isMoverAndShaker'", ",", "false", ")", ";", "}", "}", "$", "this", "->", "addMoversAndShakersMetadata", "(", "$", "insight", ",", "$", "totalValue", ",", "$", "lastTotalValue", ")", ";", "}" ]
Extends an already generated insight report by adding a column "isMoverAndShaker" whether a row is also a "Mover and Shaker" or not. Avoids the need to fetch all reports again when we already have the currentReport/lastReport
[ "Extends", "an", "already", "generated", "insight", "report", "by", "adding", "a", "column", "isMoverAndShaker", "whether", "a", "row", "is", "also", "a", "Mover", "and", "Shaker", "or", "not", "." ]
72df150735664275a60a7861e468c6ff3b152a14
https://github.com/matomo-org/matomo/blob/72df150735664275a60a7861e468c6ff3b152a14/plugins/Insights/InsightReport.php#L86-L115
210,183
matomo-org/matomo
core/DataTable/Map.php
Map.filter
public function filter($className, $parameters = array()) { foreach ($this->getDataTables() as $table) { $table->filter($className, $parameters); } }
php
public function filter($className, $parameters = array()) { foreach ($this->getDataTables() as $table) { $table->filter($className, $parameters); } }
[ "public", "function", "filter", "(", "$", "className", ",", "$", "parameters", "=", "array", "(", ")", ")", "{", "foreach", "(", "$", "this", "->", "getDataTables", "(", ")", "as", "$", "table", ")", "{", "$", "table", "->", "filter", "(", "$", "className", ",", "$", "parameters", ")", ";", "}", "}" ]
Apply a filter to all tables contained by this instance. @param string|Closure $className Name of filter class or a Closure. @param array $parameters Parameters to pass to the filter.
[ "Apply", "a", "filter", "to", "all", "tables", "contained", "by", "this", "instance", "." ]
72df150735664275a60a7861e468c6ff3b152a14
https://github.com/matomo-org/matomo/blob/72df150735664275a60a7861e468c6ff3b152a14/core/DataTable/Map.php#L106-L111
210,184
matomo-org/matomo
core/DataTable/Map.php
Map.filterSubtables
public function filterSubtables($className, $parameters = array()) { foreach ($this->getDataTables() as $table) { $table->filterSubtables($className, $parameters); } }
php
public function filterSubtables($className, $parameters = array()) { foreach ($this->getDataTables() as $table) { $table->filterSubtables($className, $parameters); } }
[ "public", "function", "filterSubtables", "(", "$", "className", ",", "$", "parameters", "=", "array", "(", ")", ")", "{", "foreach", "(", "$", "this", "->", "getDataTables", "(", ")", "as", "$", "table", ")", "{", "$", "table", "->", "filterSubtables", "(", "$", "className", ",", "$", "parameters", ")", ";", "}", "}" ]
Apply a filter to all subtables contained by this instance. @param string|Closure $className Name of filter class or a Closure. @param array $parameters Parameters to pass to the filter.
[ "Apply", "a", "filter", "to", "all", "subtables", "contained", "by", "this", "instance", "." ]
72df150735664275a60a7861e468c6ff3b152a14
https://github.com/matomo-org/matomo/blob/72df150735664275a60a7861e468c6ff3b152a14/core/DataTable/Map.php#L119-L124
210,185
matomo-org/matomo
core/DataTable/Map.php
Map.queueFilterSubtables
public function queueFilterSubtables($className, $parameters = array()) { foreach ($this->getDataTables() as $table) { $table->queueFilterSubtables($className, $parameters); } }
php
public function queueFilterSubtables($className, $parameters = array()) { foreach ($this->getDataTables() as $table) { $table->queueFilterSubtables($className, $parameters); } }
[ "public", "function", "queueFilterSubtables", "(", "$", "className", ",", "$", "parameters", "=", "array", "(", ")", ")", "{", "foreach", "(", "$", "this", "->", "getDataTables", "(", ")", "as", "$", "table", ")", "{", "$", "table", "->", "queueFilterSubtables", "(", "$", "className", ",", "$", "parameters", ")", ";", "}", "}" ]
Apply a queued filter to all subtables contained by this instance. @param string|Closure $className Name of filter class or a Closure. @param array $parameters Parameters to pass to the filter.
[ "Apply", "a", "queued", "filter", "to", "all", "subtables", "contained", "by", "this", "instance", "." ]
72df150735664275a60a7861e468c6ff3b152a14
https://github.com/matomo-org/matomo/blob/72df150735664275a60a7861e468c6ff3b152a14/core/DataTable/Map.php#L132-L137
210,186
matomo-org/matomo
core/DataTable/Map.php
Map.copyRowsAndSetLabel
private function copyRowsAndSetLabel($toTable, $fromTable, $label) { foreach ($fromTable->getRows() as $fromRow) { $oldColumns = $fromRow->getColumns(); unset($oldColumns['label']); $columns = array_merge(array('label' => $label), $oldColumns); $row = new Row(array( Row::COLUMNS => $columns, Row::METADATA => $fromRow->getMetadata(), Row::DATATABLE_ASSOCIATED => $fromRow->getIdSubDataTable() )); $toTable->addRow($row); } }
php
private function copyRowsAndSetLabel($toTable, $fromTable, $label) { foreach ($fromTable->getRows() as $fromRow) { $oldColumns = $fromRow->getColumns(); unset($oldColumns['label']); $columns = array_merge(array('label' => $label), $oldColumns); $row = new Row(array( Row::COLUMNS => $columns, Row::METADATA => $fromRow->getMetadata(), Row::DATATABLE_ASSOCIATED => $fromRow->getIdSubDataTable() )); $toTable->addRow($row); } }
[ "private", "function", "copyRowsAndSetLabel", "(", "$", "toTable", ",", "$", "fromTable", ",", "$", "label", ")", "{", "foreach", "(", "$", "fromTable", "->", "getRows", "(", ")", "as", "$", "fromRow", ")", "{", "$", "oldColumns", "=", "$", "fromRow", "->", "getColumns", "(", ")", ";", "unset", "(", "$", "oldColumns", "[", "'label'", "]", ")", ";", "$", "columns", "=", "array_merge", "(", "array", "(", "'label'", "=>", "$", "label", ")", ",", "$", "oldColumns", ")", ";", "$", "row", "=", "new", "Row", "(", "array", "(", "Row", "::", "COLUMNS", "=>", "$", "columns", ",", "Row", "::", "METADATA", "=>", "$", "fromRow", "->", "getMetadata", "(", ")", ",", "Row", "::", "DATATABLE_ASSOCIATED", "=>", "$", "fromRow", "->", "getIdSubDataTable", "(", ")", ")", ")", ";", "$", "toTable", "->", "addRow", "(", "$", "row", ")", ";", "}", "}" ]
Utility function used by mergeChildren. Copies the rows from one table, sets their 'label' columns to a value and adds them to another table. @param DataTable $toTable The table to copy rows to. @param DataTable $fromTable The table to copy rows from. @param string $label The value to set the 'label' column of every copied row.
[ "Utility", "function", "used", "by", "mergeChildren", ".", "Copies", "the", "rows", "from", "one", "table", "sets", "their", "label", "columns", "to", "a", "value", "and", "adds", "them", "to", "another", "table", "." ]
72df150735664275a60a7861e468c6ff3b152a14
https://github.com/matomo-org/matomo/blob/72df150735664275a60a7861e468c6ff3b152a14/core/DataTable/Map.php#L435-L449
210,187
matomo-org/matomo
core/DataTable/Map.php
Map.addDataTable
public function addDataTable(DataTable $tableToSum) { foreach ($this->getDataTables() as $childTable) { $childTable->addDataTable($tableToSum); } }
php
public function addDataTable(DataTable $tableToSum) { foreach ($this->getDataTables() as $childTable) { $childTable->addDataTable($tableToSum); } }
[ "public", "function", "addDataTable", "(", "DataTable", "$", "tableToSum", ")", "{", "foreach", "(", "$", "this", "->", "getDataTables", "(", ")", "as", "$", "childTable", ")", "{", "$", "childTable", "->", "addDataTable", "(", "$", "tableToSum", ")", ";", "}", "}" ]
Sums a DataTable to all the tables in this array. _Note: Will only add `$tableToSum` if the childTable has some rows._ See {@link Piwik\DataTable::addDataTable()}. @param DataTable $tableToSum
[ "Sums", "a", "DataTable", "to", "all", "the", "tables", "in", "this", "array", "." ]
72df150735664275a60a7861e468c6ff3b152a14
https://github.com/matomo-org/matomo/blob/72df150735664275a60a7861e468c6ff3b152a14/core/DataTable/Map.php#L460-L465
210,188
matomo-org/matomo
plugins/Actions/Actions/ActionClickUrl.php
ActionClickUrl.detectActionIsOutlinkOnAliasHost
protected function detectActionIsOutlinkOnAliasHost(Action $action, $idSite) { $decodedActionUrl = $action->getActionUrl(); $actionUrlParsed = @parse_url($decodedActionUrl); if (!isset($actionUrlParsed['host'])) { return false; } return Visit::isHostKnownAliasHost($actionUrlParsed['host'], $idSite); }
php
protected function detectActionIsOutlinkOnAliasHost(Action $action, $idSite) { $decodedActionUrl = $action->getActionUrl(); $actionUrlParsed = @parse_url($decodedActionUrl); if (!isset($actionUrlParsed['host'])) { return false; } return Visit::isHostKnownAliasHost($actionUrlParsed['host'], $idSite); }
[ "protected", "function", "detectActionIsOutlinkOnAliasHost", "(", "Action", "$", "action", ",", "$", "idSite", ")", "{", "$", "decodedActionUrl", "=", "$", "action", "->", "getActionUrl", "(", ")", ";", "$", "actionUrlParsed", "=", "@", "parse_url", "(", "$", "decodedActionUrl", ")", ";", "if", "(", "!", "isset", "(", "$", "actionUrlParsed", "[", "'host'", "]", ")", ")", "{", "return", "false", ";", "}", "return", "Visit", "::", "isHostKnownAliasHost", "(", "$", "actionUrlParsed", "[", "'host'", "]", ",", "$", "idSite", ")", ";", "}" ]
Detect whether action is an outlink given host aliases @param Action $action @return bool true if the outlink the visitor clicked on points to one of the known hosts for this website
[ "Detect", "whether", "action", "is", "an", "outlink", "given", "host", "aliases" ]
72df150735664275a60a7861e468c6ff3b152a14
https://github.com/matomo-org/matomo/blob/72df150735664275a60a7861e468c6ff3b152a14/plugins/Actions/Actions/ActionClickUrl.php#L60-L70
210,189
matomo-org/matomo
core/ProxyHttp.php
ProxyHttp.isPhpOutputCompressed
public static function isPhpOutputCompressed() { // Off = ''; On = '1'; otherwise, it's a buffer size $zlibOutputCompression = ini_get('zlib.output_compression'); // could be ob_gzhandler, ob_deflatehandler, etc $outputHandler = ini_get('output_handler'); // output handlers can be stacked $obHandlers = array_filter(ob_list_handlers(), function ($var) { return $var !== "default output handler"; }); // user defined handler via wrapper if (!defined('PIWIK_TEST_MODE')) { $autoPrependFile = ini_get('auto_prepend_file'); $autoAppendFile = ini_get('auto_append_file'); } return !empty($zlibOutputCompression) || !empty($outputHandler) || !empty($obHandlers) || !empty($autoPrependFile) || !empty($autoAppendFile); }
php
public static function isPhpOutputCompressed() { // Off = ''; On = '1'; otherwise, it's a buffer size $zlibOutputCompression = ini_get('zlib.output_compression'); // could be ob_gzhandler, ob_deflatehandler, etc $outputHandler = ini_get('output_handler'); // output handlers can be stacked $obHandlers = array_filter(ob_list_handlers(), function ($var) { return $var !== "default output handler"; }); // user defined handler via wrapper if (!defined('PIWIK_TEST_MODE')) { $autoPrependFile = ini_get('auto_prepend_file'); $autoAppendFile = ini_get('auto_append_file'); } return !empty($zlibOutputCompression) || !empty($outputHandler) || !empty($obHandlers) || !empty($autoPrependFile) || !empty($autoAppendFile); }
[ "public", "static", "function", "isPhpOutputCompressed", "(", ")", "{", "// Off = ''; On = '1'; otherwise, it's a buffer size", "$", "zlibOutputCompression", "=", "ini_get", "(", "'zlib.output_compression'", ")", ";", "// could be ob_gzhandler, ob_deflatehandler, etc", "$", "outputHandler", "=", "ini_get", "(", "'output_handler'", ")", ";", "// output handlers can be stacked", "$", "obHandlers", "=", "array_filter", "(", "ob_list_handlers", "(", ")", ",", "function", "(", "$", "var", ")", "{", "return", "$", "var", "!==", "\"default output handler\"", ";", "}", ")", ";", "// user defined handler via wrapper", "if", "(", "!", "defined", "(", "'PIWIK_TEST_MODE'", ")", ")", "{", "$", "autoPrependFile", "=", "ini_get", "(", "'auto_prepend_file'", ")", ";", "$", "autoAppendFile", "=", "ini_get", "(", "'auto_append_file'", ")", ";", "}", "return", "!", "empty", "(", "$", "zlibOutputCompression", ")", "||", "!", "empty", "(", "$", "outputHandler", ")", "||", "!", "empty", "(", "$", "obHandlers", ")", "||", "!", "empty", "(", "$", "autoPrependFile", ")", "||", "!", "empty", "(", "$", "autoAppendFile", ")", ";", "}" ]
Test if php output is compressed @return bool True if php output is (or suspected/likely) to be compressed
[ "Test", "if", "php", "output", "is", "compressed" ]
72df150735664275a60a7861e468c6ff3b152a14
https://github.com/matomo-org/matomo/blob/72df150735664275a60a7861e468c6ff3b152a14/core/ProxyHttp.php#L178-L202
210,190
matomo-org/matomo
core/API/Proxy.php
Proxy.registerClass
public function registerClass($className) { if (isset($this->alreadyRegistered[$className])) { return; } $this->includeApiFile($className); $this->checkClassIsSingleton($className); $rClass = new ReflectionClass($className); if (!$this->shouldHideAPIMethod($rClass->getDocComment())) { foreach ($rClass->getMethods() as $method) { $this->loadMethodMetadata($className, $method); } $this->setDocumentation($rClass, $className); $this->alreadyRegistered[$className] = true; } }
php
public function registerClass($className) { if (isset($this->alreadyRegistered[$className])) { return; } $this->includeApiFile($className); $this->checkClassIsSingleton($className); $rClass = new ReflectionClass($className); if (!$this->shouldHideAPIMethod($rClass->getDocComment())) { foreach ($rClass->getMethods() as $method) { $this->loadMethodMetadata($className, $method); } $this->setDocumentation($rClass, $className); $this->alreadyRegistered[$className] = true; } }
[ "public", "function", "registerClass", "(", "$", "className", ")", "{", "if", "(", "isset", "(", "$", "this", "->", "alreadyRegistered", "[", "$", "className", "]", ")", ")", "{", "return", ";", "}", "$", "this", "->", "includeApiFile", "(", "$", "className", ")", ";", "$", "this", "->", "checkClassIsSingleton", "(", "$", "className", ")", ";", "$", "rClass", "=", "new", "ReflectionClass", "(", "$", "className", ")", ";", "if", "(", "!", "$", "this", "->", "shouldHideAPIMethod", "(", "$", "rClass", "->", "getDocComment", "(", ")", ")", ")", "{", "foreach", "(", "$", "rClass", "->", "getMethods", "(", ")", "as", "$", "method", ")", "{", "$", "this", "->", "loadMethodMetadata", "(", "$", "className", ",", "$", "method", ")", ";", "}", "$", "this", "->", "setDocumentation", "(", "$", "rClass", ",", "$", "className", ")", ";", "$", "this", "->", "alreadyRegistered", "[", "$", "className", "]", "=", "true", ";", "}", "}" ]
Registers the API information of a given module. The module to be registered must be - a singleton (providing a getInstance() method) - the API file must be located in plugins/ModuleName/API.php for example plugins/Referrers/API.php The method will introspect the methods, their parameters, etc. @param string $className ModuleName eg. "API"
[ "Registers", "the", "API", "information", "of", "a", "given", "module", "." ]
72df150735664275a60a7861e468c6ff3b152a14
https://github.com/matomo-org/matomo/blob/72df150735664275a60a7861e468c6ff3b152a14/core/API/Proxy.php#L75-L92
210,191
matomo-org/matomo
core/API/Proxy.php
Proxy.setDocumentation
private function setDocumentation($rClass, $className) { // Doc comment $doc = $rClass->getDocComment(); $doc = str_replace(" * " . PHP_EOL, "<br>", $doc); // boldify the first line only if there is more than one line, otherwise too much bold if (substr_count($doc, '<br>') > 1) { $firstLineBreak = strpos($doc, "<br>"); $doc = "<div class='apiFirstLine'>" . substr($doc, 0, $firstLineBreak) . "</div>" . substr($doc, $firstLineBreak + strlen("<br>")); } $doc = preg_replace("/(@package)[a-z _A-Z]*/", "", $doc); $doc = preg_replace("/(@method).*/", "", $doc); $doc = str_replace(array("\t", "\n", "/**", "*/", " * ", " *", " ", "\t*", " * @package"), " ", $doc); // replace 'foo' and `bar` and "foobar" with code blocks... much magic $doc = preg_replace('/`(.*?)`/', '<code>$1</code>', $doc); $this->metadataArray[$className]['__documentation'] = $doc; }
php
private function setDocumentation($rClass, $className) { // Doc comment $doc = $rClass->getDocComment(); $doc = str_replace(" * " . PHP_EOL, "<br>", $doc); // boldify the first line only if there is more than one line, otherwise too much bold if (substr_count($doc, '<br>') > 1) { $firstLineBreak = strpos($doc, "<br>"); $doc = "<div class='apiFirstLine'>" . substr($doc, 0, $firstLineBreak) . "</div>" . substr($doc, $firstLineBreak + strlen("<br>")); } $doc = preg_replace("/(@package)[a-z _A-Z]*/", "", $doc); $doc = preg_replace("/(@method).*/", "", $doc); $doc = str_replace(array("\t", "\n", "/**", "*/", " * ", " *", " ", "\t*", " * @package"), " ", $doc); // replace 'foo' and `bar` and "foobar" with code blocks... much magic $doc = preg_replace('/`(.*?)`/', '<code>$1</code>', $doc); $this->metadataArray[$className]['__documentation'] = $doc; }
[ "private", "function", "setDocumentation", "(", "$", "rClass", ",", "$", "className", ")", "{", "// Doc comment", "$", "doc", "=", "$", "rClass", "->", "getDocComment", "(", ")", ";", "$", "doc", "=", "str_replace", "(", "\" * \"", ".", "PHP_EOL", ",", "\"<br>\"", ",", "$", "doc", ")", ";", "// boldify the first line only if there is more than one line, otherwise too much bold", "if", "(", "substr_count", "(", "$", "doc", ",", "'<br>'", ")", ">", "1", ")", "{", "$", "firstLineBreak", "=", "strpos", "(", "$", "doc", ",", "\"<br>\"", ")", ";", "$", "doc", "=", "\"<div class='apiFirstLine'>\"", ".", "substr", "(", "$", "doc", ",", "0", ",", "$", "firstLineBreak", ")", ".", "\"</div>\"", ".", "substr", "(", "$", "doc", ",", "$", "firstLineBreak", "+", "strlen", "(", "\"<br>\"", ")", ")", ";", "}", "$", "doc", "=", "preg_replace", "(", "\"/(@package)[a-z _A-Z]*/\"", ",", "\"\"", ",", "$", "doc", ")", ";", "$", "doc", "=", "preg_replace", "(", "\"/(@method).*/\"", ",", "\"\"", ",", "$", "doc", ")", ";", "$", "doc", "=", "str_replace", "(", "array", "(", "\"\\t\"", ",", "\"\\n\"", ",", "\"/**\"", ",", "\"*/\"", ",", "\" * \"", ",", "\" *\"", ",", "\" \"", ",", "\"\\t*\"", ",", "\" * @package\"", ")", ",", "\" \"", ",", "$", "doc", ")", ";", "// replace 'foo' and `bar` and \"foobar\" with code blocks... much magic", "$", "doc", "=", "preg_replace", "(", "'/`(.*?)`/'", ",", "'<code>$1</code>'", ",", "$", "doc", ")", ";", "$", "this", "->", "metadataArray", "[", "$", "className", "]", "[", "'__documentation'", "]", "=", "$", "doc", ";", "}" ]
Will be displayed in the API page @param ReflectionClass $rClass Instance of ReflectionClass @param string $className Name of the class
[ "Will", "be", "displayed", "in", "the", "API", "page" ]
72df150735664275a60a7861e468c6ff3b152a14
https://github.com/matomo-org/matomo/blob/72df150735664275a60a7861e468c6ff3b152a14/core/API/Proxy.php#L100-L118
210,192
matomo-org/matomo
core/API/Proxy.php
Proxy.getRequestParametersArray
private function getRequestParametersArray($requiredParameters, $parametersRequest) { $finalParameters = array(); foreach ($requiredParameters as $name => $defaultValue) { try { if ($defaultValue instanceof NoDefaultValue) { $requestValue = Common::getRequestVar($name, null, null, $parametersRequest); } else { try { if ($name == 'segment' && !empty($parametersRequest['segment'])) { // segment parameter is an exception: we do not want to sanitize user input or it would break the segment encoding $requestValue = ($parametersRequest['segment']); } else { $requestValue = Common::getRequestVar($name, $defaultValue, null, $parametersRequest); } } catch (Exception $e) { // Special case: empty parameter in the URL, should return the empty string if (isset($parametersRequest[$name]) && $parametersRequest[$name] === '' ) { $requestValue = ''; } else { $requestValue = $defaultValue; } } } } catch (Exception $e) { throw new Exception(Piwik::translate('General_PleaseSpecifyValue', array($name))); } $finalParameters[$name] = $requestValue; } return $finalParameters; }
php
private function getRequestParametersArray($requiredParameters, $parametersRequest) { $finalParameters = array(); foreach ($requiredParameters as $name => $defaultValue) { try { if ($defaultValue instanceof NoDefaultValue) { $requestValue = Common::getRequestVar($name, null, null, $parametersRequest); } else { try { if ($name == 'segment' && !empty($parametersRequest['segment'])) { // segment parameter is an exception: we do not want to sanitize user input or it would break the segment encoding $requestValue = ($parametersRequest['segment']); } else { $requestValue = Common::getRequestVar($name, $defaultValue, null, $parametersRequest); } } catch (Exception $e) { // Special case: empty parameter in the URL, should return the empty string if (isset($parametersRequest[$name]) && $parametersRequest[$name] === '' ) { $requestValue = ''; } else { $requestValue = $defaultValue; } } } } catch (Exception $e) { throw new Exception(Piwik::translate('General_PleaseSpecifyValue', array($name))); } $finalParameters[$name] = $requestValue; } return $finalParameters; }
[ "private", "function", "getRequestParametersArray", "(", "$", "requiredParameters", ",", "$", "parametersRequest", ")", "{", "$", "finalParameters", "=", "array", "(", ")", ";", "foreach", "(", "$", "requiredParameters", "as", "$", "name", "=>", "$", "defaultValue", ")", "{", "try", "{", "if", "(", "$", "defaultValue", "instanceof", "NoDefaultValue", ")", "{", "$", "requestValue", "=", "Common", "::", "getRequestVar", "(", "$", "name", ",", "null", ",", "null", ",", "$", "parametersRequest", ")", ";", "}", "else", "{", "try", "{", "if", "(", "$", "name", "==", "'segment'", "&&", "!", "empty", "(", "$", "parametersRequest", "[", "'segment'", "]", ")", ")", "{", "// segment parameter is an exception: we do not want to sanitize user input or it would break the segment encoding", "$", "requestValue", "=", "(", "$", "parametersRequest", "[", "'segment'", "]", ")", ";", "}", "else", "{", "$", "requestValue", "=", "Common", "::", "getRequestVar", "(", "$", "name", ",", "$", "defaultValue", ",", "null", ",", "$", "parametersRequest", ")", ";", "}", "}", "catch", "(", "Exception", "$", "e", ")", "{", "// Special case: empty parameter in the URL, should return the empty string", "if", "(", "isset", "(", "$", "parametersRequest", "[", "$", "name", "]", ")", "&&", "$", "parametersRequest", "[", "$", "name", "]", "===", "''", ")", "{", "$", "requestValue", "=", "''", ";", "}", "else", "{", "$", "requestValue", "=", "$", "defaultValue", ";", "}", "}", "}", "}", "catch", "(", "Exception", "$", "e", ")", "{", "throw", "new", "Exception", "(", "Piwik", "::", "translate", "(", "'General_PleaseSpecifyValue'", ",", "array", "(", "$", "name", ")", ")", ")", ";", "}", "$", "finalParameters", "[", "$", "name", "]", "=", "$", "requestValue", ";", "}", "return", "$", "finalParameters", ";", "}" ]
Returns an array containing the values of the parameters to pass to the method to call @param array $requiredParameters array of (parameter name, default value) @param array $parametersRequest @throws Exception @return array values to pass to the function call
[ "Returns", "an", "array", "containing", "the", "values", "of", "the", "parameters", "to", "pass", "to", "the", "method", "to", "call" ]
72df150735664275a60a7861e468c6ff3b152a14
https://github.com/matomo-org/matomo/blob/72df150735664275a60a7861e468c6ff3b152a14/core/API/Proxy.php#L402-L434
210,193
matomo-org/matomo
core/API/Proxy.php
Proxy.checkMethodExists
private function checkMethodExists($className, $methodName) { if (!$this->isMethodAvailable($className, $methodName)) { throw new Exception(Piwik::translate('General_ExceptionMethodNotFound', array($methodName, $className))); } }
php
private function checkMethodExists($className, $methodName) { if (!$this->isMethodAvailable($className, $methodName)) { throw new Exception(Piwik::translate('General_ExceptionMethodNotFound', array($methodName, $className))); } }
[ "private", "function", "checkMethodExists", "(", "$", "className", ",", "$", "methodName", ")", "{", "if", "(", "!", "$", "this", "->", "isMethodAvailable", "(", "$", "className", ",", "$", "methodName", ")", ")", "{", "throw", "new", "Exception", "(", "Piwik", "::", "translate", "(", "'General_ExceptionMethodNotFound'", ",", "array", "(", "$", "methodName", ",", "$", "className", ")", ")", ")", ";", "}", "}" ]
Checks that the method exists in the class @param string $className The class name @param string $methodName The method name @throws Exception If the method is not found
[ "Checks", "that", "the", "method", "exists", "in", "the", "class" ]
72df150735664275a60a7861e468c6ff3b152a14
https://github.com/matomo-org/matomo/blob/72df150735664275a60a7861e468c6ff3b152a14/core/API/Proxy.php#L490-L495
210,194
matomo-org/matomo
core/Tracker/Action.php
Action.factory
public static function factory(Request $request) { /** @var Action[] $actions */ $actions = self::getAllActions($request); foreach ($actions as $actionType) { if (empty($action)) { $action = $actionType; continue; } $posPrevious = self::getPriority($action); $posCurrent = self::getPriority($actionType); if ($posCurrent > $posPrevious) { $action = $actionType; } } if (!empty($action)) { return $action; } return new ActionPageview($request); }
php
public static function factory(Request $request) { /** @var Action[] $actions */ $actions = self::getAllActions($request); foreach ($actions as $actionType) { if (empty($action)) { $action = $actionType; continue; } $posPrevious = self::getPriority($action); $posCurrent = self::getPriority($actionType); if ($posCurrent > $posPrevious) { $action = $actionType; } } if (!empty($action)) { return $action; } return new ActionPageview($request); }
[ "public", "static", "function", "factory", "(", "Request", "$", "request", ")", "{", "/** @var Action[] $actions */", "$", "actions", "=", "self", "::", "getAllActions", "(", "$", "request", ")", ";", "foreach", "(", "$", "actions", "as", "$", "actionType", ")", "{", "if", "(", "empty", "(", "$", "action", ")", ")", "{", "$", "action", "=", "$", "actionType", ";", "continue", ";", "}", "$", "posPrevious", "=", "self", "::", "getPriority", "(", "$", "action", ")", ";", "$", "posCurrent", "=", "self", "::", "getPriority", "(", "$", "actionType", ")", ";", "if", "(", "$", "posCurrent", ">", "$", "posPrevious", ")", "{", "$", "action", "=", "$", "actionType", ";", "}", "}", "if", "(", "!", "empty", "(", "$", "action", ")", ")", "{", "return", "$", "action", ";", "}", "return", "new", "ActionPageview", "(", "$", "request", ")", ";", "}" ]
Makes the correct Action object based on the request. @param Request $request @return Action
[ "Makes", "the", "correct", "Action", "object", "based", "on", "the", "request", "." ]
72df150735664275a60a7861e468c6ff3b152a14
https://github.com/matomo-org/matomo/blob/72df150735664275a60a7861e468c6ff3b152a14/core/Tracker/Action.php#L85-L109
210,195
matomo-org/matomo
core/Tracker/Action.php
Action.record
public function record(Visitor $visitor, $idReferrerActionUrl, $idReferrerActionName) { $this->loadIdsFromLogActionTable(); $visitAction = array( 'idvisit' => $visitor->getVisitorColumn('idvisit'), 'idsite' => $this->request->getIdSite(), 'idvisitor' => $visitor->getVisitorColumn('idvisitor'), 'idaction_url' => $this->getIdActionUrl(), 'idaction_url_ref' => $idReferrerActionUrl, 'idaction_name_ref' => $idReferrerActionName ); /** @var ActionDimension[] $dimensions */ $dimensions = ActionDimension::getAllDimensions(); foreach ($dimensions as $dimension) { $value = $dimension->onNewAction($this->request, $visitor, $this); if ($value !== false) { if (is_float($value)) { $value = Common::forceDotAsSeparatorForDecimalPoint($value); } $visitAction[$dimension->getColumnName()] = $value; } } // idaction_name is NULLable. we only set it when applicable if ($this->isActionHasActionName()) { $visitAction['idaction_name'] = (int)$this->getIdActionName(); } foreach ($this->actionIdsCached as $field => $idAction) { $visitAction[$field] = ($idAction === false) ? 0 : $idAction; } $customValue = $this->getCustomFloatValue(); if ($customValue !== false && $customValue !== null && $customValue !== '') { $visitAction[self::DB_COLUMN_CUSTOM_FLOAT] = Common::forceDotAsSeparatorForDecimalPoint($customValue); } $visitAction = array_merge($visitAction, $this->customFields); $this->idLinkVisitAction = $this->getModel()->createAction($visitAction); $visitAction['idlink_va'] = $this->idLinkVisitAction; Common::printDebug("Inserted new action:"); $visitActionDebug = $visitAction; $visitActionDebug['idvisitor'] = bin2hex($visitActionDebug['idvisitor']); Common::printDebug($visitActionDebug); }
php
public function record(Visitor $visitor, $idReferrerActionUrl, $idReferrerActionName) { $this->loadIdsFromLogActionTable(); $visitAction = array( 'idvisit' => $visitor->getVisitorColumn('idvisit'), 'idsite' => $this->request->getIdSite(), 'idvisitor' => $visitor->getVisitorColumn('idvisitor'), 'idaction_url' => $this->getIdActionUrl(), 'idaction_url_ref' => $idReferrerActionUrl, 'idaction_name_ref' => $idReferrerActionName ); /** @var ActionDimension[] $dimensions */ $dimensions = ActionDimension::getAllDimensions(); foreach ($dimensions as $dimension) { $value = $dimension->onNewAction($this->request, $visitor, $this); if ($value !== false) { if (is_float($value)) { $value = Common::forceDotAsSeparatorForDecimalPoint($value); } $visitAction[$dimension->getColumnName()] = $value; } } // idaction_name is NULLable. we only set it when applicable if ($this->isActionHasActionName()) { $visitAction['idaction_name'] = (int)$this->getIdActionName(); } foreach ($this->actionIdsCached as $field => $idAction) { $visitAction[$field] = ($idAction === false) ? 0 : $idAction; } $customValue = $this->getCustomFloatValue(); if ($customValue !== false && $customValue !== null && $customValue !== '') { $visitAction[self::DB_COLUMN_CUSTOM_FLOAT] = Common::forceDotAsSeparatorForDecimalPoint($customValue); } $visitAction = array_merge($visitAction, $this->customFields); $this->idLinkVisitAction = $this->getModel()->createAction($visitAction); $visitAction['idlink_va'] = $this->idLinkVisitAction; Common::printDebug("Inserted new action:"); $visitActionDebug = $visitAction; $visitActionDebug['idvisitor'] = bin2hex($visitActionDebug['idvisitor']); Common::printDebug($visitActionDebug); }
[ "public", "function", "record", "(", "Visitor", "$", "visitor", ",", "$", "idReferrerActionUrl", ",", "$", "idReferrerActionName", ")", "{", "$", "this", "->", "loadIdsFromLogActionTable", "(", ")", ";", "$", "visitAction", "=", "array", "(", "'idvisit'", "=>", "$", "visitor", "->", "getVisitorColumn", "(", "'idvisit'", ")", ",", "'idsite'", "=>", "$", "this", "->", "request", "->", "getIdSite", "(", ")", ",", "'idvisitor'", "=>", "$", "visitor", "->", "getVisitorColumn", "(", "'idvisitor'", ")", ",", "'idaction_url'", "=>", "$", "this", "->", "getIdActionUrl", "(", ")", ",", "'idaction_url_ref'", "=>", "$", "idReferrerActionUrl", ",", "'idaction_name_ref'", "=>", "$", "idReferrerActionName", ")", ";", "/** @var ActionDimension[] $dimensions */", "$", "dimensions", "=", "ActionDimension", "::", "getAllDimensions", "(", ")", ";", "foreach", "(", "$", "dimensions", "as", "$", "dimension", ")", "{", "$", "value", "=", "$", "dimension", "->", "onNewAction", "(", "$", "this", "->", "request", ",", "$", "visitor", ",", "$", "this", ")", ";", "if", "(", "$", "value", "!==", "false", ")", "{", "if", "(", "is_float", "(", "$", "value", ")", ")", "{", "$", "value", "=", "Common", "::", "forceDotAsSeparatorForDecimalPoint", "(", "$", "value", ")", ";", "}", "$", "visitAction", "[", "$", "dimension", "->", "getColumnName", "(", ")", "]", "=", "$", "value", ";", "}", "}", "// idaction_name is NULLable. we only set it when applicable", "if", "(", "$", "this", "->", "isActionHasActionName", "(", ")", ")", "{", "$", "visitAction", "[", "'idaction_name'", "]", "=", "(", "int", ")", "$", "this", "->", "getIdActionName", "(", ")", ";", "}", "foreach", "(", "$", "this", "->", "actionIdsCached", "as", "$", "field", "=>", "$", "idAction", ")", "{", "$", "visitAction", "[", "$", "field", "]", "=", "(", "$", "idAction", "===", "false", ")", "?", "0", ":", "$", "idAction", ";", "}", "$", "customValue", "=", "$", "this", "->", "getCustomFloatValue", "(", ")", ";", "if", "(", "$", "customValue", "!==", "false", "&&", "$", "customValue", "!==", "null", "&&", "$", "customValue", "!==", "''", ")", "{", "$", "visitAction", "[", "self", "::", "DB_COLUMN_CUSTOM_FLOAT", "]", "=", "Common", "::", "forceDotAsSeparatorForDecimalPoint", "(", "$", "customValue", ")", ";", "}", "$", "visitAction", "=", "array_merge", "(", "$", "visitAction", ",", "$", "this", "->", "customFields", ")", ";", "$", "this", "->", "idLinkVisitAction", "=", "$", "this", "->", "getModel", "(", ")", "->", "createAction", "(", "$", "visitAction", ")", ";", "$", "visitAction", "[", "'idlink_va'", "]", "=", "$", "this", "->", "idLinkVisitAction", ";", "Common", "::", "printDebug", "(", "\"Inserted new action:\"", ")", ";", "$", "visitActionDebug", "=", "$", "visitAction", ";", "$", "visitActionDebug", "[", "'idvisitor'", "]", "=", "bin2hex", "(", "$", "visitActionDebug", "[", "'idvisitor'", "]", ")", ";", "Common", "::", "printDebug", "(", "$", "visitActionDebug", ")", ";", "}" ]
Records in the DB the association between the visit and this action. @param int $idReferrerActionUrl is the ID of the last action done by the current visit. @param $idReferrerActionName @param Visitor $visitor
[ "Records", "in", "the", "DB", "the", "association", "between", "the", "visit", "and", "this", "action", "." ]
72df150735664275a60a7861e468c6ff3b152a14
https://github.com/matomo-org/matomo/blob/72df150735664275a60a7861e468c6ff3b152a14/core/Tracker/Action.php#L358-L410
210,196
matomo-org/matomo
core/View.php
View.setXFrameOptions
public function setXFrameOptions($option = 'deny') { if ($option === 'deny' || $option === 'sameorigin') { $this->xFrameOptions = $option; } if ($option == 'allow') { $this->xFrameOptions = null; } }
php
public function setXFrameOptions($option = 'deny') { if ($option === 'deny' || $option === 'sameorigin') { $this->xFrameOptions = $option; } if ($option == 'allow') { $this->xFrameOptions = null; } }
[ "public", "function", "setXFrameOptions", "(", "$", "option", "=", "'deny'", ")", "{", "if", "(", "$", "option", "===", "'deny'", "||", "$", "option", "===", "'sameorigin'", ")", "{", "$", "this", "->", "xFrameOptions", "=", "$", "option", ";", "}", "if", "(", "$", "option", "==", "'allow'", ")", "{", "$", "this", "->", "xFrameOptions", "=", "null", ";", "}", "}" ]
Set X-Frame-Options field in the HTTP response. The header is set just before rendering. _Note: setting this allows you to make sure the View **cannot** be embedded in iframes. Learn more [here](https://developer.mozilla.org/en-US/docs/HTTP/X-Frame-Options)._ @param string $option ('deny' or 'sameorigin')
[ "Set", "X", "-", "Frame", "-", "Options", "field", "in", "the", "HTTP", "response", ".", "The", "header", "is", "set", "just", "before", "rendering", "." ]
72df150735664275a60a7861e468c6ff3b152a14
https://github.com/matomo-org/matomo/blob/72df150735664275a60a7861e468c6ff3b152a14/core/View.php#L379-L388
210,197
matomo-org/matomo
core/View.php
View.addForm
public function addForm(QuickForm2 $form) { // assign array with form data $this->assign('form_data', $form->getFormData()); $this->assign('element_list', $form->getElementList()); }
php
public function addForm(QuickForm2 $form) { // assign array with form data $this->assign('form_data', $form->getFormData()); $this->assign('element_list', $form->getElementList()); }
[ "public", "function", "addForm", "(", "QuickForm2", "$", "form", ")", "{", "// assign array with form data", "$", "this", "->", "assign", "(", "'form_data'", ",", "$", "form", "->", "getFormData", "(", ")", ")", ";", "$", "this", "->", "assign", "(", "'element_list'", ",", "$", "form", "->", "getElementList", "(", ")", ")", ";", "}" ]
Add form to view @param QuickForm2 $form @ignore
[ "Add", "form", "to", "view" ]
72df150735664275a60a7861e468c6ff3b152a14
https://github.com/matomo-org/matomo/blob/72df150735664275a60a7861e468c6ff3b152a14/core/View.php#L396-L402
210,198
matomo-org/matomo
core/View.php
View.assign
public function assign($var, $value = null) { if (is_string($var)) { $this->$var = $value; } elseif (is_array($var)) { foreach ($var as $key => $value) { $this->$key = $value; } } }
php
public function assign($var, $value = null) { if (is_string($var)) { $this->$var = $value; } elseif (is_array($var)) { foreach ($var as $key => $value) { $this->$key = $value; } } }
[ "public", "function", "assign", "(", "$", "var", ",", "$", "value", "=", "null", ")", "{", "if", "(", "is_string", "(", "$", "var", ")", ")", "{", "$", "this", "->", "$", "var", "=", "$", "value", ";", "}", "elseif", "(", "is_array", "(", "$", "var", ")", ")", "{", "foreach", "(", "$", "var", "as", "$", "key", "=>", "$", "value", ")", "{", "$", "this", "->", "$", "key", "=", "$", "value", ";", "}", "}", "}" ]
Assign value to a variable for use in a template @param string|array $var @param mixed $value @ignore
[ "Assign", "value", "to", "a", "variable", "for", "use", "in", "a", "template" ]
72df150735664275a60a7861e468c6ff3b152a14
https://github.com/matomo-org/matomo/blob/72df150735664275a60a7861e468c6ff3b152a14/core/View.php#L410-L419
210,199
matomo-org/matomo
core/View.php
View.clearCompiledTemplates
public static function clearCompiledTemplates() { $twig = StaticContainer::get(Twig::class); $environment = $twig->getTwigEnvironment(); $environment->clearTemplateCache(); $cacheDirectory = $environment->getCache(); if (!empty($cacheDirectory) && is_dir($cacheDirectory) ) { $environment->clearCacheFiles(); } }
php
public static function clearCompiledTemplates() { $twig = StaticContainer::get(Twig::class); $environment = $twig->getTwigEnvironment(); $environment->clearTemplateCache(); $cacheDirectory = $environment->getCache(); if (!empty($cacheDirectory) && is_dir($cacheDirectory) ) { $environment->clearCacheFiles(); } }
[ "public", "static", "function", "clearCompiledTemplates", "(", ")", "{", "$", "twig", "=", "StaticContainer", "::", "get", "(", "Twig", "::", "class", ")", ";", "$", "environment", "=", "$", "twig", "->", "getTwigEnvironment", "(", ")", ";", "$", "environment", "->", "clearTemplateCache", "(", ")", ";", "$", "cacheDirectory", "=", "$", "environment", "->", "getCache", "(", ")", ";", "if", "(", "!", "empty", "(", "$", "cacheDirectory", ")", "&&", "is_dir", "(", "$", "cacheDirectory", ")", ")", "{", "$", "environment", "->", "clearCacheFiles", "(", ")", ";", "}", "}" ]
Clear compiled Twig templates @ignore
[ "Clear", "compiled", "Twig", "templates" ]
72df150735664275a60a7861e468c6ff3b152a14
https://github.com/matomo-org/matomo/blob/72df150735664275a60a7861e468c6ff3b152a14/core/View.php#L425-L437