Exemplo n.º 1
0
 public static function setUpBeforeClass()
 {
     $dbName = false;
     if (!empty($GLOBALS['PIWIK_BENCHMARK_DATABASE'])) {
         $dbName = $GLOBALS['PIWIK_BENCHMARK_DATABASE'];
     }
     // connect to database
     self::createTestConfig();
     self::connectWithoutDatabase();
     // create specified fixture (global var not set, use default no-data fixture (see end of this file))
     if (empty($GLOBALS['PIWIK_BENCHMARK_FIXTURE'])) {
         $fixtureName = 'Piwik_Test_Fixture_EmptyOneSite';
     } else {
         $fixtureName = 'Piwik_Test_Fixture_' . $GLOBALS['PIWIK_BENCHMARK_FIXTURE'];
     }
     self::$fixture = new $fixtureName();
     // figure out if the desired fixture has already been setup, and if not empty the database
     $installedFixture = false;
     try {
         if (isset(self::$fixture->tablesPrefix)) {
             Config::getInstance()->database['tables_prefix'] = self::$fixture->tablesPrefix;
         }
         Db::query("USE " . $dbName);
         $installedFixture = \Piwik\Option::get('benchmark_fixture_name');
     } catch (Exception $ex) {
         // ignore
     }
     $createEmptyDatabase = $fixtureName != $installedFixture;
     parent::_setUpBeforeClass($dbName, $createEmptyDatabase);
     // if we created an empty database, setup the fixture
     if ($createEmptyDatabase) {
         self::$fixture->setUp();
         \Piwik\Option::set('benchmark_fixture_name', $fixtureName);
     }
 }
 public static function setUpBeforeClass()
 {
     parent::setUpBeforeClass();
     // note: not sure why I have to manually install plugin
     \Piwik\Plugin\Manager::getInstance()->loadPlugin('CustomAlerts')->install();
     $result = Fixture::updateDatabase();
     if ($result === false) {
         throw new \Exception("Failed to update pre-2.0 database (nothing to update).");
     }
     // truncate log tables so old data won't be re-archived
     foreach (array('log_visit', 'log_link_visit_action', 'log_conversion', 'log_conversion_item') as $table) {
         Db::query("TRUNCATE TABLE " . Common::prefixTable($table));
     }
     // add two visits from same visitor on dec. 29
     $t = Fixture::getTracker(1, '2012-12-29 01:01:30', $defaultInit = true);
     $t->setUrl('http://site.com/index.htm');
     $t->setIp('136.5.3.2');
     Fixture::checkResponse($t->doTrackPageView('incredible title!'));
     $t->setForceVisitDateTime('2012-12-29 03:01:30');
     $t->setUrl('http://site.com/other/index.htm');
     $t->DEBUG_APPEND_URL = '&_idvc=2';
     // make sure visit is marked as returning
     Fixture::checkResponse($t->doTrackPageView('other incredible title!'));
     // launch archiving
     VisitFrequencyApi::getInstance()->get(1, 'year', '2012-12-29');
 }
Exemplo n.º 3
0
 private function insertInto($table, $row)
 {
     $columns = implode(', ', array_keys($row));
     $columnsPlaceholders = Common::getSqlStringFieldsArray($row);
     $values = array_values($row);
     Db::query("INSERT INTO " . Common::prefixTable($table) . " ({$columns}) VALUES ({$columnsPlaceholders})", $values);
 }
Exemplo n.º 4
0
 /**
  * Sets the language for the user
  *
  * @param string $login
  * @param string $languageCode
  * @return bool
  */
 public function setLanguageForUser($login, $languageCode)
 {
     $query = 'INSERT INTO ' . $this->table . ' (login, language) VALUES (?,?) ON DUPLICATE KEY UPDATE language=?';
     $bind = array($login, $languageCode, $languageCode);
     Db::query($query, $bind);
     return true;
 }
 public static function update($idvisitor, $name = false, $email = false, $phone = false, $comments = false)
 {
     if ($name == false && $email == false && $phone == false && $comments == false) {
         return false;
     }
     $buildQuery = "";
     $argSet = array();
     $argOnUpdate = array();
     $argSet[] = @Common::hex2bin($idvisitor);
     if ($name) {
         $argSet[] = $name;
         $argOnUpdate[] = $name;
         $buildQuery .= " name = ?,";
     }
     if ($email) {
         $argSet[] = $email;
         $argOnUpdate[] = $email;
         $buildQuery .= " email = ?,";
     }
     if ($phone) {
         $argSet[] = $phone;
         $argOnUpdate[] = $phone;
         $buildQuery .= " phone = ?,";
     }
     if ($comments) {
         $argSet[] = $comments;
         $argOnUpdate[] = $comments;
         $buildQuery .= " comments = ?,";
     }
     $buildQuery = trim(substr_replace($buildQuery, "", -1));
     $arguments = array_merge($argSet, $argOnUpdate);
     Db::query("INSERT INTO " . Common::prefixTable('chat_personnal_informations') . " SET idvisitor = ?, {$buildQuery} ON DUPLICATE KEY UPDATE {$buildQuery}", $arguments);
     return true;
 }
