├── src ├── Controller │ ├── .gitignore │ ├── Controller.php │ ├── AuthController.php │ ├── CollectController.php │ └── DashboardController.php ├── Kernel.php ├── Entity │ ├── Domain.php │ ├── SiteStats.php │ ├── PageStats.php │ ├── ReferrerStats.php │ └── User.php ├── Command │ ├── RotateSeedCommand.php │ ├── UserDeleteCommand.php │ ├── UserCreateCommand.php │ ├── DomainDeleteCommand.php │ ├── DatabasePurgeCommand.php │ ├── AggregateCommand.php │ ├── DatabaseResetCommand.php │ ├── DatabaseMigrateCommand.php │ ├── DomainCreateCommand.php │ └── DatabaseSeedCommand.php ├── ReferrerBlocklist.php ├── Database.php ├── Repository │ ├── UserRepository.php │ ├── DomainRepository.php │ ├── StatRepositorySqlite.php │ ├── StatRepositoryMysql.php │ └── StatRepository.php ├── Template.php ├── Security │ └── Gate.php ├── Chart.php ├── Dates.php ├── SessionManager.php ├── Normalizer.php └── Aggregator.php ├── public ├── favicon.ico ├── screenshot.png ├── icon-128x128.png ├── index.php ├── ka.js └── dashboard.js ├── config ├── bundles.php ├── routes.yaml ├── routes │ └── framework.yaml ├── preload.php ├── packages │ ├── routing.yaml │ └── framework.yaml └── services.yaml ├── templates ├── _footer.html.php ├── _performance.html.php ├── _header.html.php ├── dashboard-list.html.php ├── dashboard-create.html.php ├── login.html.php ├── _chart.html.php ├── settings.html.php └── dashboard.html.php ├── .env.test ├── migrations ├── mysql │ ├── 006-domain-user.php │ ├── 002-domains-table.php │ ├── 004-settings-table.php │ ├── 001-users-table.php │ └── 005-domain-settings.php └── sqlite │ ├── 002-domains-table.php │ ├── 004-settings-table.php │ ├── 001-users-table.php │ ├── 005-domain-settings.php │ └── 006-domain-user.php ├── .editorconfig ├── tests ├── bootstrap.php ├── ReferrerBlocklistTest.php ├── Repository │ ├── UserRepositoryTest.php │ └── DomainRepositoryTest.php ├── benchmarks │ ├── preg-match-constraint-vs-negative-lookahead.php │ ├── preg-match-vs-ctype-alnum.php │ ├── str-starts-with-vs-strncmp.php │ └── in-array-vs-multiple-if.php ├── NormalizerTest.php ├── Controller │ ├── AuthControllerTest.php │ └── CollectControllerTest.php ├── SessionManagerTest.php ├── SmokeTest.php └── DatesTest.php ├── SECURITY.md ├── phpcs.xml.dist ├── psalm.xml ├── .gitignore ├── .github └── workflows │ ├── php-check-syntax.yml │ └── test.yml ├── bin ├── console ├── check_templates └── phpunit ├── .env ├── phpunit.xml.dist ├── composer.json ├── symfony.lock ├── README.md └── LICENSE /src/Controller/.gitignore: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /public/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ibericode/koko-analytics-standalone/main/public/favicon.ico -------------------------------------------------------------------------------- /public/screenshot.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ibericode/koko-analytics-standalone/main/public/screenshot.png -------------------------------------------------------------------------------- /public/icon-128x128.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ibericode/koko-analytics-standalone/main/public/icon-128x128.png -------------------------------------------------------------------------------- /config/bundles.php: -------------------------------------------------------------------------------- 1 | ['all' => true], 5 | ]; 6 | -------------------------------------------------------------------------------- /config/routes.yaml: -------------------------------------------------------------------------------- 1 | controllers: 2 | resource: 3 | path: ../src/Controller/ 4 | namespace: App\Controller 5 | type: attribute 6 | -------------------------------------------------------------------------------- /templates/_footer.html.php: -------------------------------------------------------------------------------- 1 |
2 | partial('_performance.html.php'); ?> 3 |
4 | 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /config/routes/framework.yaml: -------------------------------------------------------------------------------- 1 | when@dev: 2 | _errors: 3 | resource: '@FrameworkBundle/Resources/config/routing/errors.php' 4 | prefix: /_error 5 | -------------------------------------------------------------------------------- /config/preload.php: -------------------------------------------------------------------------------- 1 | 2 | Page generated in ms.
3 | Peak memory > 20; ?> MB. 4 |

5 | -------------------------------------------------------------------------------- /public/index.php: -------------------------------------------------------------------------------- 1 | exec("ALTER TABLE koko_analytics_domains ADD COLUMN user_id INT UNSIGNED NOT NULL"); 7 | $db->exec("UPDATE koko_analytics_domains SET user_id = (SELECT id FROM koko_analytics_users LIMIT 1)"); 8 | }; 9 | -------------------------------------------------------------------------------- /src/Entity/Domain.php: -------------------------------------------------------------------------------- 1 | exec( 7 | "CREATE TABLE koko_analytics_domains ( 8 | id INTEGER PRIMARY KEY, 9 | name VARCHAR(255) NOT NULL, 10 | UNIQUE (name) 11 | )" 12 | ); 13 | }; 14 | -------------------------------------------------------------------------------- /.editorconfig: -------------------------------------------------------------------------------- 1 | # editorconfig.org 2 | 3 | root = true 4 | 5 | [*] 6 | charset = utf-8 7 | end_of_line = lf 8 | indent_size = 4 9 | indent_style = space 10 | insert_final_newline = true 11 | trim_trailing_whitespace = true 12 | 13 | [{compose.yaml,compose.*.yaml}] 14 | indent_size = 2 15 | 16 | [*.md] 17 | trim_trailing_whitespace = false 18 | -------------------------------------------------------------------------------- /config/packages/routing.yaml: -------------------------------------------------------------------------------- 1 | framework: 2 | router: 3 | # Configure how to generate URLs in non-HTTP contexts, such as CLI commands. 4 | # See https://symfony.com/doc/current/routing.html#generating-urls-in-commands 5 | #default_uri: http://localhost 6 | 7 | when@prod: 8 | framework: 9 | router: 10 | strict_requirements: null 11 | -------------------------------------------------------------------------------- /migrations/sqlite/004-settings-table.php: -------------------------------------------------------------------------------- 1 | exec( 7 | "CREATE TABLE koko_analytics_settings ( 8 | domain_id SMALLINT UNSIGNED NOT NULL, 9 | name VARCHAR(127) NOT NULL, 10 | value TEXT NOT NULL, 11 | PRIMARY KEY (domain_id, name) 12 | )" 13 | ); 14 | }; 15 | -------------------------------------------------------------------------------- /migrations/mysql/002-domains-table.php: -------------------------------------------------------------------------------- 1 | exec( 7 | "CREATE TABLE koko_analytics_domains ( 8 | id SMALLINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY, 9 | name VARCHAR(255) NOT NULL, 10 | UNIQUE INDEX (name) 11 | ) ENGINE=INNODB CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;" 12 | ); 13 | }; 14 | -------------------------------------------------------------------------------- /migrations/mysql/004-settings-table.php: -------------------------------------------------------------------------------- 1 | exec( 7 | "CREATE TABLE koko_analytics_settings ( 8 | domain_id SMALLINT UNSIGNED NOT NULL, 9 | name VARCHAR(127) NOT NULL, 10 | value TEXT NOT NULL, 11 | PRIMARY KEY (domain_id, name) 12 | ) ENGINE=INNODB CHARACTER SET=utf8mb4" 13 | ); 14 | }; 15 | -------------------------------------------------------------------------------- /migrations/sqlite/001-users-table.php: -------------------------------------------------------------------------------- 1 | exec( 7 | "CREATE TABLE koko_analytics_users ( 8 | id INTEGER PRIMARY KEY, 9 | email VARCHAR(255) NOT NULL, 10 | password VARCHAR(255) NOT NULL DEFAULT '', 11 | role VARCHAR(32) NOT NULL DEFAULT 'viewer', 12 | UNIQUE (email) 13 | )" 14 | ); 15 | }; 16 | -------------------------------------------------------------------------------- /tests/bootstrap.php: -------------------------------------------------------------------------------- 1 | bootEnv(dirname(__DIR__) . '/.env'); 9 | } 10 | 11 | // create buffer file for default domain 12 | // so that requests to /collect are accepted 13 | touch(dirname(__DIR__) . "/var/buffer-website.com"); 14 | 15 | if ($_SERVER['APP_DEBUG']) { 16 | umask(0000); 17 | } 18 | -------------------------------------------------------------------------------- /SECURITY.md: -------------------------------------------------------------------------------- 1 | # Security Policy 2 | 3 | The Koko Analytics team and community take potential security issues in our software seriously. 4 | We appreciate your efforts to responsibly disclose your findings, and will make every effort to acknowledge your contributions. 5 | 6 | ## Reporting a Vulnerability 7 | 8 | To report a security issue, please email us at support@kokoanalytics.com or use the GitHub Security Advisory "[Report a Vulnerability](https://github.com/koko-analytics/koko-analytics/security/advisories/new)" tab. 9 | -------------------------------------------------------------------------------- /migrations/mysql/001-users-table.php: -------------------------------------------------------------------------------- 1 | exec( 7 | "CREATE TABLE koko_analytics_users ( 8 | id INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY, 9 | email VARCHAR(255) NOT NULL, 10 | password VARCHAR(255) NOT NULL DEFAULT '', 11 | role ENUM ('viewer', 'admin') DEFAULT 'viewer', 12 | UNIQUE INDEX (email) 13 | ) ENGINE=INNODB CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;" 14 | ); 15 | }; 16 | -------------------------------------------------------------------------------- /tests/ReferrerBlocklistTest.php: -------------------------------------------------------------------------------- 1 | getFilename()); 14 | self::assertEquals([], $blocklist->read(), "non-existing blocklist not empty"); 15 | 16 | $blocklist->update(); 17 | self::assertNotEmpty($blocklist->read(), "blocklist not updated"); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /phpcs.xml.dist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | bin/ 14 | config/ 15 | public/ 16 | src/ 17 | tests/ 18 | 19 | 20 | -------------------------------------------------------------------------------- /psalm.xml: -------------------------------------------------------------------------------- 1 | 2 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | -------------------------------------------------------------------------------- /src/Entity/SiteStats.php: -------------------------------------------------------------------------------- 1 | date = isset($data['date']) ? new \DateTimeImmutable($data['date'], new \DateTimeZone('UTC')) : null; 15 | $obj->visitors = (int) $data['visitors']; 16 | $obj->pageviews = (int) $data['pageviews']; 17 | return $obj; 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /migrations/mysql/005-domain-settings.php: -------------------------------------------------------------------------------- 1 | exec( 7 | "ALTER TABLE koko_analytics_domains ADD COLUMN timezone VARCHAR(255) NOT NULL DEFAULT 'UTC'" 8 | ); 9 | $db->exec( 10 | "ALTER TABLE koko_analytics_domains ADD COLUMN purge_treshold SMALLINT UNSIGNED NOT NULL DEFAULT 1825" 11 | ); 12 | $db->exec( 13 | "ALTER TABLE koko_analytics_domains ADD COLUMN excluded_ip_addresses TEXT NOT NULL" 14 | ); 15 | $db->exec( 16 | "DROP TABLE koko_analytics_settings" 17 | ); 18 | }; 19 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | TODO.md 2 | bin/deploy.sh 3 | 4 | ###> symfony/framework-bundle ### 5 | /.env.local 6 | /.env.local.php 7 | /.env.*.local 8 | /config/secrets/prod/prod.decrypt.private.php 9 | /public/bundles/ 10 | /var/ 11 | /vendor/ 12 | ###< symfony/framework-bundle ### 13 | 14 | ###> symfony/phpunit-bridge ### 15 | .phpunit.result.cache 16 | /phpunit.xml 17 | ###< symfony/phpunit-bridge ### 18 | 19 | ###> phpunit/phpunit ### 20 | /phpunit.xml 21 | .phpunit.result.cache 22 | ###< phpunit/phpunit ### 23 | 24 | 25 | 26 | ###> squizlabs/php_codesniffer ### 27 | /.phpcs-cache 28 | /phpcs.xml 29 | ###< squizlabs/php_codesniffer ### 30 | -------------------------------------------------------------------------------- /.github/workflows/php-check-syntax.yml: -------------------------------------------------------------------------------- 1 | name: Check PHP Syntax 2 | on: push 3 | jobs: 4 | build: 5 | runs-on: ubuntu-24.04 6 | strategy: 7 | matrix: 8 | php-versions: ['8.4', 'highest'] 9 | steps: 10 | # Install PHP interpreter 11 | - name: Setup PHP 12 | uses: shivammathur/setup-php@v2 13 | with: 14 | php-version: ${{ matrix.php-versions }} 15 | 16 | # Checkout source repository 17 | - name: checkout repo 18 | uses: actions/checkout@v3 19 | 20 | # Check syntax of every PHP source file using PHP interpreter 21 | - run: composer run check-syntax 22 | -------------------------------------------------------------------------------- /src/Entity/PageStats.php: -------------------------------------------------------------------------------- 1 | date = isset($data['date']) ? new \DateTimeImmutable($data['date'], new \DateTimeZone('UTC')) : null; 16 | $obj->visitors = (int) $data['visitors']; 17 | $obj->pageviews = (int) $data['pageviews']; 18 | $obj->url = $data['url']; 19 | return $obj; 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/Entity/ReferrerStats.php: -------------------------------------------------------------------------------- 1 | date = isset($data['date']) ? new \DateTimeImmutable($data['date'], new \DateTimeZone('UTC')) : null; 16 | $obj->visitors = (int) $data['visitors']; 17 | $obj->pageviews = (int) $data['pageviews']; 18 | $obj->url = $data['url']; 19 | return $obj; 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /bin/console: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env php 2 | /', $line)) { 16 | echo "WARNING: unquoted HTML attributes with dynamic content in file '$file' on line {$ln}.\n> {$line}\n"; 17 | $exit_status = 1; 18 | } 19 | 20 | $ln++; 21 | } 22 | 23 | fclose($fh); 24 | } 25 | 26 | exit($exit_status); 27 | -------------------------------------------------------------------------------- /config/services.yaml: -------------------------------------------------------------------------------- 1 | parameters: 2 | services: 3 | # default configuration for services in *this* file 4 | _defaults: 5 | autowire: true # Automatically injects dependencies in your services. 6 | autoconfigure: true 7 | 8 | # this creates a service per class whose id is the fully-qualified class name 9 | App\: 10 | resource: '../src/' 11 | exclude: 12 | - '../src/DependencyInjection/' 13 | - '../src/Entity/' 14 | - '../src/Kernel.php' 15 | 16 | App\Database: 17 | arguments: 18 | $dsn: '%env(DATABASE_DSN)%' 19 | $username: '%env(DATABASE_USER)%' 20 | $password: '%env(DATABASE_PASSWORD)%' 21 | 22 | App\Repository\StatRepository: 23 | factory: [ 'App\Repository\StatRepository', 'create'] 24 | 25 | -------------------------------------------------------------------------------- /src/Command/RotateSeedCommand.php: -------------------------------------------------------------------------------- 1 | rotateSeed(); 18 | $output->writeln("Written new seed to {$sessionManager->getSeedFilename()}."); 19 | return Command::SUCCESS; 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /templates/_header.html.php: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | <?php $this->e($title ?? ''); ?> 6 | 7 | 8 | 9 | 10 | 11 | getFlashMessages() as $type => $messages) { 13 | echo '
'; 14 | foreach ($messages as $message) { 15 | echo '
'; 16 | echo $message; 17 | echo ''; 18 | echo '
'; 19 | } 20 | echo '
'; 21 | } 22 | ?> 23 | -------------------------------------------------------------------------------- /migrations/sqlite/005-domain-settings.php: -------------------------------------------------------------------------------- 1 | exec("ALTER TABLE koko_analytics_domains RENAME TO koko_analytics_domains_old"); 7 | 8 | $db->exec( 9 | "CREATE TABLE koko_analytics_domains ( 10 | id INTEGER PRIMARY KEY, 11 | name VARCHAR(255) NOT NULL, 12 | timezone VARCHAR(255) NOT NULL DEFAULT 'UTC', 13 | purge_treshold INTEGER NOT NULL DEFAULT 1825, 14 | excluded_ip_addresses VARCHAR(255) NOT NULL DEFAULT '', 15 | UNIQUE (name) 16 | )" 17 | ); 18 | 19 | $db->exec("INSERT INTO koko_analytics_domains(id, name) SELECT id, name FROM koko_analytics_domains_old"); 20 | $db->exec("DROP TABLE koko_analytics_domains_old"); 21 | $db->exec("DROP TABLE koko_analytics_settings"); 22 | }; 23 | -------------------------------------------------------------------------------- /bin/phpunit: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env php 2 | = 80000) { 10 | require dirname(__DIR__).'/vendor/phpunit/phpunit/phpunit'; 11 | } else { 12 | define('PHPUNIT_COMPOSER_INSTALL', dirname(__DIR__).'/vendor/autoload.php'); 13 | require PHPUNIT_COMPOSER_INSTALL; 14 | PHPUnit\TextUI\Command::main(); 15 | } 16 | } else { 17 | if (!is_file(dirname(__DIR__).'/vendor/symfony/phpunit-bridge/bin/simple-phpunit.php')) { 18 | echo "Unable to find the `simple-phpunit.php` script in `vendor/symfony/phpunit-bridge/bin/`.\n"; 19 | exit(1); 20 | } 21 | 22 | require dirname(__DIR__).'/vendor/symfony/phpunit-bridge/bin/simple-phpunit.php'; 23 | } 24 | -------------------------------------------------------------------------------- /public/ka.js: -------------------------------------------------------------------------------- 1 | window.addEventListener('load', function() { 2 | if ( 3 | document.visibilityState === 'prerender' 4 | || (/bot|crawl|spider|seo|lighthouse|facebookexternalhit|preview/i).test(navigator.userAgent) 5 | ) { 6 | return 7 | } 8 | 9 | var path = window.ka.path ? window.ka.path : location.pathname; 10 | var self = location.origin; 11 | var canonical = document.querySelector('link[rel="canonical"]'); 12 | if (canonical) { 13 | path = canonical.href.split(self.split('http').pop()).pop(); 14 | } 15 | path = path.replace(/.*:\/\/[^\/]+/, '') 16 | var referrer = document.referrer.startsWith(self) ? '' : document.referrer; 17 | navigator.sendBeacon(window.ka.url + '/collect', new URLSearchParams({ 18 | d: window.ka.domain, 19 | p: path, 20 | r: referrer, 21 | })); 22 | }); 23 | -------------------------------------------------------------------------------- /src/Controller/Controller.php: -------------------------------------------------------------------------------- 1 | container)->render($view, $parameters, $response); 16 | } 17 | 18 | protected function getAuthenticatedUser(): ?User 19 | { 20 | /** @var Request $request */ 21 | $request = $this->container->get('request_stack')->getCurrentRequest(); 22 | $session = $request->getSession(); 23 | return $session->get('user'); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /migrations/sqlite/006-domain-user.php: -------------------------------------------------------------------------------- 1 | exec("ALTER TABLE koko_analytics_domains RENAME TO koko_analytics_domains_old"); 7 | 8 | $db->exec( 9 | "CREATE TABLE koko_analytics_domains ( 10 | id INTEGER PRIMARY KEY, 11 | user_id INTEGER NOT NULL, 12 | name VARCHAR(255) NOT NULL, 13 | timezone VARCHAR(255) NOT NULL DEFAULT 'UTC', 14 | purge_treshold INTEGER NOT NULL DEFAULT 1825, 15 | excluded_ip_addresses VARCHAR(255) NOT NULL DEFAULT '', 16 | UNIQUE (name) 17 | )" 18 | ); 19 | 20 | $db->exec("INSERT INTO koko_analytics_domains(id, user_id, name) SELECT id, (SELECT id FROM koko_analytics_users LIMIT 1), name FROM koko_analytics_domains_old"); 21 | $db->exec("DROP TABLE koko_analytics_domains_old"); 22 | }; 23 | -------------------------------------------------------------------------------- /templates/dashboard-list.html.php: -------------------------------------------------------------------------------- 1 | partial('_header.html.php', [ 'title' => 'Dashboards - Koko Analytics']); ?> 2 | 3 |
4 | 5 |

