作者:a4tunad
项目:piwi
/**
* Create a component instance that exists within a specific plugin. Uses the component's
* unqualified class name and expected base type.
*
* This method will only create a class if it is located within the component type's
* associated subdirectory.
*
* @param string $pluginName The name of the plugin the component is expected to belong to,
* eg, `'UserSettings'`.
* @param string $componentClassSimpleName The component's class name w/o namespace, eg,
* `"GetKeywords"`.
* @param string $componentTypeClass The fully qualified class name of the component type, eg,
* `"Piwik\Plugin\Report"`.
* @return mixed|null A new instance of the desired component or null if not found. If the
* plugin is not loaded or activated or the component is not located in
* in the sub-namespace specified by `$componentTypeClass::COMPONENT_SUBNAMESPACE`,
* this method will return null.
*/
public static function factory($pluginName, $componentClassSimpleName, $componentTypeClass)
{
if (empty($pluginName) || empty($componentClassSimpleName)) {
return null;
}
$pluginManager = PluginManager::getInstance();
try {
if (!$pluginManager->isPluginActivated($pluginName)) {
return null;
}
$plugin = $pluginManager->getLoadedPlugin($pluginName);
} catch (Exception $e) {
Log::debug($e);
return null;
}
$subnamespace = $componentTypeClass::COMPONENT_SUBNAMESPACE;
$desiredComponentClass = 'Piwik\\Plugins\\' . $pluginName . '\\' . $subnamespace . '\\' . $componentClassSimpleName;
$components = $plugin->findMultipleComponents($subnamespace, $componentTypeClass);
foreach ($components as $class) {
if ($class == $desiredComponentClass) {
return new $class();
}
}
return null;
}
作者:saadouu
项目:plugin-SiteMigratio
protected function execute(InputInterface $input, OutputInterface $output)
{
// Set memory limit to off
@ini_set('memory_limit', -1);
Piwik::doAsSuperUser(function () use($input, $output) {
$settings = new MigratorSettings();
$settings->idSite = $input->getArgument('idSite');
$settings->site = $this->getSite($settings->idSite);
$settings->dateFrom = $input->getOption('date-from') ? new \DateTime($input->getOption('date-from')) : null;
$settings->dateTo = $input->getOption('date-to') ? new \DateTime($input->getOption('date-to')) : null;
$settings->skipArchiveData = $input->getOption('skip-archive-data');
$settings->skipLogData = $input->getOption('skip-log-data');
$config = Db::getDatabaseConfig();
$startTime = microtime(true);
$this->createTargetDatabaseConfig($input, $output, $config);
$tmpConfig = $config;
$sourceDb = Db::get();
try {
$targetDb = @Db\Adapter::factory($config['adapter'], $tmpConfig);
} catch (\Exception $e) {
throw new \RuntimeException('Unable to connect to the target database: ' . $e->getMessage(), 0, $e);
}
$sourceDbHelper = new DBHelper($sourceDb, Db::getDatabaseConfig());
$migratorFacade = new Migrator($sourceDbHelper, new DBHelper($targetDb, $config), GCHelper::getInstance(), $settings, new ArchiveLister($sourceDbHelper));
$migratorFacade->migrate();
$endTime = microtime(true);
Log::debug(sprintf('Time taken: %01.2f sec', $endTime - $startTime));
Log::debug(sprintf('Peak memory usage: %01.2f MB', memory_get_peak_usage(true) / 1048576));
});
}
作者:bossrabbi
项目:piwi
private static function getErrorResponse(Exception $ex)
{
$debugTrace = $ex->getTraceAsString();
$message = $ex->getMessage();
if (!method_exists($ex, 'isHtmlMessage') || !$ex->isHtmlMessage()) {
$message = Common::sanitizeInputValue($message);
}
$logo = new CustomLogo();
$logoHeaderUrl = false;
$logoFaviconUrl = false;
try {
$logoHeaderUrl = $logo->getHeaderLogoUrl();
$logoFaviconUrl = $logo->getPathUserFavicon();
} catch (Exception $ex) {
Log::debug($ex);
}
$result = Piwik_GetErrorMessagePage($message, $debugTrace, true, true, $logoHeaderUrl, $logoFaviconUrl);
/**
* Triggered before a Piwik error page is displayed to the user.
*
* This event can be used to modify the content of the error page that is displayed when
* an exception is caught.
*
* @param string &$result The HTML of the error page.
* @param Exception $ex The Exception displayed in the error page.
*/
Piwik::postEvent('FrontController.modifyErrorPage', array(&$result, $ex));
return $result;
}
作者:bossrabbi
项目:piwi
/**
* Purges old data from the following tables:
* - log_visit
* - log_link_visit_action
* - log_conversion
* - log_conversion_item
* - log_action
*/
public function purgeData()
{
$maxIdVisit = $this->getDeleteIdVisitOffset();
// break if no ID was found (nothing to delete for given period)
if (empty($maxIdVisit)) {
return;
}
$logTables = self::getDeleteTableLogTables();
// delete data from log tables
$where = "WHERE idvisit <= ?";
foreach ($logTables as $logTable) {
// deleting from log_action must be handled differently, so we do it later
if ($logTable != Common::prefixTable('log_action')) {
Db::deleteAllRows($logTable, $where, "idvisit ASC", $this->maxRowsToDeletePerQuery, array($maxIdVisit));
}
}
// delete unused actions from the log_action table (but only if we can lock tables)
if (Db::isLockPrivilegeGranted()) {
$this->purgeUnusedLogActions();
} else {
$logMessage = get_class($this) . ": LOCK TABLES privilege not granted; skipping unused actions purge";
Log::warning($logMessage);
}
// optimize table overhead after deletion
Db::optimizeTables($logTables);
}
作者:TensorWrenchOS
项目:piwi
protected static function deleteArchivesWithPeriodRange(Date $date)
{
$numericTable = ArchiveTableCreator::getNumericTable($date);
$blobTable = ArchiveTableCreator::getBlobTable($date);
$yesterday = Date::factory('yesterday')->getDateTime();
Log::debug("Purging Custom Range archives: done [ purged archives older than %s from %s / blob ]", $yesterday, $numericTable);
self::getModel()->deleteArchivesWithPeriodRange($numericTable, $blobTable, Piwik::$idPeriods['range'], $yesterday);
}
作者:diosmosi
项目:piwi
public function updateTracker()
{
try {
$trackerUpdater = new TrackerUpdater();
$trackerUpdater->update();
} catch (\Exception $e) {
Log::error('There was an error while updating the javascript tracker: ' . $e->getMessage());
}
}
作者:ruchitram
项目:plugin-QueuedTrackin
public function testConnection()
{
try {
$this->connectIfNeeded();
return 'TEST' === $this->redis->echo('TEST');
} catch (\Exception $e) {
Log::debug($e->getMessage());
}
return false;
}
作者:mgou-ne
项目:piwi
public static function tearDownAfterClass()
{
Log::debug("Tearing down " . get_called_class());
if (!isset(static::$fixture)) {
$fixture = new Fixture();
} else {
$fixture = static::$fixture;
}
$fixture->performTearDown();
}
作者:carriercom
项目:piwi
public function logVariables()
{
try {
if (isset($_SERVER['QUERY_STRING'])) {
\Piwik\Log::verbose("Test Environment Variables for (%s):\n%s", $_SERVER['QUERY_STRING'], print_r($this->behaviorOverrideProperties, true));
}
} catch (Exception $ex) {
// ignore
}
}
作者:FluentDevelopmen
项目:piwi
/**
* @test
*/
public function it_should_add_severity_for_errors()
{
$processor = new ExceptionToTextProcessor();
Log::$debugBacktraceForTests = '[stack trace]';
$exception = new \ErrorException('Hello world', 0, 1, 'file.php', 123);
$record = array('context' => array('exception' => $exception));
$result = $processor($record);
$expected = array('message' => "file.php(123): Error - Hello world\n[stack trace]", 'context' => array('exception' => $exception));
$this->assertEquals($expected, $result);
}
作者:TensorWrenchOS
项目:piwi
private function addCommandIfExists($command)
{
if (!class_exists($command)) {
Log::warning(sprintf('Cannot add command %s, class does not exist', $command));
} elseif (!is_subclass_of($command, 'Piwik\\Plugin\\ConsoleCommand')) {
Log::warning(sprintf('Cannot add command %s, class does not extend Piwik\\Plugin\\ConsoleCommand', $command));
} else {
$this->add(new $command());
}
}
作者:saadouu
项目:plugin-SiteMigratio
public function migrate($siteId, \DateTime $from = null, \DateTime $to = null)
{
$archives = $this->archiveLister->getArchiveList($from, $to);
foreach ($archives as $archiveDate) {
Log::debug('Migrating archive ' . $archiveDate);
$this->migrateArchive($archiveDate, 'archive_numeric_' . $archiveDate, $siteId);
try {
$this->migrateArchive($archiveDate, 'archive_blob_' . $archiveDate, $siteId);
} catch (\Exception $e) {
// blob tables can be missing
}
}
}
作者:a4tunad
项目:piwi
protected static function deleteArchivesWithPeriodRange(Date $date)
{
$query = "DELETE FROM %s WHERE period = ? AND ts_archived < ?";
$yesterday = Date::factory('yesterday')->getDateTime();
$bind = array(Piwik::$idPeriods['range'], $yesterday);
$numericTable = ArchiveTableCreator::getNumericTable($date);
Db::query(sprintf($query, $numericTable), $bind);
Log::debug("Purging Custom Range archives: done [ purged archives older than %s from %s / blob ]", $yesterday, $numericTable);
try {
Db::query(sprintf($query, ArchiveTableCreator::getBlobTable($date)), $bind);
} catch (Exception $e) {
// Individual blob tables could be missing
}
}
作者:KiwiJuice
项目:handball-dacha
public function run()
{
$console = new Application();
$commands = $this->getAvailableCommands();
foreach ($commands as $command) {
if (!class_exists($command)) {
Log::warning(sprintf('Cannot add command %s, class does not exist', $command));
} elseif (!is_subclass_of($command, 'Piwik\\Plugin\\ConsoleCommand')) {
Log::warning(sprintf('Cannot add command %s, class does not extend Piwik\\Plugin\\ConsoleCommand', $command));
} else {
$console->add(new $command());
}
}
$console->run();
}
作者:brienomatt
项目:elmsl
protected function execute(InputInterface $input, OutputInterface $output)
{
$url = $input->getOption('url');
if ($input->getOption('piwik-domain') && !$url) {
$_SERVER['argv'][] = '--url=' . $input->getOption('piwik-domain');
}
if (is_string($url) && $url && in_array($url, array('http://', 'https://'))) {
// see http://dev.piwik.org/trac/ticket/5180 and http://forum.piwik.org/read.php?2,115274
throw new \InvalidArgumentException('No valid URL given. If you have specified a valid URL try --piwik-domain instead of --url');
}
if ($input->getOption('verbose')) {
Log::getInstance()->setLogLevel(Log::VERBOSE);
}
include PIWIK_INCLUDE_PATH . '/misc/cron/archive.php';
}
作者:FluentDevelopmen
项目:piwi
private function addCommandIfExists($command)
{
if (!class_exists($command)) {
Log::warning(sprintf('Cannot add command %s, class does not exist', $command));
} elseif (!is_subclass_of($command, 'Piwik\\Plugin\\ConsoleCommand')) {
Log::warning(sprintf('Cannot add command %s, class does not extend Piwik\\Plugin\\ConsoleCommand', $command));
} else {
/** @var Command $commandInstance */
$commandInstance = new $command();
// do not add the command if it already exists; this way we can add the command ourselves in tests
if (!$this->has($commandInstance->getName())) {
$this->add($commandInstance);
}
}
}
作者:diosmosi
项目:piwi
/**
* Purges old data from the following tables:
* - log_visit
* - log_link_visit_action
* - log_conversion
* - log_conversion_item
* - log_action
*
* @param int $deleteLogsOlderThan The number of days after which log entires are considered old.
* Visits and related data whose age is greater than this number
* will be purged.
*/
public function purgeData($deleteLogsOlderThan)
{
$dateUpperLimit = Date::factory("today")->subDay($deleteLogsOlderThan);
$this->logDeleter->deleteVisitsFor($start = null, $dateUpperLimit->getDatetime());
$logTables = self::getDeleteTableLogTables();
// delete unused actions from the log_action table (but only if we can lock tables)
if (Db::isLockPrivilegeGranted()) {
$this->rawLogDao->deleteUnusedLogActions();
} else {
$logMessage = get_class($this) . ": LOCK TABLES privilege not granted; skipping unused actions purge";
Log::warning($logMessage);
}
// optimize table overhead after deletion
Db::optimizeTables($logTables);
}
作者:ruchitram
项目:plugin-QueuedTrackin
protected function execute(InputInterface $input, OutputInterface $output)
{
$systemCheck = new SystemCheck();
$systemCheck->checkRedisIsInstalled();
$trackerEnvironment = new Environment('tracker');
$trackerEnvironment->init();
Log::unsetInstance();
$trackerEnvironment->getContainer()->get('Piwik\\Access')->setSuperUserAccess(false);
$trackerEnvironment->getContainer()->get('Piwik\\Plugin\\Manager')->setTrackerPluginsNotToLoad(array('Provider'));
Tracker::loadTrackerEnvironment();
if (OutputInterface::VERBOSITY_VERY_VERBOSE <= $output->getVerbosity()) {
$GLOBALS['PIWIK_TRACKER_DEBUG'] = true;
}
$backend = Queue\Factory::makeBackend();
$queueManager = Queue\Factory::makeQueueManager($backend);
if (!$queueManager->canAcquireMoreLocks()) {
$trackerEnvironment->destroy();
$this->writeSuccessMessage($output, array("Nothing to proccess. Already max number of workers in process."));
return;
}
$shouldProcess = false;
foreach ($queueManager->getAllQueues() as $queue) {
if ($queue->shouldProcess()) {
$shouldProcess = true;
break;
}
}
if (!$shouldProcess) {
$trackerEnvironment->destroy();
$this->writeSuccessMessage($output, array("No queue currently needs processing"));
return;
}
$output->writeln("<info>Starting to process request sets, this can take a while</info>");
register_shutdown_function(function () use($queueManager) {
$queueManager->unlock();
});
$startTime = microtime(true);
$processor = new Processor($queueManager);
$processor->setNumberOfMaxBatchesToProcess(1000);
$tracker = $processor->process();
$neededTime = microtime(true) - $startTime;
$numRequestsTracked = $tracker->getCountOfLoggedRequests();
$requestsPerSecond = $this->getNumberOfRequestsPerSecond($numRequestsTracked, $neededTime);
Piwik::postEvent('Tracker.end');
$trackerEnvironment->destroy();
$this->writeSuccessMessage($output, array(sprintf('This worker finished queue processing with %sreq/s (%s requests in %02.2f seconds)', $requestsPerSecond, $numRequestsTracked, $neededTime)));
}
作者:FluentDevelopmen
项目:piwi
private static function getErrorResponse(Exception $ex)
{
$debugTrace = $ex->getTraceAsString();
$message = $ex->getMessage();
$isHtmlMessage = method_exists($ex, 'isHtmlMessage') && $ex->isHtmlMessage();
if (!$isHtmlMessage && Request::isApiRequest($_GET)) {
$outputFormat = strtolower(Common::getRequestVar('format', 'xml', 'string', $_GET + $_POST));
$response = new ResponseBuilder($outputFormat);
return $response->getResponseException($ex);
} elseif (!$isHtmlMessage) {
$message = Common::sanitizeInputValue($message);
}
$logo = new CustomLogo();
$logoHeaderUrl = false;
$logoFaviconUrl = false;
try {
$logoHeaderUrl = $logo->getHeaderLogoUrl();
$logoFaviconUrl = $logo->getPathUserFavicon();
} catch (Exception $ex) {
try {
Log::debug($ex);
} catch (\Exception $otherEx) {
// DI container may not be setup at this point
}
}
$result = Piwik_GetErrorMessagePage($message, $debugTrace, true, true, $logoHeaderUrl, $logoFaviconUrl);
try {
/**
* Triggered before a Piwik error page is displayed to the user.
*
* This event can be used to modify the content of the error page that is displayed when
* an exception is caught.
*
* @param string &$result The HTML of the error page.
* @param Exception $ex The Exception displayed in the error page.
*/
Piwik::postEvent('FrontController.modifyErrorPage', array(&$result, $ex));
} catch (ContainerDoesNotExistException $ex) {
// this can happen when an error occurs before the Piwik environment is created
}
return $result;
}
作者:a4tunad
项目:piwi
protected function execute(InputInterface $input, OutputInterface $output)
{
$url = $input->getOption('url') ?: $input->getOption('piwik-domain');
if (empty($url)) {
throw new \InvalidArgumentException("The --url argument is not set. It should be set to your Piwik URL, for example: --url=http://example.org/piwik/.");
}
if (is_string($url) && $url && in_array($url, array('http://', 'https://'))) {
// see https://github.com/piwik/piwik/issues/5180 and http://forum.piwik.org/read.php?2,115274
throw new \InvalidArgumentException('No valid URL given. If you have specified a valid URL try --piwik-domain instead of --url');
}
if ($input->getOption('verbose')) {
Log::getInstance()->setLogLevel(Log::VERBOSE);
}
$archiver = $this->makeArchiver($url, $input);
try {
$archiver->main();
} catch (Exception $e) {
$archiver->logFatalError($e->getMessage());
}
}