Exemplo n.º 6
0
 /**
  * Sets whether the given user wants to use 12 hout clock
  *
  * @param string $login
  * @param string $use12HourClock
  * @return bool
  */
 public function set12HourClock($login, $use12HourClock)
 {
     $query = 'INSERT INTO ' . $this->table . ' (login, use_12_hour_clock) VALUES (?,?) ON DUPLICATE KEY UPDATE use_12_hour_clock=?';
     $bind = array($login, $use12HourClock, $use12HourClock);
     Db::query($query, $bind);
     return true;
 }
Exemplo n.º 7
0
 protected function write(array $record)
 {
     $sql = sprintf('INSERT INTO %s (tag, timestamp, level, message) VALUES (?, ?, ?, ?)', Common::prefixTable('logger_message'));
     $queryLog = Db::isQueryLogEnabled();
     Db::enableQueryLog(false);
     Db::query($sql, array($record['extra']['class'], $record['datetime']->format('Y-m-d H:i:s'), $record['level_name'], trim($record['formatted'])));
     Db::enableQueryLog($queryLog);
 }
 public static function setLastSent($idsite, $idvisitor, $microtime)
 {
     foreach (ChatCommon::getUsersBySite($idsite) as $user) {
         $arguments = array($user['login'], @Common::hex2bin($idvisitor), $microtime, $microtime);
         Db::query("INSERT INTO " . Common::prefixTable('chat_history_admin') . " SET login = ?, idvisitor = ?, lastsent = ? ON DUPLICATE KEY UPDATE lastsent = ?", $arguments);
     }
     return true;
 }
 public function test_getSitesAndDatesOfRowsUsingDuplicates_ReturnsTheServerTimeAndIdSite_OfRowsUsingSpecifiedActionIds()
 {
     $row = array('idsite' => 3, 'idvisitor' => pack("H*", DuplicateActions::DUMMY_IDVISITOR), 'server_time' => '2012-02-13 00:00:00', 'idvisit' => 5, 'idorder' => 6, 'price' => 15, 'quantity' => 21, 'deleted' => 1, 'idaction_sku' => 3, 'idaction_name' => 3, 'idaction_category' => 12, 'idaction_category2' => 3, 'idaction_category3' => 3, 'idaction_category4' => 3, 'idaction_category5' => 3);
     Db::query("INSERT INTO " . Common::prefixTable('log_conversion_item') . " (" . implode(", ", array_keys($row)) . ") VALUES ('" . implode("', '", array_values($row)) . "')");
     $expectedResult = array(array('idsite' => 1, 'server_time' => '2012-02-01'), array('idsite' => 3, 'server_time' => '2012-02-13'));
     $actualResult = $this->duplicateActionRemover->getSitesAndDatesOfRowsUsingDuplicates('log_conversion_item', array(4, 6, 12));
     $this->assertEquals($expectedResult, $actualResult);
 }
Exemplo n.º 10
0
 /**
  * Performs a batch insert into a specific table by iterating through the data
  *
  * NOTE: you should use tableInsertBatch() which will fallback to this function if LOAD DATA INFILE not available
  *
  * @param string $tableName PREFIXED table name! you must call Common::prefixTable() before passing the table name
  * @param array $fields array of unquoted field names
  * @param array $values array of data to be inserted
  * @param bool $ignoreWhenDuplicate Ignore new rows that contain unique key values that duplicate old rows
  */
 public static function tableInsertBatchIterate($tableName, $fields, $values, $ignoreWhenDuplicate = true)
 {
     $fieldList = '(' . join(',', $fields) . ')';
     $ignore = $ignoreWhenDuplicate ? 'IGNORE' : '';
     foreach ($values as $row) {
         $query = "INSERT {$ignore}\n\t\t\t\t\tINTO " . $tableName . "\n\t\t\t\t\t{$fieldList}\n\t\t\t\t\tVALUES (" . Common::getSqlStringFieldsArray($row) . ")";
         Db::query($query, $row);
     }
 }