6 | Koko Analytics logo 7 | Choose a domain 8 |

9 | 10 | 15 | 16 |
17 | + Add new domain 18 |
19 | 20 | 21 |
22 | 23 | 24 | -------------------------------------------------------------------------------- /tests/Repository/UserRepositoryTest.php: -------------------------------------------------------------------------------- 1 | get(UserRepository::class); 20 | 21 | $repo->reset(); 22 | self::assertEquals(null, $repo->getByEmail('test@kokoanalytics.com')); 23 | 24 | $user = new User(); 25 | $user->setEmail('test@kokoanalytics.com'); 26 | $user->setPassword(''); 27 | $repo->save($user); 28 | self::assertGreaterThan(0, $user->getId()); 29 | self::assertEquals($user, $repo->getByEmail('test@kokoanalytics.com')); 30 | 31 | $repo->reset(); 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /templates/dashboard-create.html.php: -------------------------------------------------------------------------------- 1 | partial('_header.html.php', [ 'title' => 'Add domain - Koko Analytics']); ?> 2 | 3 |
4 |

5 | Koko Analytics logo 6 | Add new domain 7 |

8 | 9 |
10 | 11 |
12 | e($error) ?> 13 |
14 | 15 | 16 |
17 | 18 | 19 |
Enter your domain name. Use only alphanumeric characters, hyphens or dots.
20 |
21 | 22 |
23 | 24 |
25 |
26 |
27 | 28 | -------------------------------------------------------------------------------- /.env: -------------------------------------------------------------------------------- 1 | # In all environments, the following files are loaded if they exist, 2 | # the latter taking precedence over the former: 3 | # 4 | # * .env contains default values for the environment variables needed by the app 5 | # * .env.local uncommitted file with local overrides 6 | # * .env.$APP_ENV committed environment-specific defaults 7 | # * .env.$APP_ENV.local uncommitted environment-specific overrides 8 | # 9 | # Real environment variables win over .env files. 10 | # 11 | # DO NOT DEFINE PRODUCTION SECRETS IN THIS FILE NOR IN ANY OTHER COMMITTED FILES. 12 | # https://symfony.com/doc/current/configuration/secrets.html 13 | # 14 | # Run "composer dump-env prod" to compile .env files for production use (requires symfony/flex >=1.2). 15 | # https://symfony.com/doc/current/best_practices.html#use-environment-variables-for-infrastructure-configuration 16 | 17 | ###> symfony/framework-bundle ### 18 | APP_ENV=prod 19 | APP_SECRET= 20 | APP_DEBUG=false 21 | ###< symfony/framework-bundle ### 22 | 23 | DATABASE_DSN="mysql:host=127.0.0.1;dbname=koko_analytics" 24 | DATABASE_USER="koko_analytics" 25 | DATABASE_PASSWORD="" 26 | -------------------------------------------------------------------------------- /tests/benchmarks/preg-match-constraint-vs-negative-lookahead.php: -------------------------------------------------------------------------------- 1 | $fn) { 8 | $time_start = microtime(true); 9 | for ($i = 0; $i < $n; $i++) { 10 | $result = $fn(); 11 | } 12 | $time = (microtime(true) - $time_start) / $n; 13 | $result or throw new Exception("Incorrect result"); 14 | 15 | $results[] = [$name, $time * 1e6]; 16 | } 17 | 18 | usort($results, function ($a, $b) { 19 | return $a[1] > $b[1]; 20 | }); 21 | 22 | foreach ($results as [$name, $time]) { 23 | echo sprintf("%-16s\t%.2f μs / it\n", $name, $time); 24 | } 25 | } 26 | 27 | 28 | $path = '/contact/?p=100&utm_source=foobar%20barfoo+hello'; 29 | // [a-zA-Z0-9-\/\#\&\?\=\%] 30 | bench([ 31 | '[a-zA-Z0-9\-\/\#\&\?\=\%]+' => function () use ($path) { 32 | return 1 === preg_match("/[a-zA-Z0-9\-\/\#\&\?\=\%]+/", $path); 33 | }, 34 | '[^a-zA-Z0-9\-\/\#\&\?\=\%]' => function () use ($path) { 35 | return 0 === preg_match("/[^a-zA-Z0-9\-\/\#\&\?\=\%\_\+]/", $path); 36 | }, 37 | ]); 38 | -------------------------------------------------------------------------------- /tests/benchmarks/preg-match-vs-ctype-alnum.php: -------------------------------------------------------------------------------- 1 | $fn) { 10 | $time_start = microtime(true); 11 | for ($i = 0; $i < $n; $i++) { 12 | $result = $fn(); 13 | } 14 | $time = (microtime(true) - $time_start) / $n; 15 | $result or throw new Exception("Incorrect result"); 16 | 17 | $results[] = [$name, $time * 1e6]; 18 | } 19 | 20 | usort($results, function ($a, $b) { 21 | return $a[1] > $b[1]; 22 | }); 23 | 24 | foreach ($results as [$name, $time]) { 25 | echo sprintf("%-16s\t%.2f μs / it\n", $name, $time); 26 | } 27 | } 28 | 29 | bench([ 30 | "preg_replace" => function () use ($string) { 31 | return ! preg_match('/[^a-zA-Z0-9\.\-]/', $string); 32 | }, 33 | "strtr + ctype_alnum" => function () use ($string) { 34 | return ctype_alnum(strtr($string, ["-" => "0", "." => "0"])); 35 | }, 36 | "strspn" => function () use ($string) { 37 | return strspn($string, "abcdefghijklmnopqrstuvwxyz0123456789-.") == strlen($string); 38 | } 39 | ]); 40 | -------------------------------------------------------------------------------- /src/ReferrerBlocklist.php: -------------------------------------------------------------------------------- 1 | getFilename(); 15 | 16 | // only update once per day unless $force is true 17 | if (!$force && is_file($filename) && filemtime($filename) > time() - 24 * 60 * 60) { 18 | return false; 19 | } 20 | 21 | $blocklist = file_get_contents("https://raw.githubusercontent.com/matomo-org/referrer-spam-blacklist/master/spammers.txt"); 22 | if (!$blocklist) { 23 | throw new \Exception("Error downloading blocklist"); 24 | } 25 | 26 | if (!file_put_contents($this->getFilename(), $blocklist)) { 27 | throw new \Exception("Error writing blocklist to file"); 28 | } 29 | 30 | return true; 31 | } 32 | 33 | public function read(): array 34 | { 35 | $filename = $this->getFilename(); 36 | if (!is_file($filename)) { 37 | return []; 38 | } 39 | 40 | return \file($filename, FILE_IGNORE_NEW_LINES) ?: []; 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /tests/NormalizerTest.php: -------------------------------------------------------------------------------- 1 | '', 16 | '/' => '/', 17 | '/ABOUT' => '/about', 18 | '/about/amp/' => '/about/', 19 | '/about/?utm_source=source&utm_campaign=campaign&utm_medium=medium' => '/about/', 20 | '/about/?p=100' => '/about/?p=100', 21 | ]; 22 | 23 | $normalizer = new Normalizer(); 24 | foreach ($tests as $input => $expected) { 25 | self::assertEquals($expected, $normalizer->path($input)); 26 | } 27 | } 28 | 29 | public function testReferrer(): void 30 | { 31 | $tests = [ 32 | '' => '', 33 | 'https://website.com/foo' => 'website.com', 34 | 'not an url' => '', 35 | 'https://www.google.com' => 'google.com', 36 | ]; 37 | 38 | $normalizer = new Normalizer(); 39 | foreach ($tests as $input => $expected) { 40 | self::assertEquals($expected, $normalizer->referrer($input)); 41 | } 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /tests/benchmarks/str-starts-with-vs-strncmp.php: -------------------------------------------------------------------------------- 1 | $fn) { 8 | $time_start = microtime(true); 9 | for ($i = 0; $i < $n; $i++) { 10 | $result = $fn(); 11 | } 12 | $time = (microtime(true) - $time_start) / $n; 13 | $result or throw new Exception("Incorrect result"); 14 | 15 | $results[] = [$name, $time * 1e6]; 16 | } 17 | 18 | usort($results, function ($a, $b) { 19 | return $a[1] > $b[1]; 20 | }); 21 | 22 | foreach ($results as [$name, $time]) { 23 | echo sprintf("%-16s\t%.2f μs / it\n", $name, $time); 24 | } 25 | } 26 | 27 | bench([ 28 | 'str_starts_with' => function () { 29 | return str_starts_with("App\\Controllers\\ApiController", "App\\"); 30 | }, 31 | 'strncmp' => function () { 32 | return strncmp("App\\Controllers\\ApiController", "App\\", strlen("App\\")) === 0; 33 | }, 34 | 'substr' => function () { 35 | return substr("App\\Controllers\\ApiController", 0, strlen("App\\")) === "App\\"; 36 | }, 37 | 'strpos' => function () { 38 | return strpos("App\\Controllers\\ApiController", "App\\") === 0; 39 | }, 40 | ]); 41 | -------------------------------------------------------------------------------- /src/Entity/User.php: -------------------------------------------------------------------------------- 1 | id; 18 | } 19 | 20 | public function setId(?int $id): static 21 | { 22 | $this->id = $id; 23 | return $this; 24 | } 25 | 26 | public function getEmail(): string 27 | { 28 | return $this->email; 29 | } 30 | 31 | public function setEmail(string $email): static 32 | { 33 | $this->email = $email; 34 | return $this; 35 | } 36 | 37 | public function getRole(): string 38 | { 39 | return $this->role; 40 | } 41 | 42 | public function setRole(string $role): static 43 | { 44 | $this->role = $role; 45 | return $this; 46 | } 47 | 48 | public function getPassword(): string 49 | { 50 | return $this->password; 51 | } 52 | 53 | public function setPassword(string $password): static 54 | { 55 | $this->password = $password; 56 | return $this; 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /src/Command/UserDeleteCommand.php: -------------------------------------------------------------------------------- 1 | addArgument('email', InputArgument::REQUIRED, 'The email address of the user.') 24 | ; 25 | } 26 | 27 | protected function execute(InputInterface $input, OutputInterface $output): int 28 | { 29 | $email = $input->getArgument('email'); 30 | 31 | $user = $this->userRepository->getByEmail($email); 32 | if (!$user) { 33 | $output->writeln("No user with email {$email}"); 34 | return Command::FAILURE; 35 | } 36 | 37 | $this->userRepository->delete($user); 38 | return Command::SUCCESS; 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /phpunit.xml.dist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | tests 23 | 24 | 25 | 26 | 27 | 28 | src 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | -------------------------------------------------------------------------------- /src/Command/UserCreateCommand.php: -------------------------------------------------------------------------------- 1 | addArgument('email', InputArgument::REQUIRED, 'The email address of the user.') 25 | ->addArgument('password', InputArgument::REQUIRED, 'The password of the user.') 26 | ; 27 | } 28 | 29 | protected function execute(InputInterface $input, OutputInterface $output): int 30 | { 31 | $email = $input->getArgument('email'); 32 | $raw_password = $input->getArgument('password'); 33 | $password = password_hash($raw_password, PASSWORD_DEFAULT); 34 | $user = new User(); 35 | $user->setEmail($email); 36 | $user->setPassword($password); 37 | $this->userRepository->save($user); 38 | return Command::SUCCESS; 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /src/Command/DomainDeleteCommand.php: -------------------------------------------------------------------------------- 1 | addArgument('name', InputArgument::REQUIRED, 'Name of the domain (without protocol)'); 27 | } 28 | 29 | protected function execute(InputInterface $input, OutputInterface $output): int 30 | { 31 | $name = $input->getArgument('name'); 32 | $domain = $this->domainRepository->getByName($name); 33 | if (!$domain) { 34 | $output->writeln("No domain with name {$name}"); 35 | return Command::FAILURE; 36 | } 37 | 38 | $this->statRepository->reset($domain); 39 | $this->domainRepository->delete($domain); 40 | return Command::SUCCESS; 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /src/Database.php: -------------------------------------------------------------------------------- 1 | driverName = \substr($dsn, 0, \strpos($dsn, ':')); 22 | 23 | parent::__construct($this->makeDatabasePathAbsolute($dsn), $username, $password, [ 24 | PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, 25 | PDO::ATTR_EMULATE_PREPARES => false, 26 | PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC, 27 | ]); 28 | } 29 | 30 | private function makeDatabasePathAbsolute(string $dsn): string 31 | { 32 | // do nothing if not using sqlite driver 33 | if (!\str_starts_with($dsn, 'sqlite:')) { 34 | return $dsn; 35 | } 36 | 37 | // return unmodified if already absolute 38 | if (\str_starts_with($dsn, 'sqlite:/') || \str_starts_with($dsn, 'sqlite::memory:')) { 39 | return $dsn; 40 | } 41 | 42 | $root = \dirname(__DIR__) . DIRECTORY_SEPARATOR; 43 | $database = \substr($dsn, \strlen('sqlite:')); 44 | return "sqlite:{$root}{$database}"; 45 | } 46 | 47 | public function getDriverName(): string 48 | { 49 | return $this->driverName; 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /config/packages/framework.yaml: -------------------------------------------------------------------------------- 1 | # see https://symfony.com/doc/current/reference/configuration/framework.html 2 | framework: 3 | secret: '%env(APP_SECRET)%' 4 | 5 | # Note that the session will be started ONLY if you read or write from it. 6 | session: 7 | enabled: true 8 | storage_factory_id: session.storage.factory.native 9 | handler_id: session.handler.native_file 10 | save_path: '%kernel.project_dir%/var/symfony-sessions/%kernel.environment%' 11 | cookie_lifetime: 604800 12 | cookie_httponly: true 13 | cookie_secure: auto 14 | cookie_samesite: strict 15 | 16 | #esi: true 17 | #fragments: true 18 | cache: 19 | # Unique name of your app: used to compute stable namespaces for cache keys. 20 | #prefix_seed: your_vendor_name/app_name 21 | 22 | # The "app" cache stores to the filesystem by default. 23 | # The data in this cache should persist between deploys. 24 | # Other options include: 25 | 26 | # Redis 27 | #app: cache.adapter.redis 28 | #default_redis_provider: redis://localhost 29 | 30 | # APCu (not recommended with heavy random-write workloads as memory fragmentation can cause perf issues) 31 | #app: cache.adapter.apcu 32 | 33 | # Namespaced pools use the above "app" backend by default 34 | #pools: 35 | #my.dedicated.cache: null 36 | 37 | when@test: 38 | framework: 39 | test: true 40 | session: 41 | storage_factory_id: session.storage.factory.mock_file 42 | -------------------------------------------------------------------------------- /src/Command/DatabasePurgeCommand.php: -------------------------------------------------------------------------------- 1 | addOption('months', 'm', InputOption::VALUE_REQUIRED, 'Purge data older than how many months?', '24'); 29 | } 30 | 31 | protected function execute(InputInterface $input, OutputInterface $output): int 32 | { 33 | $months = (int) $input->getOption('months'); 34 | $cutoff_date = new DateTimeImmutable("-{$months} months", new DateTimeZone('UTC')); 35 | 36 | $domains = $this->domainRepository->getAll(); 37 | foreach ($domains as $domain) { 38 | $this->statRepository->deleteAllBeforeDate($domain, $cutoff_date); 39 | } 40 | 41 | return Command::SUCCESS; 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /src/Repository/UserRepository.php: -------------------------------------------------------------------------------- 1 | setId((int) $data['id']); 19 | $user->setEmail($data['email']); 20 | $user->setPassword($data['password']); 21 | $user->setRole($data['role']); 22 | return $user; 23 | } 24 | 25 | public function getByEmail(string $email): ?User 26 | { 27 | $stmt = $this->db->prepare("SELECT * FROM koko_analytics_users WHERE email = ? LIMIT 1"); 28 | $stmt->execute([ $email ]); 29 | $obj = $stmt->fetch(\PDO::FETCH_ASSOC); 30 | return $obj ? $this->hydrate($obj) : null; 31 | } 32 | 33 | // TODO: handle updates 34 | public function save(User $user): void 35 | { 36 | $this->db 37 | ->prepare("INSERT INTO koko_analytics_users (email, password) VALUES (?, ?)") 38 | ->execute([ $user->getEmail(), $user->getPassword() ]); 39 | $user->setId((int) $this->db->lastInsertId()); 40 | } 41 | 42 | public function delete(User $user): void 43 | { 44 | $this->db 45 | ->prepare("DELETE FROM koko_analytics_users WHERE id = ?") 46 | ->execute([$user->getId()]); 47 | $user->setId(null); 48 | } 49 | 50 | public function reset(): void 51 | { 52 | $this->db->exec("DELETE FROM koko_analytics_users"); 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /src/Command/AggregateCommand.php: -------------------------------------------------------------------------------- 1 | domainRepository->getAll(); 29 | foreach ($domains as $domain) { 30 | $time_start = microtime(true); 31 | $this->aggregator->run($domain); 32 | $time_elapsed = round((microtime(true) - $time_start) * 1000, 2); // in ms 33 | $output->writeln("{$domain->name}: aggregation completed in {$time_elapsed} ms."); 34 | } 35 | 36 | // (maybe) update referrer blocklist 37 | if ((new ReferrerBlocklist())->update()) { 38 | $output->writeln("global: referrer blocklist updated"); 39 | } 40 | 41 | return Command::SUCCESS; 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /tests/Controller/AuthControllerTest.php: -------------------------------------------------------------------------------- 1 | request('GET', '/login'); 16 | self::assertResponseIsSuccessful(); 17 | $this->assertSelectorExists('form button[type="submit"]'); 18 | $this->assertSelectorExists('h1'); 19 | 20 | $client->submitForm('Log in', [ 21 | '_username' => 'test@kokoanalytics.com', 22 | '_password' => '', 23 | ]); 24 | self::assertResponseIsSuccessful(); 25 | self::assertSelectorExists('.error'); 26 | 27 | // create test user for logging in 28 | $repo = self::getContainer()->get(UserRepository::class); 29 | $repo->reset(); 30 | $user = new User(); 31 | $user->setEmail('test@kokoanalytics.com'); 32 | $user->setPassword(\password_hash('password', PASSWORD_DEFAULT)); 33 | $repo->save($user); 34 | 35 | $client->submitForm('Log in', [ 36 | '_username' => 'test@kokoanalytics.com', 37 | '_password' => 'password', 38 | ]); 39 | $client->followRedirects(true); 40 | self::assertResponseRedirects(); 41 | 42 | $repo->reset(); 43 | } 44 | 45 | public function testLogout(): void 46 | { 47 | $client = self::createClient(); 48 | $client->followRedirects(true); 49 | $client->request('GET', '/logout'); 50 | self::assertResponseIsSuccessful(); 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /src/Template.php: -------------------------------------------------------------------------------- 1 | partial($view, $parameters); 20 | $content = \ob_get_clean(); 21 | 22 | $response ??= new Response(); 23 | $response->setContent($content); 24 | return $response; 25 | } 26 | 27 | protected function partial(string $view, array $parameters = []): void 28 | { 29 | \extract($parameters); 30 | require \dirname(__DIR__, 1) . "/templates/{$view}"; 31 | } 32 | 33 | /** 34 | * Generates a URL from the given parameters. 35 | * 36 | * @see UrlGeneratorInterface 37 | */ 38 | protected function generateUrl(string $route, array $parameters = [], int $referenceType = UrlGeneratorInterface::ABSOLUTE_PATH): string 39 | { 40 | return $this->container->get('router')->generate($route, $parameters, $referenceType); 41 | } 42 | 43 | protected function getFlashMessages(): array 44 | { 45 | return $this->container->get('request_stack')->getSession()->getFlashBag()->all(); 46 | } 47 | 48 | protected function e(string $value): void 49 | { 50 | if (str_starts_with($value, 'javascript:')) { 51 | $value = substr($value, strlen('javascript:')); 52 | } 53 | 54 | echo \htmlspecialchars($value, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8'); 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /tests/benchmarks/in-array-vs-multiple-if.php: -------------------------------------------------------------------------------- 1 | $fn) { 8 | $time_start = microtime(true); 9 | for ($i = 0; $i < $n; $i++) { 10 | $result = $fn(); 11 | } 12 | $time = (microtime(true) - $time_start) / $n; 13 | 14 | $results[] = [$name, $time * 1e6]; 15 | } 16 | 17 | usort($results, function ($a, $b) { 18 | return $a[1] > $b[1]; 19 | }); 20 | 21 | foreach ($results as [$name, $time]) { 22 | echo sprintf("%-16s\t%.2f μs / it\n", $name, $time); 23 | } 24 | } 25 | 26 | $first_match = '.'; 27 | $last_match = 'seed.txt'; 28 | $no_match = bin2hex(random_bytes(16)); 29 | 30 | bench([ 31 | 'in_array-first' => function () use ($first_match, $last_match, $no_match) { 32 | return in_array($first_match, ['.', '..', 'seed.txt']); 33 | }, 34 | 'in_array-last' => function () use ($first_match, $last_match, $no_match) { 35 | return in_array($last_match, ['.', '..', 'seed.txt']); 36 | }, 37 | 'in_array-no' => function () use ($first_match, $last_match, $no_match) { 38 | return in_array($no_match, ['.', '..', 'seed.txt']); 39 | }, 40 | 'multiple-if-first' => function () use ($first_match, $last_match, $no_match) { 41 | return $first_match == '.' || $first_match == '..' || $first_match == 'seed.txt'; 42 | }, 43 | 'multiple-if-last' => function () use ($first_match, $last_match, $no_match) { 44 | return $last_match == '.' || $last_match == '..' || $last_match == 'seed.txt'; 45 | }, 46 | 'multiple-if-no' => function () use ($first_match, $last_match, $no_match) { 47 | return $no_match == '.' || $no_match == '..' || $no_match == 'seed.txt'; 48 | }, 49 | ]); 50 | -------------------------------------------------------------------------------- /src/Command/DatabaseResetCommand.php: -------------------------------------------------------------------------------- 1 | getHelper('question'); 32 | $question = new ConfirmationQuestion('Are you sure you want to reset your database? This will remove all data. (y/N)', false); 33 | if (!$helper->ask($input, $output, $question)) { 34 | return Command::SUCCESS; 35 | } 36 | 37 | $domains = $this->domainRepository->getAll(); 38 | foreach ($domains as $domain) { 39 | $this->statRepository->reset($domain); 40 | } 41 | 42 | $this->domainRepository->reset(); 43 | $this->userRepository->reset(); 44 | $output->writeln("Database successfully emptied."); 45 | return Command::SUCCESS; 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /src/Security/Gate.php: -------------------------------------------------------------------------------- 1 | isMainRequest()) { 22 | return; 23 | } 24 | 25 | // don't do anything if request is not for a protected URL path 26 | $public_access_urls = [ 27 | '/login', 28 | '/collect' 29 | ]; 30 | $request = $event->getRequest(); 31 | if (\in_array($request->getPathInfo(), $public_access_urls)) { 32 | return; 33 | } 34 | 35 | // get user from session 36 | $session = $request->getSession(); 37 | $user = $session->get('user'); 38 | if (!$user instanceof User) { 39 | $event->setResponse(new RedirectResponse('/login')); 40 | return; 41 | } 42 | 43 | // abort session if user credentials changed 44 | $user2 = $this->userRepository->getByEmail($user->getEmail()); 45 | if (!$user2 || $user->getEmail() !== $user2->getEmail() || $user->getPassword() !== $user2->getPassword()) { 46 | $session->remove('user'); 47 | $session->invalidate(); 48 | $event->setResponse(new RedirectResponse('/login')); 49 | return; 50 | } 51 | 52 | // user is authenticated! 53 | 54 | // TODO: check for proper role for certain parts (ie admin role for settings) 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /src/Controller/AuthController.php: -------------------------------------------------------------------------------- 1 | getSession()->get('user') instanceof User) { 18 | return $this->redirectToRoute('app_dashboard_list'); 19 | } 20 | 21 | // check if form submitted 22 | if ($request->getMethod() === Request::METHOD_POST) { 23 | $identifier = $request->request->getString('_username', ''); 24 | $password = $request->request->getString('_password', ''); 25 | $user = $userRepository->getByEmail($identifier); 26 | $userPassword = $user ? $user->getPassword() : ''; 27 | if (\password_verify($password, $userPassword) && $user) { 28 | $session = $request->getSession(); 29 | $session->set('user', $user); 30 | $session->save(); 31 | return $this->redirectToRoute('app_dashboard_list'); 32 | } else { 33 | $error = 'Invalid credentials.'; 34 | } 35 | } 36 | 37 | return $this->render("login.html.php", [ 38 | 'last_username' => $identifier ?? '', 39 | 'error' => $error ?? '', 40 | ]); 41 | } 42 | 43 | #[Route('/logout', name: 'app_logout')] 44 | public function logout(Request $request): Response 45 | { 46 | $session = $request->getSession(); 47 | $session->invalidate(); 48 | return new RedirectResponse('/login'); 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /tests/Repository/DomainRepositoryTest.php: -------------------------------------------------------------------------------- 1 | get(DomainRepository::class); 21 | 22 | // assert repository is empty after calling reset 23 | $repo->reset(); 24 | self::assertEquals([], $repo->getAll()); 25 | self::assertEquals(null, $repo->getByName('website.com')); 26 | 27 | // assert inserting a domain sets the ID 28 | $domain = new Domain(); 29 | $domain->user_id = 1; 30 | $domain->name = ('website.com'); 31 | $domain->timezone = ('Europe/Amsterdam'); 32 | $domain->purge_treshold = (100); 33 | $domain->excluded_ip_addresses = (['127.0.0.1']); 34 | $repo->save($domain); 35 | self::assertGreaterThan(0, $domain->id); 36 | 37 | // assert repository contains 1 item now 38 | self::assertCount(1, $repo->getAll()); 39 | 40 | // asert item matches what we just inserted 41 | $saved = $repo->getByName('website.com'); 42 | self::assertNotNull($saved); 43 | self::assertEquals($domain->name, $saved->name); 44 | self::assertEquals($domain->timezone, $saved->timezone); 45 | self::assertEquals($domain->purge_treshold, $saved->purge_treshold); 46 | self::assertEquals($domain->excluded_ip_addresses, $saved->excluded_ip_addresses); 47 | 48 | // assert repository is empty again after calling reset 49 | $repo->reset(); 50 | self::assertEquals([], $repo->getAll()); 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /templates/login.html.php: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | Log in - Koko Analytics 7 | 8 | 9 | 36 | 37 | 38 | 39 |
40 |
41 |
42 | 43 |