Exemplo n.º 11
0
 /**
  * Removes a list of actions from the log_action table by ID.
  *
  * @param int[] $idActions
  */
 public function delete($idActions)
 {
     foreach ($idActions as &$id) {
         $id = (int) $id;
     }
     $table = Common::prefixTable('log_action');
     $sql = "DELETE FROM {$table} WHERE idaction IN (" . implode(",", $idActions) . ")";
     Db::query($sql);
 }
Exemplo n.º 12
0
 /**
  * Saves (persists) the current setting values in the database.
  */
 public function save()
 {
     $table = $this->getTableName();
     foreach ($this->toBeDeleted as $name => $delete) {
         if ($delete) {
             $sql = "DELETE FROM {$table} WHERE `idsite` = ? and `setting_name` = ?";
             $bind = array($this->idSite, $name);
             $this->db->query($sql, $bind);
         }
     }
     $this->toBeDeleted = array();
     foreach ($this->settingsValues as $name => $value) {
         $value = serialize($value);
         $sql = "INSERT INTO {$table} (`idsite`, `setting_name`, `setting_value`) VALUES (?, ?, ?) ON DUPLICATE KEY UPDATE `setting_value` = ?";
         $bind = array($this->idSite, $name, $value, $value);
         $this->db->query($sql, $bind);
     }
 }
 public static function setUpBeforeClass()
 {
     parent::setUpBeforeClass();
     // add duplicates for every action
     $table = Common::prefixTable('log_action');
     foreach (Db::fetchAll("SELECT * FROM {$table}") as $row) {
         $insertSql = "INSERT INTO {$table} (name, type, hash, url_prefix)\n                               VALUES (?, ?, CRC32(?), ?)";
         Db::query($insertSql, array($row['name'], $row['type'], $row['name'], $row['url_prefix']));
     }
 }
Exemplo n.º 14
0
 protected static function deleteArchiveIds(Date $date, $idArchivesToDelete)
 {
     $batches = array_chunk($idArchivesToDelete, 1000);
     foreach ($batches as $idsToDelete) {
         $query = "DELETE FROM %s WHERE idarchive IN (" . implode(',', $idsToDelete) . ")";
         Db::query(sprintf($query, ArchiveTableCreator::getNumericTable($date)));
         try {
             Db::query(sprintf($query, ArchiveTableCreator::getBlobTable($date)));
         } catch (Exception $e) {
             // Individual blob tables could be missing
         }
     }
 }
Exemplo n.º 15
0
 /**
  * @group Core
  */
 public function testGetOption()
 {
     // empty table, expect false (i.e., not found)
     $this->assertFalse(Option::get('anonymous_defaultReport'));
     // populate table, expect '1' (i.e., found)
     Db::query("INSERT INTO `" . Common::prefixTable('option') . "` VALUES ('anonymous_defaultReport', '1',true)");
     $this->assertSame('1', Option::get('anonymous_defaultReport'));
     // delete row (bypassing API), expect '1' (i.e., from cache)
     Db::query("DELETE FROM `" . Common::prefixTable('option') . "` WHERE option_name = ?", array('anonymous_defaultReport'));
     $this->assertSame('1', Option::get('anonymous_defaultReport'));
     // force cache reload, expect false (i.e., not found)
     Option::clearCache();
     $this->assertFalse(Option::get('anonymous_defaultReport'));
 }