Log in

44 |
e($error); ?>
45 |
46 | 47 | 48 |
49 |
50 | 51 |

© e(date('Y')); ?> — Koko Analytics

52 | partial('_performance.html.php'); ?> 53 |
54 |
55 |
56 | 57 | 58 | -------------------------------------------------------------------------------- /src/Chart.php: -------------------------------------------------------------------------------- 1 | prepareChartData($data); 27 | } 28 | 29 | public function render(int $height = 200): void 30 | { 31 | $data = $this->data; 32 | $y_max = $this->y_max; 33 | $date_start = $this->date_start; 34 | $date_end = $this->date_end; 35 | $y_max_nice = $this->getMagnitude(); 36 | 37 | $padding_top = 6; 38 | $padding_bottom = 24; 39 | $padding_left = 4 + \strlen(\number_format($y_max_nice)) * 8; 40 | $inner_height = $height - $padding_top - $padding_bottom; 41 | $height_modifier = $y_max_nice > 0 ? $inner_height / $y_max_nice : 1; 42 | $date_format = 'Y-m-d'; 43 | $empty = new SiteStats(); 44 | 45 | require \dirname(__DIR__, 1) . '/templates/_chart.html.php'; 46 | } 47 | 48 | /** 49 | * Transform chart data into an associative array index by the date propery 50 | */ 51 | private function prepareChartData(array $data): void 52 | { 53 | $this->data = []; 54 | foreach ($data as $tick) { 55 | $this->data[$tick->date->format('Y-m-d')] = $tick; 56 | $this->y_max = \max($this->y_max, $tick->pageviews); 57 | } 58 | } 59 | 60 | private function getMagnitude(): int 61 | { 62 | $n = $this->y_max; 63 | 64 | if ($n < 10) { 65 | return 10; 66 | } 67 | 68 | if ($n > 100000) { 69 | return (int) \ceil($n / 10000.0) * 10000; 70 | } 71 | 72 | $e = \floor(\log10($n)); 73 | $pow = \pow(10, $e); 74 | return (int) (\ceil($n / $pow) * $pow); 75 | } 76 | } 77 | -------------------------------------------------------------------------------- /tests/Controller/CollectControllerTest.php: -------------------------------------------------------------------------------- 1 | request('GET', '/collect?d=website.com&p=/about'); 18 | self::assertResponseIsSuccessful(); 19 | 20 | $client->request('GET', '/collect?d=website.com&p=/about&r=https://www.kokoanalytics.com/'); 21 | self::assertResponseIsSuccessful(); 22 | } 23 | 24 | public function testRequestWithoutQueryParameters(): void 25 | { 26 | $client = self::createClient(); 27 | $client->request('GET', '/collect'); 28 | self::assertResponseStatusCodeSame(200); 29 | } 30 | 31 | public function provideMissingQueryParameters(): \Generator 32 | { 33 | yield ['/collect?r=https://www.kokoanalytics.com']; 34 | yield ['/collect?p=/r=https://www.kokoanalytics.com']; 35 | yield ['/collect?d=website.com&r=https://www.kokoanalytics.com']; 36 | } 37 | 38 | /** 39 | * @dataProvider provideMissingQueryParameters 40 | */ 41 | public function testRequestWithMissingQueryParameters(string $url): void 42 | { 43 | $client = self::createClient(); 44 | $client->request('GET', $url); 45 | self::assertResponseStatusCodeSame(200); 46 | } 47 | 48 | 49 | public function provideInvalidQueryParameters(): \Generator 50 | { 51 | yield ['/collect?d=website.com&p=/&r=not-an-url']; 52 | yield ['/collect?d=unexisting-domain.com&p=/']; 53 | yield ['/collect?d=../&p=/']; 54 | } 55 | 56 | /** 57 | * @dataProvider provideInvalidQueryParameters 58 | */ 59 | public function testRequestWithInvalidQueryParameters(string $url): void 60 | { 61 | $client = self::createClient(); 62 | $client->request('GET', $url); 63 | self::assertResponseStatusCodeSame(200); 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /src/Command/DatabaseMigrateCommand.php: -------------------------------------------------------------------------------- 1 | db->getDriverName(); 23 | $migration_files = glob("migrations/{$driver}/*-*.php"); 24 | try { 25 | $version = $this->db->query('SELECT MAX(version) FROM koko_analytics_migrations')->fetchColumn(0); 26 | } catch (Exception) { 27 | $this->db->exec( 28 | "CREATE TABLE koko_analytics_migrations ( 29 | version INT UNSIGNED NOT NULL PRIMARY KEY, 30 | timestamp DATETIME NOT NULL 31 | )" 32 | ); 33 | 34 | $version = 0; 35 | } 36 | 37 | $stmt = $this->db->prepare("INSERT INTO koko_analytics_migrations (version, timestamp) VALUES (:version, :timestamp);"); 38 | 39 | foreach ($migration_files as $migration_file) { 40 | // extract migration version from filename 41 | $migration_filename = basename($migration_file); 42 | $migration_version = (int) explode("-", $migration_filename)[0]; 43 | 44 | // skip migration if already executed 45 | if ($migration_version <= $version) { 46 | continue; 47 | } 48 | 49 | // execute migration 50 | (require $migration_file)($this->db); 51 | 52 | // mark migration as completed 53 | $stmt->execute(["version" => $migration_version, "timestamp" => (new \DateTimeImmutable('now', new \DateTimeZone('UTC')))->format('Y-m-d H:i:s')]); 54 | 55 | $output->writeln("Executed migration file '$migration_file'"); 56 | } 57 | 58 | return Command::SUCCESS; 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /src/Command/DomainCreateCommand.php: -------------------------------------------------------------------------------- 1 | addArgument('name', InputArgument::REQUIRED, 'Name of the domain (without HTTP protocol)') 30 | ->addArgument('user', InputArgument::REQUIRED, 'Email of the user this domain belongs to') 31 | ; 32 | } 33 | 34 | protected function execute(InputInterface $input, OutputInterface $output): int 35 | { 36 | $name = $input->getArgument('name'); 37 | if (strlen($name) < 3 || strlen($name) > 255) { 38 | $output->writeln("Name must be between 3 and 255 characters in length."); 39 | return Command::FAILURE; 40 | } 41 | 42 | if (preg_match('/[^a-zA-Z0-9\.\-]/', $name)) { 43 | $output->writeln("Name of domain can only contain alphanumeric characters, hyphens and dots."); 44 | return Command::FAILURE; 45 | } 46 | 47 | $userEmail = $input->getArgument('user'); 48 | $user = $this->userRepository->getByEmail($userEmail); 49 | if (!$user) { 50 | $output->writeln("No user with email {$userEmail}"); 51 | return Command::FAILURE; 52 | } 53 | 54 | $domain = new Domain(); 55 | $domain->user_id = $user->getId(); 56 | $domain->name = $name; 57 | $this->domainRepository->save($domain); 58 | $this->statRepository->createTables($domain); 59 | return Command::SUCCESS; 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /.github/workflows/test.yml: -------------------------------------------------------------------------------- 1 | name: Build and test 2 | on: push 3 | jobs: 4 | build: 5 | runs-on: ubuntu-24.04 6 | strategy: 7 | matrix: 8 | php-versions: ['8.4'] 9 | steps: 10 | # Install PHP interpreter 11 | - name: Setup PHP 12 | uses: shivammathur/setup-php@v2 13 | with: 14 | php-version: ${{ matrix.php-versions }} 15 | extensions: ctype, iconv, pdo, mbstring, json, xml, zip 16 | 17 | # Checkout source repository 18 | - name: checkout repo 19 | uses: actions/checkout@v3 20 | 21 | - name: Check escaping in templates 22 | run: ./bin/check_templates 23 | 24 | # Check syntax of every PHP source file using PHP interpreter 25 | - run: composer run check-syntax 26 | 27 | # Install project depencencies incl. development dependencies 28 | - name: Get Composer Cache Directory 29 | id: composer-cache 30 | run: | 31 | echo "dir=$(composer config cache-files-dir)" >> $GITHUB_OUTPUT 32 | - uses: actions/cache@v4 33 | with: 34 | path: ${{ steps.composer-cache.outputs.dir }} 35 | key: ${{ runner.os }}-composer-${{ hashFiles('**/composer.lock') }} 36 | restore-keys: | 37 | ${{ runner.os }}-composer- 38 | - run: composer install --no-progress 39 | 40 | # Check codestyle 41 | - run: composer run check-codestyle 42 | 43 | # Run static analysis 44 | # - run: ./vendor/bin/psalm 45 | 46 | # Test app against SQLite database 47 | - run: APP_ENV=test DATABASE_DSN="sqlite:var/db_test.sqlite" php bin/console app:database:migrate 48 | - run: APP_ENV=test DATABASE_DSN="sqlite:var/db_test.sqlite" php bin/console app:database:seed --months=1 49 | - run: APP_ENV=test DATABASE_DSN="sqlite:var/db_test.sqlite" php bin/phpunit 50 | 51 | # Test app against MySQL database 52 | - run: sudo systemctl start mysql.service 53 | - run: sudo mysql -uroot -proot -e 'CREATE DATABASE koko_analytics_test;' 54 | - run: APP_ENV=test DATABASE_DSN="mysql:dbname=koko_analytics_test;host=127.0.0.1" php bin/console app:database:migrate 55 | - run: APP_ENV=test DATABASE_DSN="mysql:dbname=koko_analytics_test;host=127.0.0.1" php bin/console app:database:seed --months=1 56 | - run: APP_ENV=test DATABASE_DSN="mysql:dbname=koko_analytics_test;host=127.0.0.1" php bin/phpunit 57 | 58 | -------------------------------------------------------------------------------- /tests/SessionManagerTest.php: -------------------------------------------------------------------------------- 1 | generateId($domain, $user_agent, $ip_address); 18 | self::assertNotEmpty($a); 19 | 20 | $b = $s->generateId($domain, $user_agent, $ip_address); 21 | self::assertEquals($a, $b); 22 | 23 | // assert that id changes after rotating seed 24 | $s->rotateSeed(); 25 | $c = $s->generateId($domain, $user_agent, $ip_address); 26 | self::assertNotEquals($b, $c); 27 | } 28 | 29 | public function testRotateSeed(): void 30 | { 31 | $s = new SessionManager(); 32 | $seed_a = $s->getSeed(); 33 | 34 | $s->rotateSeed(); 35 | $seed_b = $s->getSeed(); 36 | self::assertNotEquals($seed_a, $seed_b); 37 | } 38 | 39 | public function testGetSeed(): void 40 | { 41 | $s = new SessionManager(); 42 | $seed = $s->getSeed(); 43 | self::assertNotEmpty($seed); 44 | } 45 | 46 | public function testGetVisitedPages(): void 47 | { 48 | $s = new SessionManager(); 49 | $user_agent = "Mozilla/5.0 (X11; Linux x86_64; rv:128.0) Gecko/20100101 Firefox/128.0"; 50 | $ip_address = '127.0.0.1'; 51 | $domain = 'website.com'; 52 | $id = $s->generateId($domain, $user_agent, $ip_address); 53 | 54 | self::assertEquals([], $s->getVisitedPages($id)); 55 | } 56 | 57 | public function testAddVisitedPage(): void 58 | { 59 | $s = new SessionManager(); 60 | $user_agent = "Mozilla/5.0 (X11; Linux x86_64; rv:128.0) Gecko/20100101 Firefox/128.0"; 61 | $ip_address = '127.0.0.1'; 62 | $domain = 'website.com'; 63 | $id = $s->generateId($domain, $user_agent, $ip_address); 64 | $s->addVisitedPage($id, '/about'); 65 | self::assertEquals(["/about"], $s->getVisitedPages($id)); 66 | } 67 | 68 | public function testPurge(): void 69 | { 70 | $s = new SessionManager(); 71 | $d = new Domain(); 72 | $s->purge($d); 73 | 74 | // we're not actually testing anything here 75 | // but still make sure the method above gets exercised 76 | self::assertTrue(true); 77 | } 78 | } 79 | -------------------------------------------------------------------------------- /composer.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "koko-analytics/koko-analytics", 3 | "description": "Open-source and privacy friendly website analytics", 4 | "type": "project", 5 | "license": "AGPL-3.0-or-later", 6 | "minimum-stability": "stable", 7 | "prefer-stable": true, 8 | "require": { 9 | "php": ">=8.4", 10 | "ext-ctype": "*", 11 | "ext-iconv": "*", 12 | "ext-json": "*", 13 | "ext-pdo": "*", 14 | "symfony/console": "7.3.*", 15 | "symfony/dotenv": "7.3.*", 16 | "symfony/flex": "^2.8.2", 17 | "symfony/framework-bundle": "7.3.*", 18 | "symfony/runtime": "7.3.*", 19 | "symfony/yaml": "7.3.*" 20 | }, 21 | "config": { 22 | "allow-plugins": { 23 | "php-http/discovery": true, 24 | "symfony/flex": true, 25 | "symfony/runtime": true 26 | }, 27 | "bump-after-update": true, 28 | "sort-packages": true 29 | }, 30 | "autoload": { 31 | "psr-4": { 32 | "App\\": "src/" 33 | } 34 | }, 35 | "autoload-dev": { 36 | "psr-4": { 37 | "App\\Tests\\": "tests/" 38 | } 39 | }, 40 | "replace": { 41 | "symfony/polyfill-ctype": "*", 42 | "symfony/polyfill-iconv": "*", 43 | "symfony/polyfill-php72": "*", 44 | "symfony/polyfill-php73": "*", 45 | "symfony/polyfill-php74": "*", 46 | "symfony/polyfill-php80": "*", 47 | "symfony/polyfill-php81": "*", 48 | "symfony/polyfill-php82": "*", 49 | "symfony/polyfill-php83": "*", 50 | "symfony/polyfill-php84": "*" 51 | }, 52 | "scripts": { 53 | "auto-scripts": { 54 | "cache:clear": "symfony-cmd", 55 | "assets:install %PUBLIC_DIR%": "symfony-cmd" 56 | }, 57 | "post-install-cmd": [ 58 | "@auto-scripts" 59 | ], 60 | "post-update-cmd": [ 61 | "@auto-scripts" 62 | ], 63 | "check-syntax": "find . -name '*.php' -not -path './vendor/*' -not -path './var/*' -print0 | xargs -0 -n1 php --define error_reporting=-1 -l", 64 | "check-codestyle": "vendor/bin/phpcs -sn" 65 | }, 66 | "conflict": { 67 | "symfony/symfony": "*" 68 | }, 69 | "extra": { 70 | "symfony": { 71 | "allow-contrib": false, 72 | "require": "7.3.*" 73 | } 74 | }, 75 | "require-dev": { 76 | "phpunit/phpunit": "^9.6.29", 77 | "squizlabs/php_codesniffer": "^3.13.4", 78 | "symfony/browser-kit": "7.3.*", 79 | "symfony/css-selector": "7.3.*", 80 | "symfony/phpunit-bridge": "^7.3.4" 81 | } 82 | } 83 | -------------------------------------------------------------------------------- /templates/_chart.html.php: -------------------------------------------------------------------------------- 1 |
2 | 3 | 4 | 0 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | format($date_format); ?> 13 | format($date_format); ?> 14 | 15 | 29 | 30 | 46 |
id = (int) $data['id']; 21 | $domain->user_id = (int) $data['user_id']; 22 | $domain->name = $data['name']; 23 | $domain->timezone = $data['timezone']; 24 | $domain->excluded_ip_addresses = array_filter(array_map('trim', explode("\n", trim($data['excluded_ip_addresses'])))); 25 | $domain->purge_treshold = (int) $data['purge_treshold']; 26 | return $domain; 27 | } 28 | 29 | /** 30 | * @return Domain[] 31 | */ 32 | public function getAll(): array 33 | { 34 | $stmt = $this->db->prepare("SELECT * FROM koko_analytics_domains"); 35 | $stmt->execute(); 36 | $result = $stmt->fetchAll(\PDO::FETCH_ASSOC); 37 | return array_map([$this, 'hydrate'], $result); 38 | } 39 | 40 | /** 41 | * @return Domain[] 42 | */ 43 | public function getAllByUser(User $user): array 44 | { 45 | $stmt = $this->db->prepare("SELECT * FROM koko_analytics_domains WHERE user_id = ?"); 46 | $stmt->execute([$user->getId()]); 47 | $result = $stmt->fetchAll(\PDO::FETCH_ASSOC); 48 | return array_map([$this, 'hydrate'], $result); 49 | } 50 | 51 | public function getByName(string $name): ?Domain 52 | { 53 | $stmt = $this->db->prepare("SELECT * FROM koko_analytics_domains WHERE name = ? LIMIT 1"); 54 | $stmt->execute([$name]); 55 | $obj = $stmt->fetch(\PDO::FETCH_ASSOC); 56 | return $obj ? $this->hydrate($obj) : null; 57 | } 58 | 59 | public function save(Domain $domain): void 60 | { 61 | $domain->id ? $this->update($domain) : $this->insert($domain); 62 | } 63 | 64 | protected function update(Domain $domain): void 65 | { 66 | $this->db->prepare( 67 | "UPDATE koko_analytics_domains SET user_id = ?, name = ?, timezone = ?, purge_treshold = ?, excluded_ip_addresses = ? WHERE id = ?" 68 | )->execute([$domain->user_id, $domain->name, $domain->timezone, $domain->purge_treshold, join("\n", $domain->excluded_ip_addresses), $domain->id]); 69 | } 70 | 71 | protected function insert(Domain $domain): void 72 | { 73 | $this->db->prepare( 74 | "INSERT INTO koko_analytics_domains (user_id, name, timezone, purge_treshold, excluded_ip_addresses) VALUES (?, ?, ?, ?, ?)" 75 | )->execute([$domain->user_id, $domain->name, $domain->timezone, $domain->purge_treshold, join("\n", $domain->excluded_ip_addresses)]); 76 | $domain->id = (int) $this->db->lastInsertId(); 77 | } 78 | 79 | public function delete(Domain $domain): void 80 | { 81 | $this->db->prepare( 82 | "DELETE FROM koko_analytics_domains WHERE id = ?" 83 | )->execute([$domain->id]); 84 | $domain->id = null; 85 | } 86 | 87 | public function reset(): void 88 | { 89 | $this->db->exec("DELETE FROM koko_analytics_domains"); 90 | } 91 | } 92 | -------------------------------------------------------------------------------- /tests/SmokeTest.php: -------------------------------------------------------------------------------- 1 | request('GET', $url); 38 | $this->assertResponseRedirects(); 39 | } 40 | 41 | /** 42 | * @dataProvider provideDashboardUrls 43 | */ 44 | public function testProtectedPageIsSuccessful($url): void 45 | { 46 | /** @var KernelBrowser */ 47 | $client = self::createClient(); 48 | 49 | /** @var \App\Repository\UserRepository */ 50 | $userRepository = self::getContainer()->get(UserRepository::class); 51 | if (! ($user = $userRepository->getByEmail('test@kokoanalytics.com'))) { 52 | $user = new User(); 53 | $user->setEmail('test@kokoanalytics.com'); 54 | $user->setPassword(''); 55 | $userRepository->save($user); 56 | } 57 | 58 | /** @var DomainRepository */ 59 | $domainRepository = self::getContainer()->get(DomainRepository::class); 60 | $domainRepository->reset(); 61 | 62 | $domain = new Domain(); 63 | $domain->user_id = $user->getId(); 64 | $domain->name = 'smoke-test.com'; 65 | $domainRepository->save($domain); 66 | 67 | /** @var StatRepository */ 68 | $statRepository = self::getContainer()->get(StatRepository::class); 69 | $statRepository->createTables($domain); 70 | 71 | /** @var Session */ 72 | $session = self::getContainer()->get('session.factory')->createSession(); 73 | $session->set('user', $user); 74 | $session->save(); 75 | $domains = array_unique(array_map(fn (Cookie $cookie) => $cookie->getName() === $session->getName() ? $cookie->getDomain() : '', $client->getCookieJar()->all())) ?: ['']; 76 | foreach ($domains as $domain) { 77 | $cookie = new Cookie($session->getName(), $session->getId(), null, null, $domain); 78 | $client->getCookieJar()->set($cookie); 79 | } 80 | 81 | $client->request('GET', $url); 82 | 83 | $this->assertResponseIsSuccessful(); 84 | $this->assertSelectorExists('.chart'); 85 | $this->assertSelectorExists('.table'); 86 | } 87 | } 88 | -------------------------------------------------------------------------------- /src/Dates.php: -------------------------------------------------------------------------------- 1 | format('w') === $week_starts_on) { 14 | return $dt; 15 | } 16 | 17 | $dt = $dt->modify("last sunday, +{$week_starts_on} days"); 18 | if ($dt === false) { 19 | throw new InvalidArgumentException("Could not set start of week on DateTime object"); 20 | } 21 | return $dt; 22 | } 23 | 24 | public function getDateRange(string $range, \DateTimeImmutable $now = new \DateTimeImmutable('now', new \DateTimeZone('UTC')), int $start_of_week = 0): array 25 | { 26 | switch ($range) { 27 | case 'today': 28 | return [ 29 | $now->modify('today midnight'), 30 | $now->modify('tomorrow midnight, -1 second') 31 | ]; 32 | break; 33 | case 'yesterday': 34 | return [ 35 | $now->modify('yesterday midnight'), 36 | $now->modify('today midnight, -1 second') 37 | ]; 38 | break; 39 | case 'this_week': 40 | $start = $this->getFirstDayOfWeek($now, $start_of_week); 41 | return [ 42 | $start, 43 | $start->modify('+7 days, midnight, -1 second') 44 | ]; 45 | break; 46 | case 'last_week': 47 | $start = $this->getFirstDayOfWeek($now, $start_of_week)->modify('-7 days'); 48 | return [ 49 | $start, 50 | $start->modify('+7 days, midnight, -1 second') 51 | ]; 52 | break; 53 | case 'last_14_days': 54 | return [ 55 | $now->modify('-14 days'), 56 | $now->modify('tomorrow midnight, -1 second') 57 | ]; 58 | break; 59 | default: 60 | case 'last_28_days': 61 | return [ 62 | $now->modify('-28 days'), 63 | $now->modify('tomorrow midnight, -1 second') 64 | ]; 65 | break; 66 | case 'this_month': 67 | return [ 68 | $now->modify('first day of this month'), 69 | $now->modify('last day of this month') 70 | ]; 71 | break; 72 | case 'last_month': 73 | return [ 74 | $now->modify('first day of last month, midnight'), 75 | $now->modify('last day of last month') 76 | ]; 77 | break; 78 | case 'this_year': 79 | return [ 80 | $now->setDate((int) $now->format('Y'), 1, 1), 81 | $now->setDate((int) $now->format('Y'), 12, 31), 82 | ]; 83 | break; 84 | case 'last_year': 85 | return [ 86 | $now->setDate((int) $now->format('Y') - 1, 1, 1), 87 | $now->setDate((int) $now->format('Y') - 1, 12, 31), 88 | ]; 89 | break; 90 | } 91 | 92 | throw new InvalidArgumentException("Invalid date range: {$range}"); 93 | } 94 | } 95 | -------------------------------------------------------------------------------- /src/SessionManager.php: -------------------------------------------------------------------------------- 1 | getSeed(); 22 | return \hash("xxh64", "{$seed}-{$domain}-{$user_agent}-{$ip_address}", false); 23 | } 24 | 25 | public function purge(Domain $domain): void 26 | { 27 | $session_directory = $this->getStorageDirectory(); 28 | $midnight = (new \DateTimeImmutable('today, midnight', new \DateTimeZone($domain->timezone)))->getTimestamp(); 29 | 30 | // clean all session files older than 6 hours 31 | $files = \scandir("{$session_directory}", SCANDIR_SORT_NONE); 32 | $ignored_files = [".", "..", "seed.txt"]; 33 | foreach ($files as $filename) { 34 | if (in_array($filename, $ignored_files)) { 35 | continue; 36 | } 37 | 38 | $filename = "{$session_directory}/$filename"; 39 | if (\filemtime($filename) < $midnight) { 40 | \unlink($filename); 41 | } 42 | } 43 | 44 | // rotate seed for hashing every night at midnight 45 | $seed_filename = $this->getSeedFilename(); 46 | if (!\is_file($seed_filename) || \filemtime($seed_filename) < $midnight) { 47 | $this->rotateSeed(); 48 | } 49 | } 50 | 51 | public function getStorageDirectory(): string 52 | { 53 | static $session_directory; 54 | 55 | if ($session_directory === null) { 56 | $session_directory = \dirname(__DIR__, 1) . '/var/sessions'; 57 | if (!\is_dir($session_directory)) { 58 | \mkdir($session_directory, 0755); 59 | } 60 | } 61 | 62 | return $session_directory; 63 | } 64 | 65 | public function getSeed(): string 66 | { 67 | $filename = $this->getSeedFilename(); 68 | if (!\is_file($filename)) { 69 | $this->rotateSeed(); 70 | } 71 | 72 | return \file_get_contents($filename); 73 | } 74 | 75 | public function getSeedFilename(): string 76 | { 77 | return "{$this->getStorageDirectory()}/seed.txt"; 78 | } 79 | 80 | public function rotateSeed(): void 81 | { 82 | $seed = \bin2hex(\random_bytes(16)); 83 | \file_put_contents($this->getSeedFilename(), $seed); 84 | } 85 | 86 | public function getVisitedPages(string $id): array 87 | { 88 | $session_filename = "{$this->getStorageDirectory()}/$id"; 89 | if (! \is_file($session_filename)) { 90 | return []; 91 | } 92 | 93 | // TODO: This should use domain timezone 94 | if (\filemtime($session_filename) < (new DateTimeImmutable('today, midnight'))->getTimestamp()) { 95 | \unlink($session_filename); 96 | return []; 97 | } 98 | 99 | return \file($session_filename, FILE_IGNORE_NEW_LINES); 100 | } 101 | 102 | public function addVisitedPage(string $id, string $page): void 103 | { 104 | $session_filename = "{$this->getStorageDirectory()}/$id"; 105 | \file_put_contents($session_filename, $page . PHP_EOL, FILE_APPEND); 106 | } 107 | } 108 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Koko Analytics 2 | 3 | > [!NOTE] 4 | > This project is still in development. While functional, we can't guarantee not introducing any breaking chances until we release an official version 1. 5 | 6 | Koko Analytics is a PHP application that you can self-host to provide you with simple, open-source, lightweight (< 1 KB) and privacy-friendly website analytics. 7 | 8 | It aims to be an alternative to Google Analytics for a lot of websites, providing you with the most important metrics while respecting the privacy of your visitors. Nothing about individual visitors is tracked, only aggregated counts. 9 | 10 |
11 | Screenshot of the Koko Analytics standalone dashboard 12 |
Screenshot of the Koko Analytics dashboard.
13 |
14 | 15 | 16 | ## Features 17 | 18 | - Compliance: GDPR and CCPA Compliant by design. 19 | - Local: No external services. 20 | - Anonymous: No personal information or anything visitor specific is tracked. 21 | - No cookies: No cookies or other identifiers are used and/or stored. 22 | - Fast: Handles thousands of daily visitors or sudden bursts of traffic without breaking a sweat. 23 | - Lightweight: The tracking script is < 1 kB. 24 | - Storage efficient: A year worth of data takes up less than 5 MB of database storage. 25 | - Cached: Fully compatible with pages served from server or browser caches. 26 | - Open-source: GNU AGPLv3 licensed. 27 | 28 | > [!TIP] 29 | > There is a WordPress plugin which offers a lof of the same functionality as this project: https://github.com/ibericode/koko-analytics 30 | 31 | ## Installation 32 | 33 | To install Koko Analytics you will need a server with at least the following requirements: 34 | 35 | 36 | ### Requirements 37 | 38 | - PHP 8.2 or higher. 39 | - SQLite or MySQL database. 40 | 41 | Koko Analytics runs on a traditional LAMP stack. It aims to run alongside whatever software you already have running while consuming minimal resources. There is no need to spin-up an OLAP database just to provide you with some metrics. 42 | 43 | 44 | ### Deployment 45 | 46 | First, read through [deploying a Symfony application](https://symfony.com/doc/current/deployment.html) for a general overview on what to expect in deploying Koko Analytics. 47 | 48 | 1. Upload the source code to the server on which you want to run Koko Analytics. 49 | 1. Use Composer to install dependencies: `composer install --no-dev --optimize-autoloader` 50 | 1. Create a local configuration file: `cp .env .env.local` 51 | 1. In `.env.local`, update `APP_SECRET` and the various `DATABASE_` entries. 52 | 1. Run `php bin/console app:database:migrate` to initialize the database. 53 | 1. Configure your webserver to point all requests to `public/index.php` 54 | 1. Run `php bin/console app:user:create ` to register a new user. 55 | 56 | You can then create dashboards for each domain you want to track from the user interface. 57 | 58 | #### Setting up the server cronjob 59 | 60 | The Koko Analytics application needs a single cronjob for persisting collected statistics from the temporary buffer files (optimized for writing) to permanent storage (optimized for querying): 61 | 62 | ```sh 63 | * * * * * cd /path/to/your/application && bin/console app:aggregate 64 | ``` 65 | 66 | ### Tracking snippet 67 | 68 | To start collecting visitor statistics for any website, deploy this application to a suitable location and then add the following tracking snippet to your pages. 69 | 70 | ```html 71 | 83 | ``` 84 | 85 | ## License 86 | 87 | Koko Analytics is open-source software using the GNU AGPLv3 license. 88 | -------------------------------------------------------------------------------- /templates/settings.html.php: -------------------------------------------------------------------------------- 1 | partial('_header.html.php', [ 'title' => 'Settings - Koko Analytics']); ?> 2 | 3 |
4 |

← Back to analytics dashboard.

5 | 6 |

Settings

7 |

Configuration settings for e($domain->name); ?>.

8 | 9 |
10 | 11 | 12 | 13 | 14 | 22 | 23 | 24 | 25 | 32 | 33 | 34 | 35 | 36 | 40 | 41 | 42 | 43 | 44 | 45 | 46 |
15 | 20 |
Select your site's timezone.
21 |
26 | 27 |
28 | Enter a list of IP addresses to ignore. Separate addresses by a new line. 29 | Your current IP address is 30 |
31 |
37 | 38 |
After how many days should data be purged?
39 |
47 |
48 | 49 |
50 |

Delete domain

51 |

You can completely remove this domain and all of its data using the button below.

52 |
53 | 54 |
55 |
56 | 57 |
58 |

Tracking snippet

59 |

Start recording statistics for this domain by adding the following tracking snippet to your pages.

60 |
<script>
61 | (function(o, c) {
62 |   window[o] = c;
63 |   var s = document.createElement('script');
64 |   s.defer = true;
65 |   s.src = [c.url, '/', o, '.js'].join('');
66 |   document.body.appendChild(s);
67 | })('ka', {
68 |   url: 'generateUrl('app_dashboard_list', [], 0), '/') ?>',
69 |   domain: 'e($domain->name) ?>'
70 | })
71 | </script>
72 |
73 | 74 | 75 |
76 | 77 | -------------------------------------------------------------------------------- /src/Normalizer.php: -------------------------------------------------------------------------------- 1 | 1, 'p' => 1, 'tag' => 1, 'cat' => 1, 'product' => 1, 'attachment_id' => 1, 's' => 1])); 30 | 31 | // trim trailing question mark & replace url with new sanitized url 32 | $value = rtrim($value, '?'); 33 | } 34 | 35 | if (str_ends_with($value, '/amp/')) { 36 | $value = substr($value, 0, strlen($value) - 4); 37 | } 38 | 39 | return $value; 40 | } 41 | 42 | public function referrer($value): string 43 | { 44 | if (!$value) { 45 | return ''; 46 | } 47 | 48 | // lowercase referrer 49 | $value = strtolower($value); 50 | 51 | // take first 255 chars 52 | $value = substr($value, 0, 255); 53 | 54 | // aggregate certain sources into a single entry 55 | static $aggregations = [ 56 | // replace most android apps with their web-equivalent 57 | '/^android-app:\/\/(\w{2,3})(\.www)?\.(\w+).*/' => 'https://$3.$1', 58 | '/^android-app:\/\/m\.facebook\.com/' => 'https://facebook.com', 59 | 60 | // popular iOS apps 61 | '/^ios-app:\/\/429047995.*/' => 'https://pinterest.com', 62 | '/^ios-app:\/\/1064216828.*/' => 'https://reddit.com', 63 | '/^ios-app:\/\/284882215.*/' => 'https://facebook.com', 64 | '/^ios-app:\/\/389801252.*/' => 'https://instagram.com', 65 | 66 | // popular websites 67 | '/^https?:\/\/(?:www\.)?(google|bing|ecosia)\.([a-z]{2,4}(?:\.[a-z]{2,4})?)(?:\/search|\/url)?/' => 'https://$1.$2', 68 | '/^https?:\/\/(?:[a-z-]+\.)?l?facebook\.com(?:\/l\.php)?/' => 'https://facebook.com', 69 | '/^https?:\/\/(?:[a-z-]+\.)?l?instagram\.com(?:\/l\.php)?/' => 'https://instagram.com', 70 | '/^https?:\/\/(?:[a-z-]+\.)?linkedin\.com\/feed.*/' => 'https://linkedin.com', 71 | '/^https?:\/\/(?:[a-z-]+\.)?pinterest\.com/' => 'https://pinterest.com', 72 | '/^https?:\/\/(?:[a-z-]+\.)?baidu\.com.*/' => 'https://baidu.com', 73 | '/^https?:\/\/(?:[a-z-]+\.)?yandex\.ru\/.*/' => 'https://yandex.ru', 74 | '/^https?:\/\/(?:[a-z-]+\.)?search\.yahoo\.com\/.*/' => 'https://search.yahoo.com', 75 | '/^https?:\/\/(?:[a-z-]+\.)?reddit\.com.*/' => 'https://reddit.com', 76 | '/^https?:\/\/(?:[a-z0-9]{1,8}\.)+sendib(?:m|t)[0-9]\.com.*/' => 'https://brevo.com', 77 | ]; 78 | $normalized_value = (string) preg_replace(array_keys($aggregations), array_values($aggregations), $value, 1); 79 | if (preg_last_error() === PREG_NO_ERROR) { 80 | $value = $normalized_value; 81 | } 82 | 83 | // limit resulting value to just host 84 | $url_parts = parse_url($value); 85 | if ($url_parts === false || empty($url_parts['host'])) { 86 | return ''; 87 | } 88 | $value = $url_parts['host']; 89 | 90 | // strip www. prefix 91 | if (str_starts_with($value, 'www.')) { 92 | $value = substr($value, 4); 93 | } 94 | 95 | // add path if domain is whitelisted 96 | $whitelisted_domains = ['kokoanalytics.com', 'github.com']; 97 | if (in_array($value, $whitelisted_domains) && !empty($url_parts['path']) && $url_parts['path'] !== '/') { 98 | $value .= $url_parts['path']; 99 | } 100 | 101 | return $value; 102 | } 103 | } 104 | -------------------------------------------------------------------------------- /src/Controller/CollectController.php: -------------------------------------------------------------------------------- 1 | 'text/plain', 23 | 'Cache-Control' => 'no-cache, must-revalidate, max-age=0' 24 | ]; 25 | 26 | // do nothing if empty user-agent or looks like bot/crawler/spider 27 | $user_agent = $request->headers->get('User-Agent', ''); 28 | if (!$user_agent || \preg_match("/bot|crawl|spider|seo|lighthouse|facebookexternalhit|preview/", \strtolower($user_agent))) { 29 | return new Response('', 200, $headers); 30 | } 31 | 32 | $domain = $request->request->getString('d'); 33 | $path = $request->request->getString('p'); 34 | $referrer = $request->request->getString('r', ''); 35 | 36 | // do nothing if required param is missing 37 | if (! $domain || ! $path) { 38 | return new Response('', 200, $headers); 39 | } 40 | 41 | // validate path 42 | if ($path[0] !== '/' || preg_match('/[^a-zA-Z0-9\-\+\=\/\#\&\?\%]/', $path)) { 43 | return new Response('', 200, $headers); 44 | } 45 | 46 | // validate referrer 47 | $referrer = $referrer === '' ? '' : \filter_var($referrer, FILTER_VALIDATE_URL); 48 | if ($referrer === false) { 49 | return new Response('', 200, $headers); 50 | } 51 | 52 | 53 | // limit string inputs to a maximum of 255 chars 54 | $normalizer = new Normalizer(); 55 | $path = $normalizer->path($path); 56 | $referrer = $normalizer->referrer($referrer); 57 | $domain = \substr($domain, 0, 255); 58 | 59 | // validate domain param 60 | if (\preg_match('/[^a-zA-Z0-9\.\-]/', $domain)) { 61 | return new Response('', 200, $headers); 62 | } 63 | 64 | $buffer_filename = \dirname(__DIR__, 2) . "/var/buffer-{$domain}"; 65 | 66 | // if filename does not exist: domain is invalid 67 | if (!\is_file($buffer_filename)) { 68 | return new Response('', 200, $headers); 69 | } 70 | 71 | // check if IP address is on ignore list 72 | if ($this->isIgnoredIpAddress($domain, $request->getClientIp())) { 73 | return new Response('', 200, $headers); 74 | } 75 | 76 | // determine uniqueness of request to this path 77 | [$new_visitor, $unique_pageview ] = $this->determineUniqueness($request, $domain, $path); 78 | 79 | // write to buffer file 80 | \file_put_contents($buffer_filename, \serialize([$path, $new_visitor, $unique_pageview, $referrer]) . PHP_EOL, FILE_APPEND); 81 | 82 | return new Response('', 200, $headers); 83 | } 84 | 85 | private function determineUniqueness(Request $request, string $domain, string $path): array 86 | { 87 | $session_manager = new SessionManager(); 88 | $user_agent = $request->headers->get('User-Agent', ''); 89 | $ip_address = $request->getClientIp(); 90 | 91 | $id = $session_manager->generateId($domain, $user_agent, $ip_address); 92 | $pages_visited = $session_manager->getVisitedPages($id); 93 | $new_visitor = \count($pages_visited) === 0 ? 1 : 0; 94 | $unique_pageview = \in_array($path, $pages_visited, true) ? 0 : 1; 95 | 96 | if ($unique_pageview) { 97 | $session_manager->addVisitedPage($id, $path); 98 | } 99 | 100 | return [$new_visitor, $unique_pageview]; 101 | } 102 | 103 | private function isIgnoredIpAddress(string $domain, string $ip): bool 104 | { 105 | $filename = dirname(__DIR__, 2) . "/var/{$domain}-ignored-ips.txt"; 106 | $ignoreList = is_file($filename) ? (file($filename, FILE_IGNORE_NEW_LINES) ?: []) : []; 107 | return in_array($ip, $ignoreList); 108 | } 109 | } 110 | -------------------------------------------------------------------------------- /public/dashboard.js: -------------------------------------------------------------------------------- 1 | /* DATEPICKER */ 2 | // update date_start and date_end 's whenever a preset is selected 3 | var datePresetSelect = document.querySelector('#date-range-input'); 4 | var dateStartInput = document.querySelector('#date-start-input'); 5 | var dateEndInput = document.querySelector('#date-end-input'); 6 | datePresetSelect && datePresetSelect.addEventListener('change', function() { 7 | dateStartInput.disabled = true; 8 | dateEndInput.disabled = true; 9 | this.form.submit(); 10 | }); 11 | 12 | // set 61 | 62 | $label) { ?> 63 | 64 | 65 | 66 | 67 |
68 |
69 | 70 | 71 |
72 |
73 | 74 | 75 |
76 |
77 |
78 | 79 |
80 | 81 | 82 | 83 | 84 | 85 |
86 | Path = e($path) ?> 87 | 88 |
89 | 90 | 91 | 92 |
93 | 98 | 99 | 100 |
101 | 102 | 103 | 104 | visitors == 0 ? 0 : ($totals->visitors / $totals_previous->visitors) - 1; 107 | $pageviews_change = $totals_previous->pageviews == 0 ? 0 : ($totals->pageviews / $totals_previous->pageviews) - 1; 108 | ?> 109 | 110 | 111 | 112 | 113 | 120 | 125 | 126 | 127 | 128 | 135 | 140 | 141 | 142 | 143 | 146 | 149 | 150 | 151 |
Total visitors 114 |
visitors); ?> 115 | 116 | 117 | 118 |
119 |
121 | visitors - $totals_previous->visitors)); ?> 122 | visitors > $totals_previous->visitors ? 'more' : 'less'; ?> 123 | than in previous period 124 |
Total pageviews 129 |
pageviews); ?> 130 | 131 | 132 | 133 |
134 |
136 | pageviews - $totals_previous->pageviews)); ?> 137 | pageviews > $totals_previous->pageviews ? 'more' : 'less'; ?> 138 | than in previous period 139 |
Realtime pageviews 144 | 145 | 147 | pageviews in the last hour 148 |
152 | 153 | 154 |
155 | render(); ?> 156 |
157 | 158 |
159 | 160 |
161 | 162 | 163 | 164 | 165 | 166 | 167 | 168 | 169 | 170 | 171 | $p) { ?> 172 | 173 | 174 | 175 | 176 | 177 | 178 | 179 | 180 | 181 | 182 | 183 | 184 | 185 |
#PageVisitorsPageviews
e($p->url); ?>visitors); ?>pageviews); ?>
There is nothing here. Yet!
186 |
187 | 188 | 189 |
190 | 191 | 192 | 193 | 194 | 195 | 196 | 197 | 198 | 199 | 200 | $p) : ?> 201 | 202 | 203 | 204 | 205 | 206 | 207 | 208 | 209 | 210 | 211 | 212 | 213 | 214 |
#ReferrerVisitorsPageviews
e(get_referrer_url_label($p->url)); ?>visitors); ?>pageviews); ?>
There is nothing here. Yet!
215 |
216 |
217 | 218 | partial('_footer.html.php', []); ?> 219 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU AFFERO GENERAL PUBLIC LICENSE 2 | Version 3, 19 November 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU Affero General Public License is a free, copyleft license for 11 | software and other kinds of works, specifically designed to ensure 12 | cooperation with the community in the case of network server software. 13 | 14 | The licenses for most software and other practical works are designed 15 | to take away your freedom to share and change the works. By contrast, 16 | our General Public Licenses are intended to guarantee your freedom to 17 | share and change all versions of a program--to make sure it remains free 18 | software for all its users. 19 | 20 | When we speak of free software, we are referring to freedom, not 21 | price. Our General Public Licenses are designed to make sure that you 22 | have the freedom to distribute copies of free software (and charge for 23 | them if you wish), that you receive source code or can get it if you 24 | want it, that you can change the software or use pieces of it in new 25 | free programs, and that you know you can do these things. 26 | 27 | Developers that use our General Public Licenses protect your rights 28 | with two steps: (1) assert copyright on the software, and (2) offer 29 | you this License which gives you legal permission to copy, distribute 30 | and/or modify the software. 31 | 32 | A secondary benefit of defending all users' freedom is that 33 | improvements made in alternate versions of the program, if they 34 | receive widespread use, become available for other developers to 35 | incorporate. Many developers of free software are heartened and 36 | encouraged by the resulting cooperation. However, in the case of 37 | software used on network servers, this result may fail to come about. 38 | The GNU General Public License permits making a modified version and 39 | letting the public access it on a server without ever releasing its 40 | source code to the public. 41 | 42 | The GNU Affero General Public License is designed specifically to 43 | ensure that, in such cases, the modified source code becomes available 44 | to the community. It requires the operator of a network server to 45 | provide the source code of the modified version running there to the 46 | users of that server. Therefore, public use of a modified version, on 47 | a publicly accessible server, gives the public access to the source 48 | code of the modified version. 49 | 50 | An older license, called the Affero General Public License and 51 | published by Affero, was designed to accomplish similar goals. This is 52 | a different license, not a version of the Affero GPL, but Affero has 53 | released a new version of the Affero GPL which permits relicensing under 54 | this license. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | TERMS AND CONDITIONS 60 | 61 | 0. Definitions. 62 | 63 | "This License" refers to version 3 of the GNU Affero General Public License. 64 | 65 | "Copyright" also means copyright-like laws that apply to other kinds of 66 | works, such as semiconductor masks. 67 | 68 | "The Program" refers to any copyrightable work licensed under this 69 | License. Each licensee is addressed as "you". "Licensees" and 70 | "recipients" may be individuals or organizations. 71 | 72 | To "modify" a work means to copy from or adapt all or part of the work 73 | in a fashion requiring copyright permission, other than the making of an 74 | exact copy. The resulting work is called a "modified version" of the 75 | earlier work or a work "based on" the earlier work. 76 | 77 | A "covered work" means either the unmodified Program or a work based 78 | on the Program. 79 | 80 | To "propagate" a work means to do anything with it that, without 81 | permission, would make you directly or secondarily liable for 82 | infringement under applicable copyright law, except executing it on a 83 | computer or modifying a private copy. Propagation includes copying, 84 | distribution (with or without modification), making available to the 85 | public, and in some countries other activities as well. 86 | 87 | To "convey" a work means any kind of propagation that enables other 88 | parties to make or receive copies. Mere interaction with a user through 89 | a computer network, with no transfer of a copy, is not conveying. 90 | 91 | An interactive user interface displays "Appropriate Legal Notices" 92 | to the extent that it includes a convenient and prominently visible 93 | feature that (1) displays an appropriate copyright notice, and (2) 94 | tells the user that there is no warranty for the work (except to the 95 | extent that warranties are provided), that licensees may convey the 96 | work under this License, and how to view a copy of this License. If 97 | the interface presents a list of user commands or options, such as a 98 | menu, a prominent item in the list meets this criterion. 99 | 100 | 1. Source Code. 101 | 102 | The "source code" for a work means the preferred form of the work 103 | for making modifications to it. "Object code" means any non-source 104 | form of a work. 105 | 106 | A "Standard Interface" means an interface that either is an official 107 | standard defined by a recognized standards body, or, in the case of 108 | interfaces specified for a particular programming language, one that 109 | is widely used among developers working in that language. 110 | 111 | The "System Libraries" of an executable work include anything, other 112 | than the work as a whole, that (a) is included in the normal form of 113 | packaging a Major Component, but which is not part of that Major 114 | Component, and (b) serves only to enable use of the work with that 115 | Major Component, or to implement a Standard Interface for which an 116 | implementation is available to the public in source code form. A 117 | "Major Component", in this context, means a major essential component 118 | (kernel, window system, and so on) of the specific operating system 119 | (if any) on which the executable work runs, or a compiler used to 120 | produce the work, or an object code interpreter used to run it. 121 | 122 | The "Corresponding Source" for a work in object code form means all 123 | the source code needed to generate, install, and (for an executable 124 | work) run the object code and to modify the work, including scripts to 125 | control those activities. However, it does not include the work's 126 | System Libraries, or general-purpose tools or generally available free 127 | programs which are used unmodified in performing those activities but 128 | which are not part of the work. For example, Corresponding Source 129 | includes interface definition files associated with source files for 130 | the work, and the source code for shared libraries and dynamically 131 | linked subprograms that the work is specifically designed to require, 132 | such as by intimate data communication or control flow between those 133 | subprograms and other parts of the work. 134 | 135 | The Corresponding Source need not include anything that users 136 | can regenerate automatically from other parts of the Corresponding 137 | Source. 138 | 139 | The Corresponding Source for a work in source code form is that 140 | same work. 141 | 142 | 2. Basic Permissions. 143 | 144 | All rights granted under this License are granted for the term of 145 | copyright on the Program, and are irrevocable provided the stated 146 | conditions are met. This License explicitly affirms your unlimited 147 | permission to run the unmodified Program. The output from running a 148 | covered work is covered by this License only if the output, given its 149 | content, constitutes a covered work. This License acknowledges your 150 | rights of fair use or other equivalent, as provided by copyright law. 151 | 152 | You may make, run and propagate covered works that you do not 153 | convey, without conditions so long as your license otherwise remains 154 | in force. You may convey covered works to others for the sole purpose 155 | of having them make modifications exclusively for you, or provide you 156 | with facilities for running those works, provided that you comply with 157 | the terms of this License in conveying all material for which you do 158 | not control copyright. Those thus making or running the covered works 159 | for you must do so exclusively on your behalf, under your direction 160 | and control, on terms that prohibit them from making any copies of 161 | your copyrighted material outside their relationship with you. 162 | 163 | Conveying under any other circumstances is permitted solely under 164 | the conditions stated below. Sublicensing is not allowed; section 10 165 | makes it unnecessary. 166 | 167 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 168 | 169 | No covered work shall be deemed part of an effective technological 170 | measure under any applicable law fulfilling obligations under article 171 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 172 | similar laws prohibiting or restricting circumvention of such 173 | measures. 174 | 175 | When you convey a covered work, you waive any legal power to forbid 176 | circumvention of technological measures to the extent such circumvention 177 | is effected by exercising rights under this License with respect to 178 | the covered work, and you disclaim any intention to limit operation or 179 | modification of the work as a means of enforcing, against the work's 180 | users, your or third parties' legal rights to forbid circumvention of 181 | technological measures. 182 | 183 | 4. Conveying Verbatim Copies. 184 | 185 | You may convey verbatim copies of the Program's source code as you 186 | receive it, in any medium, provided that you conspicuously and 187 | appropriately publish on each copy an appropriate copyright notice; 188 | keep intact all notices stating that this License and any 189 | non-permissive terms added in accord with section 7 apply to the code; 190 | keep intact all notices of the absence of any warranty; and give all 191 | recipients a copy of this License along with the Program. 192 | 193 | You may charge any price or no price for each copy that you convey, 194 | and you may offer support or warranty protection for a fee. 195 | 196 | 5. Conveying Modified Source Versions. 197 | 198 | You may convey a work based on the Program, or the modifications to 199 | produce it from the Program, in the form of source code under the 200 | terms of section 4, provided that you also meet all of these conditions: 201 | 202 | a) The work must carry prominent notices stating that you modified 203 | it, and giving a relevant date. 204 | 205 | b) The work must carry prominent notices stating that it is 206 | released under this License and any conditions added under section 207 | 7. This requirement modifies the requirement in section 4 to 208 | "keep intact all notices". 209 | 210 | c) You must license the entire work, as a whole, under this 211 | License to anyone who comes into possession of a copy. This 212 | License will therefore apply, along with any applicable section 7 213 | additional terms, to the whole of the work, and all its parts, 214 | regardless of how they are packaged. This License gives no 215 | permission to license the work in any other way, but it does not 216 | invalidate such permission if you have separately received it. 217 | 218 | d) If the work has interactive user interfaces, each must display 219 | Appropriate Legal Notices; however, if the Program has interactive 220 | interfaces that do not display Appropriate Legal Notices, your 221 | work need not make them do so. 222 | 223 | A compilation of a covered work with other separate and independent 224 | works, which are not by their nature extensions of the covered work, 225 | and which are not combined with it such as to form a larger program, 226 | in or on a volume of a storage or distribution medium, is called an 227 | "aggregate" if the compilation and its resulting copyright are not 228 | used to limit the access or legal rights of the compilation's users 229 | beyond what the individual works permit. Inclusion of a covered work 230 | in an aggregate does not cause this License to apply to the other 231 | parts of the aggregate. 232 | 233 | 6. Conveying Non-Source Forms. 234 | 235 | You may convey a covered work in object code form under the terms 236 | of sections 4 and 5, provided that you also convey the 237 | machine-readable Corresponding Source under the terms of this License, 238 | in one of these ways: 239 | 240 | a) Convey the object code in, or embodied in, a physical product 241 | (including a physical distribution medium), accompanied by the 242 | Corresponding Source fixed on a durable physical medium 243 | customarily used for software interchange. 244 | 245 | b) Convey the object code in, or embodied in, a physical product 246 | (including a physical distribution medium), accompanied by a 247 | written offer, valid for at least three years and valid for as 248 | long as you offer spare parts or customer support for that product 249 | model, to give anyone who possesses the object code either (1) a 250 | copy of the Corresponding Source for all the software in the 251 | product that is covered by this License, on a durable physical 252 | medium customarily used for software interchange, for a price no 253 | more than your reasonable cost of physically performing this 254 | conveying of source, or (2) access to copy the 255 | Corresponding Source from a network server at no charge. 256 | 257 | c) Convey individual copies of the object code with a copy of the 258 | written offer to provide the Corresponding Source. This 259 | alternative is allowed only occasionally and noncommercially, and 260 | only if you received the object code with such an offer, in accord 261 | with subsection 6b. 262 | 263 | d) Convey the object code by offering access from a designated 264 | place (gratis or for a charge), and offer equivalent access to the 265 | Corresponding Source in the same way through the same place at no 266 | further charge. You need not require recipients to copy the 267 | Corresponding Source along with the object code. If the place to 268 | copy the object code is a network server, the Corresponding Source 269 | may be on a different server (operated by you or a third party) 270 | that supports equivalent copying facilities, provided you maintain 271 | clear directions next to the object code saying where to find the 272 | Corresponding Source. Regardless of what server hosts the 273 | Corresponding Source, you remain obligated to ensure that it is 274 | available for as long as needed to satisfy these requirements. 275 | 276 | e) Convey the object code using peer-to-peer transmission, provided 277 | you inform other peers where the object code and Corresponding 278 | Source of the work are being offered to the general public at no 279 | charge under subsection 6d. 280 | 281 | A separable portion of the object code, whose source code is excluded 282 | from the Corresponding Source as a System Library, need not be 283 | included in conveying the object code work. 284 | 285 | A "User Product" is either (1) a "consumer product", which means any 286 | tangible personal property which is normally used for personal, family, 287 | or household purposes, or (2) anything designed or sold for incorporation 288 | into a dwelling. In determining whether a product is a consumer product, 289 | doubtful cases shall be resolved in favor of coverage. For a particular 290 | product received by a particular user, "normally used" refers to a 291 | typical or common use of that class of product, regardless of the status 292 | of the particular user or of the way in which the particular user 293 | actually uses, or expects or is expected to use, the product. A product 294 | is a consumer product regardless of whether the product has substantial 295 | commercial, industrial or non-consumer uses, unless such uses represent 296 | the only significant mode of use of the product. 297 | 298 | "Installation Information" for a User Product means any methods, 299 | procedures, authorization keys, or other information required to install 300 | and execute modified versions of a covered work in that User Product from 301 | a modified version of its Corresponding Source. The information must 302 | suffice to ensure that the continued functioning of the modified object 303 | code is in no case prevented or interfered with solely because 304 | modification has been made. 305 | 306 | If you convey an object code work under this section in, or with, or 307 | specifically for use in, a User Product, and the conveying occurs as 308 | part of a transaction in which the right of possession and use of the 309 | User Product is transferred to the recipient in perpetuity or for a 310 | fixed term (regardless of how the transaction is characterized), the 311 | Corresponding Source conveyed under this section must be accompanied 312 | by the Installation Information. But this requirement does not apply 313 | if neither you nor any third party retains the ability to install 314 | modified object code on the User Product (for example, the work has 315 | been installed in ROM). 316 | 317 | The requirement to provide Installation Information does not include a 318 | requirement to continue to provide support service, warranty, or updates 319 | for a work that has been modified or installed by the recipient, or for 320 | the User Product in which it has been modified or installed. Access to a 321 | network may be denied when the modification itself materially and 322 | adversely affects the operation of the network or violates the rules and 323 | protocols for communication across the network. 324 | 325 | Corresponding Source conveyed, and Installation Information provided, 326 | in accord with this section must be in a format that is publicly 327 | documented (and with an implementation available to the public in 328 | source code form), and must require no special password or key for 329 | unpacking, reading or copying. 330 | 331 | 7. Additional Terms. 332 | 333 | "Additional permissions" are terms that supplement the terms of this 334 | License by making exceptions from one or more of its conditions. 335 | Additional permissions that are applicable to the entire Program shall 336 | be treated as though they were included in this License, to the extent 337 | that they are valid under applicable law. If additional permissions 338 | apply only to part of the Program, that part may be used separately 339 | under those permissions, but the entire Program remains governed by 340 | this License without regard to the additional permissions. 341 | 342 | When you convey a copy of a covered work, you may at your option 343 | remove any additional permissions from that copy, or from any part of 344 | it. (Additional permissions may be written to require their own 345 | removal in certain cases when you modify the work.) You may place 346 | additional permissions on material, added by you to a covered work, 347 | for which you have or can give appropriate copyright permission. 348 | 349 | Notwithstanding any other provision of this License, for material you 350 | add to a covered work, you may (if authorized by the copyright holders of 351 | that material) supplement the terms of this License with terms: 352 | 353 | a) Disclaiming warranty or limiting liability differently from the 354 | terms of sections 15 and 16 of this License; or 355 | 356 | b) Requiring preservation of specified reasonable legal notices or 357 | author attributions in that material or in the Appropriate Legal 358 | Notices displayed by works containing it; or 359 | 360 | c) Prohibiting misrepresentation of the origin of that material, or 361 | requiring that modified versions of such material be marked in 362 | reasonable ways as different from the original version; or 363 | 364 | d) Limiting the use for publicity purposes of names of licensors or 365 | authors of the material; or 366 | 367 | e) Declining to grant rights under trademark law for use of some 368 | trade names, trademarks, or service marks; or 369 | 370 | f) Requiring indemnification of licensors and authors of that 371 | material by anyone who conveys the material (or modified versions of 372 | it) with contractual assumptions of liability to the recipient, for 373 | any liability that these contractual assumptions directly impose on 374 | those licensors and authors. 375 | 376 | All other non-permissive additional terms are considered "further 377 | restrictions" within the meaning of section 10. If the Program as you 378 | received it, or any part of it, contains a notice stating that it is 379 | governed by this License along with a term that is a further 380 | restriction, you may remove that term. If a license document contains 381 | a further restriction but permits relicensing or conveying under this 382 | License, you may add to a covered work material governed by the terms 383 | of that license document, provided that the further restriction does 384 | not survive such relicensing or conveying. 385 | 386 | If you add terms to a covered work in accord with this section, you 387 | must place, in the relevant source files, a statement of the 388 | additional terms that apply to those files, or a notice indicating 389 | where to find the applicable terms. 390 | 391 | Additional terms, permissive or non-permissive, may be stated in the 392 | form of a separately written license, or stated as exceptions; 393 | the above requirements apply either way. 394 | 395 | 8. Termination. 396 | 397 | You may not propagate or modify a covered work except as expressly 398 | provided under this License. Any attempt otherwise to propagate or 399 | modify it is void, and will automatically terminate your rights under 400 | this License (including any patent licenses granted under the third 401 | paragraph of section 11). 402 | 403 | However, if you cease all violation of this License, then your 404 | license from a particular copyright holder is reinstated (a) 405 | provisionally, unless and until the copyright holder explicitly and 406 | finally terminates your license, and (b) permanently, if the copyright 407 | holder fails to notify you of the violation by some reasonable means 408 | prior to 60 days after the cessation. 409 | 410 | Moreover, your license from a particular copyright holder is 411 | reinstated permanently if the copyright holder notifies you of the 412 | violation by some reasonable means, this is the first time you have 413 | received notice of violation of this License (for any work) from that 414 | copyright holder, and you cure the violation prior to 30 days after 415 | your receipt of the notice. 416 | 417 | Termination of your rights under this section does not terminate the 418 | licenses of parties who have received copies or rights from you under 419 | this License. If your rights have been terminated and not permanently 420 | reinstated, you do not qualify to receive new licenses for the same 421 | material under section 10. 422 | 423 | 9. Acceptance Not Required for Having Copies. 424 | 425 | You are not required to accept this License in order to receive or 426 | run a copy of the Program. Ancillary propagation of a covered work 427 | occurring solely as a consequence of using peer-to-peer transmission 428 | to receive a copy likewise does not require acceptance. However, 429 | nothing other than this License grants you permission to propagate or 430 | modify any covered work. These actions infringe copyright if you do 431 | not accept this License. Therefore, by modifying or propagating a 432 | covered work, you indicate your acceptance of this License to do so. 433 | 434 | 10. Automatic Licensing of Downstream Recipients. 435 | 436 | Each time you convey a covered work, the recipient automatically 437 | receives a license from the original licensors, to run, modify and 438 | propagate that work, subject to this License. You are not responsible 439 | for enforcing compliance by third parties with this License. 440 | 441 | An "entity transaction" is a transaction transferring control of an 442 | organization, or substantially all assets of one, or subdividing an 443 | organization, or merging organizations. If propagation of a covered 444 | work results from an entity transaction, each party to that 445 | transaction who receives a copy of the work also receives whatever 446 | licenses to the work the party's predecessor in interest had or could 447 | give under the previous paragraph, plus a right to possession of the 448 | Corresponding Source of the work from the predecessor in interest, if 449 | the predecessor has it or can get it with reasonable efforts. 450 | 451 | You may not impose any further restrictions on the exercise of the 452 | rights granted or affirmed under this License. For example, you may 453 | not impose a license fee, royalty, or other charge for exercise of 454 | rights granted under this License, and you may not initiate litigation 455 | (including a cross-claim or counterclaim in a lawsuit) alleging that 456 | any patent claim is infringed by making, using, selling, offering for 457 | sale, or importing the Program or any portion of it. 458 | 459 | 11. Patents. 460 | 461 | A "contributor" is a copyright holder who authorizes use under this 462 | License of the Program or a work on which the Program is based. The 463 | work thus licensed is called the contributor's "contributor version". 464 | 465 | A contributor's "essential patent claims" are all patent claims 466 | owned or controlled by the contributor, whether already acquired or 467 | hereafter acquired, that would be infringed by some manner, permitted 468 | by this License, of making, using, or selling its contributor version, 469 | but do not include claims that would be infringed only as a 470 | consequence of further modification of the contributor version. For 471 | purposes of this definition, "control" includes the right to grant 472 | patent sublicenses in a manner consistent with the requirements of 473 | this License. 474 | 475 | Each contributor grants you a non-exclusive, worldwide, royalty-free 476 | patent license under the contributor's essential patent claims, to 477 | make, use, sell, offer for sale, import and otherwise run, modify and 478 | propagate the contents of its contributor version. 479 | 480 | In the following three paragraphs, a "patent license" is any express 481 | agreement or commitment, however denominated, not to enforce a patent 482 | (such as an express permission to practice a patent or covenant not to 483 | sue for patent infringement). To "grant" such a patent license to a 484 | party means to make such an agreement or commitment not to enforce a 485 | patent against the party. 486 | 487 | If you convey a covered work, knowingly relying on a patent license, 488 | and the Corresponding Source of the work is not available for anyone 489 | to copy, free of charge and under the terms of this License, through a 490 | publicly available network server or other readily accessible means, 491 | then you must either (1) cause the Corresponding Source to be so 492 | available, or (2) arrange to deprive yourself of the benefit of the 493 | patent license for this particular work, or (3) arrange, in a manner 494 | consistent with the requirements of this License, to extend the patent 495 | license to downstream recipients. "Knowingly relying" means you have 496 | actual knowledge that, but for the patent license, your conveying the 497 | covered work in a country, or your recipient's use of the covered work 498 | in a country, would infringe one or more identifiable patents in that 499 | country that you have reason to believe are valid. 500 | 501 | If, pursuant to or in connection with a single transaction or 502 | arrangement, you convey, or propagate by procuring conveyance of, a 503 | covered work, and grant a patent license to some of the parties 504 | receiving the covered work authorizing them to use, propagate, modify 505 | or convey a specific copy of the covered work, then the patent license 506 | you grant is automatically extended to all recipients of the covered 507 | work and works based on it. 508 | 509 | A patent license is "discriminatory" if it does not include within 510 | the scope of its coverage, prohibits the exercise of, or is 511 | conditioned on the non-exercise of one or more of the rights that are 512 | specifically granted under this License. You may not convey a covered 513 | work if you are a party to an arrangement with a third party that is 514 | in the business of distributing software, under which you make payment 515 | to the third party based on the extent of your activity of conveying 516 | the work, and under which the third party grants, to any of the 517 | parties who would receive the covered work from you, a discriminatory 518 | patent license (a) in connection with copies of the covered work 519 | conveyed by you (or copies made from those copies), or (b) primarily 520 | for and in connection with specific products or compilations that 521 | contain the covered work, unless you entered into that arrangement, 522 | or that patent license was granted, prior to 28 March 2007. 523 | 524 | Nothing in this License shall be construed as excluding or limiting 525 | any implied license or other defenses to infringement that may 526 | otherwise be available to you under applicable patent law. 527 | 528 | 12. No Surrender of Others' Freedom. 529 | 530 | If conditions are imposed on you (whether by court order, agreement or 531 | otherwise) that contradict the conditions of this License, they do not 532 | excuse you from the conditions of this License. If you cannot convey a 533 | covered work so as to satisfy simultaneously your obligations under this 534 | License and any other pertinent obligations, then as a consequence you may 535 | not convey it at all. For example, if you agree to terms that obligate you 536 | to collect a royalty for further conveying from those to whom you convey 537 | the Program, the only way you could satisfy both those terms and this 538 | License would be to refrain entirely from conveying the Program. 539 | 540 | 13. Remote Network Interaction; Use with the GNU General Public License. 541 | 542 | Notwithstanding any other provision of this License, if you modify the 543 | Program, your modified version must prominently offer all users 544 | interacting with it remotely through a computer network (if your version 545 | supports such interaction) an opportunity to receive the Corresponding 546 | Source of your version by providing access to the Corresponding Source 547 | from a network server at no charge, through some standard or customary 548 | means of facilitating copying of software. This Corresponding Source 549 | shall include the Corresponding Source for any work covered by version 3 550 | of the GNU General Public License that is incorporated pursuant to the 551 | following paragraph. 552 | 553 | Notwithstanding any other provision of this License, you have 554 | permission to link or combine any covered work with a work licensed 555 | under version 3 of the GNU General Public License into a single 556 | combined work, and to convey the resulting work. The terms of this 557 | License will continue to apply to the part which is the covered work, 558 | but the work with which it is combined will remain governed by version 559 | 3 of the GNU General Public License. 560 | 561 | 14. Revised Versions of this License. 562 | 563 | The Free Software Foundation may publish revised and/or new versions of 564 | the GNU Affero General Public License from time to time. Such new versions 565 | will be similar in spirit to the present version, but may differ in detail to 566 | address new problems or concerns. 567 | 568 | Each version is given a distinguishing version number. If the 569 | Program specifies that a certain numbered version of the GNU Affero General 570 | Public License "or any later version" applies to it, you have the 571 | option of following the terms and conditions either of that numbered 572 | version or of any later version published by the Free Software 573 | Foundation. If the Program does not specify a version number of the 574 | GNU Affero General Public License, you may choose any version ever published 575 | by the Free Software Foundation. 576 | 577 | If the Program specifies that a proxy can decide which future 578 | versions of the GNU Affero General Public License can be used, that proxy's 579 | public statement of acceptance of a version permanently authorizes you 580 | to choose that version for the Program. 581 | 582 | Later license versions may give you additional or different 583 | permissions. However, no additional obligations are imposed on any 584 | author or copyright holder as a result of your choosing to follow a 585 | later version. 586 | 587 | 15. Disclaimer of Warranty. 588 | 589 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 590 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 591 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 592 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 593 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 594 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 595 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 596 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 597 | 598 | 16. Limitation of Liability. 599 | 600 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 601 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 602 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 603 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 604 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 605 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 606 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 607 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 608 | SUCH DAMAGES. 609 | 610 | 17. Interpretation of Sections 15 and 16. 611 | 612 | If the disclaimer of warranty and limitation of liability provided 613 | above cannot be given local legal effect according to their terms, 614 | reviewing courts shall apply local law that most closely approximates 615 | an absolute waiver of all civil liability in connection with the 616 | Program, unless a warranty or assumption of liability accompanies a 617 | copy of the Program in return for a fee. 618 | 619 | END OF TERMS AND CONDITIONS 620 | 621 | How to Apply These Terms to Your New Programs 622 | 623 | If you develop a new program, and you want it to be of the greatest 624 | possible use to the public, the best way to achieve this is to make it 625 | free software which everyone can redistribute and change under these terms. 626 | 627 | To do so, attach the following notices to the program. It is safest 628 | to attach them to the start of each source file to most effectively 629 | state the exclusion of warranty; and each file should have at least 630 | the "copyright" line and a pointer to where the full notice is found. 631 | 632 | 633 | Copyright (C) 634 | 635 | This program is free software: you can redistribute it and/or modify 636 | it under the terms of the GNU Affero General Public License as published 637 | by the Free Software Foundation, either version 3 of the License, or 638 | (at your option) any later version. 639 | 640 | This program is distributed in the hope that it will be useful, 641 | but WITHOUT ANY WARRANTY; without even the implied warranty of 642 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 643 | GNU Affero General Public License for more details. 644 | 645 | You should have received a copy of the GNU Affero General Public License 646 | along with this program. If not, see . 647 | 648 | Also add information on how to contact you by electronic and paper mail. 649 | 650 | If your software can interact with users remotely through a computer 651 | network, you should also make sure that it provides a way for users to 652 | get its source. For example, if your program is a web application, its 653 | interface could display a "Source" link that leads users to an archive 654 | of the code. There are many ways you could offer source, and different 655 | solutions will be better for different programs; see section 13 for the 656 | specific requirements. 657 | 658 | You should also get your employer (if you work as a programmer) or school, 659 | if any, to sign a "copyright disclaimer" for the program, if necessary. 660 | For more information on this, and how to apply and follow the GNU AGPL, see 661 | . 662 | --------------------------------------------------------------------------------