Exemplo n.º 16
0
 static function update()
 {
     try {
         $dashboards = Db::fetchAll('SELECT * FROM `' . Common::prefixTable('user_dashboard') . '`');
         foreach ($dashboards as $dashboard) {
             $idDashboard = $dashboard['iddashboard'];
             $login = $dashboard['login'];
             $layout = $dashboard['layout'];
             $layout = html_entity_decode($layout);
             $layout = str_replace("\\\"", "\"", $layout);
             Db::query('UPDATE `' . Common::prefixTable('user_dashboard') . '` SET layout = ? WHERE iddashboard = ? AND login = ?', array($layout, $idDashboard, $login));
         }
         Updater::updateDatabase(__FILE__, self::getSql());
     } catch (\Exception $e) {
     }
 }
 public function setUp()
 {
     parent::setUp();
     $tablesToUpdate = array('log_visit', 'log_conversion');
     $columnsToUpdate = array('location_country' => '"xx"', 'location_region' => 'NULL', 'location_city' => 'NULL', 'location_latitude' => 'NULL', 'location_longitude' => 'NULL');
     foreach ($tablesToUpdate as $table) {
         $sql = "UPDATE `" . Common::prefixTable($table) . "` SET ";
         $sets = array();
         foreach ($columnsToUpdate as $column => $defaultValue) {
             $sets[] = $column . ' = ' . $defaultValue;
         }
         $sql .= implode(', ', $sets);
         Db::query($sql);
     }
     self::$fixture->setLocationProvider('GeoIPCity.dat');
 }
Exemplo n.º 18
0
 public function doUpdate(Updater $updater)
 {
     try {
         $dashboards = Db::fetchAll('SELECT * FROM `' . Common::prefixTable('user_dashboard') . '`');
         foreach ($dashboards as $dashboard) {
             $idDashboard = $dashboard['iddashboard'];
             $login = $dashboard['login'];
             $layout = $dashboard['layout'];
             $layout = html_entity_decode($layout);
             $layout = str_replace("\\\"", "\"", $layout);
             Db::query('UPDATE `' . Common::prefixTable('user_dashboard') . '` SET layout = ? WHERE iddashboard = ? AND login = ?', array($layout, $idDashboard, $login));
         }
         $updater->executeMigrationQueries(__FILE__, $this->getMigrationQueries($updater));
     } catch (\Exception $e) {
     }
 }
Exemplo n.º 19
0
 private static function insertRowData($unprefixedTable, $rows)
 {
     $table = Common::prefixTable($unprefixedTable);
     foreach ($rows as $row) {
         if ($unprefixedTable == 'log_action') {
             $row['hash'] = crc32($row['name']);
         }
         if (isset($row['idvisitor'])) {
             $row['idvisitor'] = pack("H*", $row['idvisitor']);
         }
         $placeholders = array_map(function () {
             return "?";
         }, $row);
         $sql = "INSERT INTO {$table} (" . implode(',', array_keys($row)) . ") VALUES (" . implode(',', $placeholders) . ")";
         Db::query($sql, array_values($row));
     }
 }
 public static function setUpBeforeClass()
 {
     parent::setUpBeforeClass();
     // note: not sure why I have to manually install plugin
     \Piwik\Plugin\Manager::getInstance()->loadPlugin('CustomAlerts')->install();
     $result = Fixture::updateDatabase();
     if ($result === false) {
         throw new \Exception("Failed to update pre-2.0 database (nothing to update).");
     }
     // truncate log tables so old data won't be re-archived
     foreach (array('log_visit', 'log_link_visit_action', 'log_conversion', 'log_conversion_item') as $table) {
         Db::query("TRUNCATE TABLE " . Common::prefixTable($table));
     }
     self::trackTwoVisitsOnSameDay();
     // launch archiving
     VisitFrequencyApi::getInstance()->get(1, 'year', '2012-12-29');
 }
Exemplo n.º 21
0
 public function doUpdate(Updater $updater)
 {
     $updater->executeMigrations(__FILE__, $this->getMigrations($updater));
     if (!\Piwik\Plugin\Manager::getInstance()->isPluginLoaded('ScheduledReports')) {
         return;
     }
     try {
         // Common::prefixTable('pdf') has been heavily refactored to be more generic
         // The following actions are taken in this update script :
         // - create the new generic report table Common::prefixTable('report')
         // - migrate previous reports, if any, from Common::prefixTable('pdf') to Common::prefixTable('report')
         // - delete Common::prefixTable('pdf')
         $reports = Db::fetchAll('SELECT * FROM `' . Common::prefixTable('pdf') . '`');
         foreach ($reports as $report) {
             $idreport = $report['idreport'];
             $idsite = $report['idsite'];
             $login = $report['login'];
             $description = $report['description'];
             $period = $report['period'];
             $format = $report['format'];
             $display_format = $report['display_format'];
             $email_me = $report['email_me'];
             $additional_emails = $report['additional_emails'];
             $reports = $report['reports'];
             $ts_created = $report['ts_created'];
             $ts_last_sent = $report['ts_last_sent'];
             $deleted = $report['deleted'];
             $parameters = array();
             if (!is_null($additional_emails)) {
                 $parameters[ScheduledReports::ADDITIONAL_EMAILS_PARAMETER] = preg_split('/,/', $additional_emails);
             }
             $parameters[ScheduledReports::EMAIL_ME_PARAMETER] = is_null($email_me) ? ScheduledReports::EMAIL_ME_PARAMETER_DEFAULT_VALUE : (bool) $email_me;
             $parameters[ScheduledReports::DISPLAY_FORMAT_PARAMETER] = $display_format;
             Db::query('INSERT INTO `' . Common::prefixTable('report') . '` SET
                 idreport = ?, idsite = ?, login = ?, description = ?, period = ?,
                 type = ?, format = ?, reports = ?, parameters = ?, ts_created = ?,
                 ts_last_sent = ?, deleted = ?', array($idreport, $idsite, $login, $description, is_null($period) ? ScheduledReports::DEFAULT_PERIOD : $period, ScheduledReports::EMAIL_TYPE, is_null($format) ? ScheduledReports::DEFAULT_REPORT_FORMAT : $format, json_encode(preg_split('/,/', $reports)), json_encode($parameters), $ts_created, $ts_last_sent, $deleted));
         }
         $updater->executeMigration(__FILE__, $this->migration->db->dropTable('pdf'));
     } catch (\Exception $e) {
     }
 }
 public static function setUpBeforeClass()
 {
     parent::setUpBeforeClass();
     self::updateDatabase();
     // truncate log tables so old data won't be re-archived
     foreach (array('log_visit', 'log_link_visit_action', 'log_conversion', 'log_conversion_item') as $table) {
         Db::query("TRUNCATE TABLE " . Common::prefixTable($table));
     }
     // add two visits from same visitor on dec. 29
     $t = Fixture::getTracker(1, '2012-12-29 01:01:30', $defaultInit = true);
     $t->setUrl('http://site.com/index.htm');
     $t->setIp('136.5.3.2');
     Fixture::checkResponse($t->doTrackPageView('incredible title!'));
     $t->setForceVisitDateTime('2012-12-29 03:01:30');
     $t->setUrl('http://site.com/other/index.htm');
     $t->DEBUG_APPEND_URL = '&_idvc=2';
     // make sure visit is marked as returning
     Fixture::checkResponse($t->doTrackPageView('other incredible title!'));
     // launch archiving
     VisitFrequencyApi::getInstance()->get(1, 'year', '2012-12-29');
 }
Exemplo n.º 23
0
 public function sendMessage($content, $fromAdmin = false, $idAutoMsg = false)
 {
     $hexVisitorId = Common::convertVisitorIdToBin($this->idvisitor);
     $sanitizeContent = Common::sanitizeInputValues($content);
     $additionnalParams = "";
     $microtime = microtime(true);
     $arguments = array($this->idsite, $hexVisitorId, $sanitizeContent, $microtime);
     if ($idAutoMsg) {
         $additionnalParams .= ", idautomsg = ?";
         $arguments[] = $idAutoMsg;
     }
     if ($fromAdmin) {
         $additionnalParams .= ", answerfrom = ?";
         $arguments[] = $fromAdmin;
     }
     $queryResult = Db::query("INSERT INTO " . Common::prefixTable('chat') . " SET idsite = ?, idvisitor = ?, content = ?, microtime = ?{$additionnalParams}", $arguments);
     if (!$fromAdmin) {
         ChatAcknowledgment::setLastSent($this->idsite, $this->idvisitor, $microtime);
         //ChatMail::sendNotificationToAdmin($this->idsite, $this->idvisitor, $sanitizeContent);
     }
     $insertedRow = Db::fetchRow("SELECT idmessage,microtime FROM " . Common::prefixTable('chat') . " WHERE idvisitor = ? AND microtime = ?", array($hexVisitorId, $microtime));
     return $insertedRow;
 }
Exemplo n.º 24
0
 private function deleteUnusedActions()
 {
     list($logActionTable, $tempTableName) = Common::prefixTables("log_action", self::TEMP_TABLE_NAME);
     $deleteSql = "DELETE LOW_PRIORITY QUICK IGNORE {$logActionTable}\n\t\t\t\t\t\tFROM {$logActionTable}\n\t\t\t\t   LEFT JOIN {$tempTableName} tmp ON tmp.idaction = {$logActionTable}.idaction\n\t\t\t\t\t   WHERE tmp.idaction IS NULL";
     Db::query($deleteSql);
 }
Exemplo n.º 25
0
 public function insertRecord($tableName, $fields, $record, $name, $value)
 {
     // duplicate idarchives are Ignored, see https://github.com/piwik/piwik/issues/987
     $query = "INSERT IGNORE INTO " . $tableName . " (" . implode(", ", $fields) . ")\n                  VALUES (?,?,?,?,?,?,?,?)";
     $bindSql = $record;
     $bindSql[] = $name;
     $bindSql[] = $value;
     Db::query($query, $bindSql);
     return true;
 }
Exemplo n.º 26
0
 /**
  * Drops all archive tables.
  */
 public static function deleteArchiveTables()
 {
     foreach (ArchiveTableCreator::getTablesArchivesInstalled() as $table) {
         Log::debug("Dropping table {$table}");
         Db::query("DROP TABLE IF EXISTS `{$table}`");
     }
     ArchiveTableCreator::refreshTableList($forceReload = true);
 }
Exemplo n.º 27
0
 /**
  * When tracking data in the past (using Tracking API), this function
  * can be used to invalidate reports for the idSites and dates where new data
  * was added.
  * DEV: If you call this API, the UI should display the data correctly, but will process
  *      in real time, which could be very slow after large data imports.
  *      After calling this function via REST, you can manually force all data
  *      to be reprocessed by visiting the script as the Super User:
  *      http://example.net/piwik/misc/cron/archive.php?token_auth=$SUPER_USER_TOKEN_AUTH_HERE
  * REQUIREMENTS: On large piwik setups, you will need in PHP configuration: max_execution_time = 0
  *    We recommend to use an hourly schedule of the script.
  *    More information: http://piwik.org/setup-auto-archiving/
  *
  * @param string $idSites Comma separated list of idSite that have had data imported for the specified dates
  * @param string $dates Comma separated list of dates to invalidate for all these websites
  * @throws Exception
  * @return array
  */
 public function invalidateArchivedReports($idSites, $dates)
 {
     $idSites = Site::getIdSitesFromIdSitesString($idSites);
     if (empty($idSites)) {
         throw new Exception("Specify a value for &idSites= as a comma separated list of website IDs, for which your token_auth has 'admin' permission");
     }
     Piwik::checkUserHasAdminAccess($idSites);
     // Ensure the specified dates are valid
     $toInvalidate = $invalidDates = array();
     $dates = explode(',', trim($dates));
     $dates = array_unique($dates);
     foreach ($dates as $theDate) {
         $theDate = trim($theDate);
         try {
             $date = Date::factory($theDate);
         } catch (Exception $e) {
             $invalidDates[] = $theDate;
             continue;
         }
         if ($date->toString() == $theDate) {
             $toInvalidate[] = $date;
         } else {
             $invalidDates[] = $theDate;
         }
     }
     // If using the feature "Delete logs older than N days"...
     $purgeDataSettings = PrivacyManager::getPurgeDataSettings();
     $logsAreDeletedBeforeThisDate = $purgeDataSettings['delete_logs_schedule_lowest_interval'];
     $logsDeleteEnabled = $purgeDataSettings['delete_logs_enable'];
     $minimumDateWithLogs = false;
     if ($logsDeleteEnabled && $logsAreDeletedBeforeThisDate) {
         $minimumDateWithLogs = Date::factory('today')->subDay($logsAreDeletedBeforeThisDate);
     }
     // Given the list of dates, process which tables they should be deleted from
     $minDate = false;
     $warningDates = $processedDates = array();
     /* @var $date Date */
     foreach ($toInvalidate as $date) {
         // we should only delete reports for dates that are more recent than N days
         if ($minimumDateWithLogs && $date->isEarlier($minimumDateWithLogs)) {
             $warningDates[] = $date->toString();
         } else {
             $processedDates[] = $date->toString();
         }
         $month = $date->toString('Y_m');
         // For a given date, we must invalidate in the monthly archive table
         $datesByMonth[$month][] = $date->toString();
         // But also the year stored in January
         $year = $date->toString('Y_01');
         $datesByMonth[$year][] = $date->toString();
         // but also weeks overlapping several months stored in the month where the week is starting
         /* @var $week Week */
         $week = Period\Factory::build('week', $date);
         $weekAsString = $week->getDateStart()->toString('Y_m');
         $datesByMonth[$weekAsString][] = $date->toString();
         // Keep track of the minimum date for each website
         if ($minDate === false || $date->isEarlier($minDate)) {
             $minDate = $date;
         }
     }
     if (empty($minDate)) {
         throw new Exception("Check the 'dates' parameter is a valid date.");
     }
     // In each table, invalidate day/week/month/year containing this date
     $archiveTables = ArchiveTableCreator::getTablesArchivesInstalled();
     foreach ($archiveTables as $table) {
         // Extract Y_m from table name
         $suffix = ArchiveTableCreator::getDateFromTableName($table);
         if (!isset($datesByMonth[$suffix])) {
             continue;
         }
         // Dates which are to be deleted from this table
         $datesToDeleteInTable = $datesByMonth[$suffix];
         // Build one statement to delete all dates from the given table
         $sql = $bind = array();
         $datesToDeleteInTable = array_unique($datesToDeleteInTable);
         foreach ($datesToDeleteInTable as $dateToDelete) {
             $sql[] = '(date1 <= ? AND ? <= date2)';
             $bind[] = $dateToDelete;
             $bind[] = $dateToDelete;
         }
         $sql = implode(" OR ", $sql);
         $query = "DELETE FROM {$table} " . " WHERE ( {$sql} ) " . " AND idsite IN (" . implode(",", $idSites) . ")";
         Db::query($query, $bind);
     }
     \Piwik\Plugins\SitesManager\API::getInstance()->updateSiteCreatedTime($idSites, $minDate);
     // Force to re-process data for these websites in the next cron core:archive command run
     $invalidatedIdSites = self::getWebsiteIdsToInvalidate();
     $invalidatedIdSites = array_merge($invalidatedIdSites, $idSites);
     $invalidatedIdSites = array_unique($invalidatedIdSites);
     $invalidatedIdSites = array_values($invalidatedIdSites);
     Option::set(self::OPTION_INVALIDATED_IDSITES, serialize($invalidatedIdSites));
     Site::clearCache();
     $output = array();
     // output logs
     if ($warningDates) {
         $output[] = 'Warning: the following Dates have not been invalidated, because they are earlier than your Log Deletion limit: ' . implode(", ", $warningDates) . "\n The last day with logs is " . $minimumDateWithLogs . ". " . "\n Please disable 'Delete old Logs' or set it to a higher deletion threshold (eg. 180 days or 365 years).'.";
     }
     $output[] = "Success. The following dates were invalidated successfully: " . implode(", ", $processedDates);
     return $output;
 }
Exemplo n.º 28
0
 /**
  * Saves the layout as default
  */
 public function saveLayoutAsDefault()
 {
     $this->checkTokenInUrl();
     if (Piwik::hasUserSuperUserAccess()) {
         $layout = Common::unsanitizeInputValue(Common::getRequestVar('layout'));
         $paramsBind = array('', '1', $layout, $layout);
         $query = sprintf('INSERT INTO %s (login, iddashboard, layout) VALUES (?,?,?) ON DUPLICATE KEY UPDATE layout=?', Common::prefixTable('user_dashboard'));
         Db::query($query, $paramsBind);
     }
 }
Exemplo n.º 29
0
 /**
  * Drops the tables created by the privilege checking queries, if they exist.
  *
  * @param \Piwik\Db $db The database object to use.
  */
 private function dropExtraTables($db)
 {
     $db->query('DROP TABLE IF EXISTS ' . self::TEST_TABLE_NAME . ', ' . self::TEST_TEMP_TABLE_NAME);
 }
Exemplo n.º 30
0
 /**
  * Updates the field ts_created for the specified websites.
  *
  * @param $idSites int Id Site to update ts_created
  * @param $minDate Date to set as creation date. To play it safe it will substract one more day.
  *
  * @ignore
  */
 public function updateSiteCreatedTime($idSites, Date $minDate)
 {
     $idSites = Site::getIdSitesFromIdSitesString($idSites);
     Piwik::checkUserHasAdminAccess($idSites);
     // Update piwik_site.ts_created
     $query = "UPDATE " . Common::prefixTable("site") . " SET ts_created = ?" . " WHERE idsite IN ( " . implode(",", $idSites) . " )\n\t\t\t\t\tAND ts_created > ?";
     $minDateSql = $minDate->subDay(1)->getDatetime();
     $bind = array($minDateSql, $minDateSql);
     Db::query($query, $bind);
 }