diff --git a/.env b/.env deleted file mode 100644 index a07ff79..0000000 --- a/.env +++ /dev/null @@ -1,3 +0,0 @@ -APP_ENV=dev -APP_SECRET=change-me -DATABASE_URL="sqlite:///%kernel.project_dir%/var/data.db" diff --git a/.github/dependabot.yml b/.github/dependabot.yml new file mode 100644 index 0000000..85a8ada --- /dev/null +++ b/.github/dependabot.yml @@ -0,0 +1,24 @@ +# SPDX-FileCopyrightText: 2026 LibreCode coop and contributors +# SPDX-License-Identifier: AGPL-3.0-or-later + +version: 2 +updates: + - package-ecosystem: composer + directories: + - / + - /vendor-bin/infection + - /vendor-bin/openapi-extractor + - /vendor-bin/phpstan + - /vendor-bin/psalm + schedule: + interval: daily + + - package-ecosystem: npm + directory: / + schedule: + interval: daily + + - package-ecosystem: github-actions + directory: / + schedule: + interval: daily diff --git a/.github/workflows/behat-sqlite.yml b/.github/workflows/behat-sqlite.yml new file mode 100644 index 0000000..55c6106 --- /dev/null +++ b/.github/workflows/behat-sqlite.yml @@ -0,0 +1,158 @@ +# SPDX-FileCopyrightText: 2026 LibreCode coop and contributors +# SPDX-License-Identifier: AGPL-3.0-or-later + +name: Behat SQLite + +on: + pull_request: + +permissions: + contents: read + +concurrency: + group: behat-sqlite-${{ github.head_ref || github.run_id }} + cancel-in-progress: true + +jobs: + matrix: + runs-on: ubuntu-latest + outputs: + php-min: ${{ steps.versions.outputs.php-min }} + php-max: ${{ steps.versions.outputs.php-max }} + branches-min: ${{ steps.versions.outputs.branches-min }} + branches-max: ${{ steps.versions.outputs.branches-max }} + + steps: + - name: Checkout app + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + + - name: Get version matrix + id: versions + uses: nextcloud-libraries/nextcloud-version-matrix@cd0211ffcef1065e2020cd579e4843b8746e7a58 # v1.3.3 + + changes: + runs-on: ubuntu-latest + permissions: + contents: read + pull-requests: read + outputs: + src: ${{ steps.changes.outputs.src }} + + steps: + - uses: dorny/paths-filter@ceb8a2b8f2d89434be7ff52d3de7ec3738c5cc9d # v4.0.3 + id: changes + continue-on-error: true + with: + filters: | + src: + - '.github/workflows/behat*' + - 'appinfo/**' + - 'lib/**' + - 'tests/integration/**' + - 'composer.json' + - 'composer.lock' + + behat-sqlite: + runs-on: ubuntu-latest + needs: [changes, matrix] + if: needs.changes.outputs.src != 'false' + timeout-minutes: 30 + + strategy: + fail-fast: false + matrix: + include: + - php-version: ${{ needs.matrix.outputs.php-min }} + server-version: ${{ needs.matrix.outputs.branches-min }} + boundary: minimum + - php-version: ${{ needs.matrix.outputs.php-max }} + server-version: ${{ needs.matrix.outputs.branches-max }} + boundary: maximum + + env: + APP_NAME: usage_statistics_server + + name: SQLite ${{ matrix.boundary }} PHP ${{ matrix.php-version }} Nextcloud ${{ matrix.server-version }} + + steps: + - name: Checkout server + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + submodules: true + repository: nextcloud/server + ref: ${{ matrix.server-version }} + + - name: Checkout app + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + path: apps/${{ env.APP_NAME }} + + - name: Set up PHP ${{ matrix.php-version }} + uses: shivammathur/setup-php@f3e473d116dcccaddc5834248c87452386958240 # v2.37.2 + with: + php-version: ${{ matrix.php-version }} + extensions: bz2, ctype, curl, dom, fileinfo, gd, iconv, intl, json, libxml, mbstring, openssl, pcntl, posix, session, simplexml, sockets, sqlite, pdo_sqlite, xmlreader, xmlwriter, zip, zlib + coverage: none + ini-file: development + ini-values: disable_functions= + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + + - name: Install dependencies + working-directory: apps/${{ env.APP_NAME }} + run: | + composer remove nextcloud/ocp --dev --no-scripts + composer install --no-dev --no-scripts + composer --working-dir=tests/integration install --prefer-dist --no-progress + + - name: Set up Nextcloud + run: | + mkdir data + ./occ maintenance:install \ + --verbose \ + --database=sqlite \ + --database-name=nextcloud \ + --admin-user admin \ + --admin-pass admin + ./occ --version + ./occ app:enable --force ${{ env.APP_NAME }} + ./occ config:system:set auth.bruteforce.protection.enabled --value false --type boolean + ./occ config:system:set ratelimit.protection.enabled --value false --type boolean + ./occ config:system:set debug --value true --type boolean + + - name: Run Behat + working-directory: apps/${{ env.APP_NAME }}/tests/integration + env: + BEHAT_ROOT_DIR: ../../../../ + BEHAT_RUN_AS: runner + BEHAT_VERBOSE: ${{ runner.debug }} + run: composer run behat + + - name: Upload Behat results + if: always() + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + with: + name: behat-results-${{ matrix.boundary }}-nc${{ matrix.server-version }}-php${{ matrix.php-version }} + path: apps/${{ env.APP_NAME }}/tests/integration/output/ + if-no-files-found: ignore + retention-days: 30 + + - name: Print logs + if: always() + run: cat data/nextcloud.log 2>/dev/null || true + + summary: + permissions: + contents: none + runs-on: ubuntu-latest + needs: [changes, behat-sqlite] + if: always() + name: behat-sqlite-summary + + steps: + - name: Summary status + run: if ${{ needs.changes.outputs.src != 'false' && needs.behat-sqlite.result != 'success' }}; then exit 1; fi diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml deleted file mode 100644 index 6f644be..0000000 --- a/.github/workflows/ci.yml +++ /dev/null @@ -1,23 +0,0 @@ -name: CI - -on: - pull_request: - push: - branches: - - main - -permissions: - contents: read - -jobs: - test: - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v4 - - uses: shivammathur/setup-php@v2 - with: - php-version: '8.4' - coverage: none - - uses: ramsey/composer-install@v3 - - run: composer validate --strict - - run: vendor/bin/phpunit diff --git a/.github/workflows/infection.yml b/.github/workflows/infection.yml new file mode 100644 index 0000000..8791081 --- /dev/null +++ b/.github/workflows/infection.yml @@ -0,0 +1,158 @@ +# SPDX-FileCopyrightText: 2026 LibreCode coop and contributors +# SPDX-License-Identifier: AGPL-3.0-or-later + +name: Infection + +on: + pull_request: + +permissions: + contents: read + +concurrency: + group: infection-${{ github.head_ref || github.run_id }} + cancel-in-progress: true + +jobs: + matrix: + runs-on: ubuntu-latest + outputs: + php-min: ${{ steps.versions.outputs.php-min }} + branches-max: ${{ steps.versions.outputs.branches-max }} + + steps: + - name: Checkout app + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + + - name: Get version matrix + id: versions + uses: nextcloud-libraries/nextcloud-version-matrix@cd0211ffcef1065e2020cd579e4843b8746e7a58 # v1.3.3 + + changes: + runs-on: ubuntu-latest + permissions: + contents: read + pull-requests: read + outputs: + src: ${{ steps.changes.outputs.src }} + + steps: + - uses: dorny/paths-filter@ceb8a2b8f2d89434be7ff52d3de7ec3738c5cc9d # v4.0.3 + id: changes + continue-on-error: true + with: + filters: | + src: + - '.github/workflows/infection.yml' + - 'appinfo/**' + - 'lib/**' + - 'tests/php/**' + - 'vendor-bin/infection/**' + - 'infection.json5' + - 'composer.json' + - 'composer.lock' + + infection: + runs-on: ubuntu-latest + needs: [changes, matrix] + if: needs.changes.outputs.src != 'false' + timeout-minutes: 30 + env: + APP_NAME: usage_statistics_server + + name: PHP ${{ needs.matrix.outputs.php-min }} Nextcloud ${{ needs.matrix.outputs.branches-max }} + + steps: + - name: Checkout server + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + submodules: true + repository: nextcloud/server + ref: ${{ needs.matrix.outputs.branches-max }} + + - name: Checkout app + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + path: apps/${{ env.APP_NAME }} + + - name: Set up PHP ${{ needs.matrix.outputs.php-min }} + uses: shivammathur/setup-php@f3e473d116dcccaddc5834248c87452386958240 # v2.37.2 + with: + php-version: ${{ needs.matrix.outputs.php-min }} + extensions: bz2, ctype, curl, dom, fileinfo, gd, iconv, intl, json, libxml, mbstring, openssl, pcntl, posix, session, simplexml, sockets, sqlite, pdo_sqlite, xmlreader, xmlwriter, zip, zlib + coverage: pcov + ini-file: development + ini-values: disable_functions=, memory_limit=2G, pcov.directory=${{ github.workspace }}/apps/${{ env.APP_NAME }}/lib + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + + - name: Install dependencies + working-directory: apps/${{ env.APP_NAME }} + run: | + composer remove nextcloud/ocp --dev --no-scripts + composer install + + - name: Set up Nextcloud + run: | + mkdir data + ./occ maintenance:install \ + --verbose \ + --database=sqlite \ + --database-name=nextcloud \ + --admin-user admin \ + --admin-pass admin + ./occ app:enable --force ${{ env.APP_NAME }} + + - name: Generate mutation coverage + working-directory: apps/${{ env.APP_NAME }} + run: | + mkdir -p build/coverage/coverage-xml + vendor/bin/phpunit -c tests/php/phpunit.xml \ + --coverage-xml build/coverage/coverage-xml \ + --log-junit build/coverage/junit.xml \ + --colors=always \ + --fail-on-warning \ + --fail-on-risky + + - name: Run Infection + working-directory: apps/${{ env.APP_NAME }} + env: + COMPOSER_PROCESS_TIMEOUT: 0 + run: | + set -o pipefail + composer mutation:test -- \ + --coverage=build/coverage \ + --skip-initial-tests \ + --threads=max \ + --show-mutations=max \ + --no-progress \ + --no-interaction 2>&1 | tee infection.log + + - name: Upload Infection results + if: always() + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + with: + name: infection-results + path: | + apps/${{ env.APP_NAME }}/infection.log + apps/${{ env.APP_NAME }}/build/coverage/junit.xml + apps/${{ env.APP_NAME }}/build/coverage/coverage-xml/index.xml + apps/${{ env.APP_NAME }}/vendor-bin/infection/composer.lock + if-no-files-found: ignore + retention-days: 14 + + summary: + permissions: + contents: none + runs-on: ubuntu-latest + needs: [changes, infection] + if: always() + name: infection-summary + + steps: + - name: Summary status + run: if ${{ needs.changes.outputs.src != 'false' && needs.infection.result != 'success' }}; then exit 1; fi diff --git a/.github/workflows/lint-eslint.yml b/.github/workflows/lint-eslint.yml new file mode 100644 index 0000000..d4b63f1 --- /dev/null +++ b/.github/workflows/lint-eslint.yml @@ -0,0 +1,39 @@ +# Based on the Nextcloud organization workflow template. +# SPDX-FileCopyrightText: 2022-2024 Nextcloud GmbH and Nextcloud contributors +# SPDX-License-Identifier: MIT + +name: Lint eslint + +on: pull_request + +permissions: + contents: read + +concurrency: + group: lint-eslint-${{ github.head_ref || github.run_id }} + cancel-in-progress: true + +jobs: + lint: + runs-on: ubuntu-latest + steps: + - name: Checkout + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - name: Read package engines + uses: skjnldsv/read-package-engines-version-actions@06d6baf7d8f41934ab630e97d9e6c0bc9c9ac5e4 # v3 + id: versions + with: + fallbackNode: '^24' + fallbackNpm: '^11.3' + - name: Set up node + uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0 + with: + node-version: ${{ steps.versions.outputs.nodeVersion }} + - name: Set up npm + run: npm i -g 'npm@${{ steps.versions.outputs.npmVersion }}' + - name: Install dependencies + run: npm install --no-package-lock + - name: Lint + run: npm run lint diff --git a/.github/workflows/lint-info-xml.yml b/.github/workflows/lint-info-xml.yml new file mode 100644 index 0000000..e96a8c0 --- /dev/null +++ b/.github/workflows/lint-info-xml.yml @@ -0,0 +1,34 @@ +# SPDX-FileCopyrightText: 2021-2024 Nextcloud GmbH and Nextcloud contributors +# SPDX-License-Identifier: MIT + +name: Lint info.xml + +on: + pull_request: + +permissions: + contents: read + +concurrency: + group: lint-info-xml-${{ github.head_ref || github.run_id }} + cancel-in-progress: true + +jobs: + xml-linters: + runs-on: ubuntu-latest + name: info.xml lint + + steps: + - name: Checkout + uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + with: + persist-credentials: false + + - name: Download schema + run: wget https://raw.githubusercontent.com/nextcloud/appstore/master/nextcloudappstore/api/v1/release/info.xsd + + - name: Lint info.xml + uses: ChristophWurst/xmllint-action@36f2a302f84f8c83fceea0b9c59e1eb4a616d3c1 # v1.2 + with: + xml-file: ./appinfo/info.xml + xml-schema-file: ./info.xsd diff --git a/.github/workflows/lint-php.yml b/.github/workflows/lint-php.yml new file mode 100644 index 0000000..fb03b74 --- /dev/null +++ b/.github/workflows/lint-php.yml @@ -0,0 +1,80 @@ +# SPDX-FileCopyrightText: 2021-2024 Nextcloud GmbH and Nextcloud contributors +# SPDX-License-Identifier: MIT + +name: Lint php + +on: + pull_request: + +permissions: + contents: read + +concurrency: + group: lint-php-${{ github.head_ref || github.run_id }} + cancel-in-progress: true + +jobs: + matrix: + runs-on: ubuntu-latest + outputs: + php-min: ${{ steps.versions.outputs.php-min }} + php-max: ${{ steps.versions.outputs.php-max }} + + steps: + - name: Checkout app + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + + - name: Get version matrix + id: versions + uses: nextcloud-libraries/nextcloud-version-matrix@cd0211ffcef1065e2020cd579e4843b8746e7a58 # v1.3.3 + + php-lint: + runs-on: ubuntu-latest + needs: matrix + name: php-lint PHP ${{ matrix.php-versions }} + + strategy: + fail-fast: false + matrix: + php-versions: + - ${{ needs.matrix.outputs.php-min }} + - ${{ needs.matrix.outputs.php-max }} + + steps: + - name: Checkout + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + + - name: Set up PHP ${{ matrix.php-versions }} + uses: shivammathur/setup-php@f3e473d116dcccaddc5834248c87452386958240 # v2.37.2 + with: + php-version: ${{ matrix.php-versions }} + extensions: bz2, ctype, curl, dom, fileinfo, gd, iconv, intl, json, libxml, mbstring, openssl, pcntl, posix, session, simplexml, xmlreader, xmlwriter, zip, zlib, sqlite, pdo_sqlite + coverage: none + ini-file: development + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + + - name: Install dependencies + run: | + composer remove nextcloud/ocp --dev --no-scripts + composer install + + - name: Lint + run: composer run lint + + summary: + permissions: + contents: none + runs-on: ubuntu-latest + needs: php-lint + if: always() + + name: php-lint-summary + + steps: + - name: Summary status + run: if ${{ needs.php-lint.result != 'success' && needs.php-lint.result != 'skipped' }}; then exit 1; fi diff --git a/.github/workflows/lint-typescript.yml b/.github/workflows/lint-typescript.yml new file mode 100644 index 0000000..ad47a73 --- /dev/null +++ b/.github/workflows/lint-typescript.yml @@ -0,0 +1,39 @@ +# Based on the Nextcloud organization workflow template. +# SPDX-FileCopyrightText: 2022-2024 Nextcloud GmbH and Nextcloud contributors +# SPDX-License-Identifier: MIT + +name: Type checking + +on: pull_request + +permissions: + contents: read + +concurrency: + group: lint-typescript-${{ github.head_ref || github.run_id }} + cancel-in-progress: true + +jobs: + typescript: + runs-on: ubuntu-latest + steps: + - name: Checkout + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - name: Read package engines + uses: skjnldsv/read-package-engines-version-actions@06d6baf7d8f41934ab630e97d9e6c0bc9c9ac5e4 # v3 + id: versions + with: + fallbackNode: '^24' + fallbackNpm: '^11.3' + - name: Set up node + uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0 + with: + node-version: ${{ steps.versions.outputs.nodeVersion }} + - name: Set up npm + run: npm i -g 'npm@${{ steps.versions.outputs.npmVersion }}' + - name: Install dependencies + run: npm install --no-package-lock + - name: Check types + run: npm run ts:check diff --git a/.github/workflows/node-test.yml b/.github/workflows/node-test.yml new file mode 100644 index 0000000..b7ad0fd --- /dev/null +++ b/.github/workflows/node-test.yml @@ -0,0 +1,41 @@ +# Based on the Nextcloud organization workflow template. +# SPDX-FileCopyrightText: 2022-2024 Nextcloud GmbH and Nextcloud contributors +# SPDX-License-Identifier: MIT + +name: Node tests + +on: pull_request + +permissions: + contents: read + +concurrency: + group: node-tests-${{ github.head_ref || github.run_id }} + cancel-in-progress: true + +jobs: + node: + runs-on: ubuntu-latest + steps: + - name: Checkout + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - name: Read package engines + uses: skjnldsv/read-package-engines-version-actions@06d6baf7d8f41934ab630e97d9e6c0bc9c9ac5e4 # v3 + id: versions + with: + fallbackNode: '^24' + fallbackNpm: '^11.3' + - name: Set up node + uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0 + with: + node-version: ${{ steps.versions.outputs.nodeVersion }} + - name: Set up npm + run: npm i -g 'npm@${{ steps.versions.outputs.npmVersion }}' + - name: Install dependencies + run: npm install --no-package-lock + - name: Run Node checks + run: | + npm run lint + npm run ts:check diff --git a/.github/workflows/openapi.yml b/.github/workflows/openapi.yml new file mode 100644 index 0000000..d8f2c92 --- /dev/null +++ b/.github/workflows/openapi.yml @@ -0,0 +1,75 @@ +# This workflow is based on the Nextcloud organization workflow template. +# +# https://github.com/nextcloud/.github +# SPDX-FileCopyrightText: 2024 Nextcloud GmbH and Nextcloud contributors +# SPDX-License-Identifier: MIT + +name: OpenAPI + +on: pull_request + +permissions: + contents: read + +concurrency: + group: openapi-${{ github.head_ref || github.run_id }} + cancel-in-progress: true + +jobs: + openapi: + runs-on: ubuntu-latest + + steps: + - name: Checkout + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + submodules: true + + - name: Get php version + id: php_versions + uses: icewind1991/nextcloud-version-matrix@cd0211ffcef1065e2020cd579e4843b8746e7a58 # v1.3.3 + + - name: Set up PHP + uses: shivammathur/setup-php@f3e473d116dcccaddc5834248c87452386958240 # v2.37.2 + with: + php-version: ${{ steps.php_versions.outputs.php-available }} + extensions: xml + coverage: none + ini-file: development + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + + - name: Read package.json node and npm engines version + uses: skjnldsv/read-package-engines-version-actions@06d6baf7d8f41934ab630e97d9e6c0bc9c9ac5e4 # v3 + id: node_versions + with: + fallbackNode: '^24' + fallbackNpm: '^11.3' + + - name: Set up node ${{ steps.node_versions.outputs.nodeVersion }} + uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0 + with: + node-version: ${{ steps.node_versions.outputs.nodeVersion }} + + - name: Set up npm ${{ steps.node_versions.outputs.npmVersion }} + run: npm i -g 'npm@${{ steps.node_versions.outputs.npmVersion }}' + + - name: Install JavaScript dependencies + run: npm install --no-package-lock + + - name: Install Composer dependencies + uses: ramsey/composer-install@65e4f84970763564f46a70b8a54b90d033b3bdda # v4.0.0 + + - name: Generate OpenAPI and TypeScript types + run: composer run openapi + + - name: Upload generated OpenAPI files + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + with: + name: generated-openapi + path: | + openapi.json + openapi-administration.json + openapi-full.json + src/types/openapi/*.ts diff --git a/.github/workflows/phpstan.yml b/.github/workflows/phpstan.yml new file mode 100644 index 0000000..0761d39 --- /dev/null +++ b/.github/workflows/phpstan.yml @@ -0,0 +1,58 @@ +# This workflow is based on the Nextcloud organization template repository +# +# https://github.com/nextcloud/.github +# +# SPDX-FileCopyrightText: 2022-2024 Nextcloud GmbH and Nextcloud contributors +# SPDX-License-Identifier: MIT + +name: PHPStan + +on: pull_request + +concurrency: + group: phpstan-${{ github.head_ref || github.run_id }} + cancel-in-progress: true + +permissions: + contents: read + +jobs: + static-analysis: + runs-on: ubuntu-latest + + name: static-phpstan-analysis + steps: + - name: Checkout + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + + - name: Get php version + id: versions + uses: nextcloud-libraries/nextcloud-version-matrix@cd0211ffcef1065e2020cd579e4843b8746e7a58 # v1.3.3 + + - name: Check enforcement of minimum PHP version ${{ steps.versions.outputs.php-min-id }} in phpstan.neon + run: "grep 'min: ${{ steps.versions.outputs.php-min-id }}' phpstan.neon" + + - name: Set up php${{ steps.versions.outputs.php-available }} + uses: shivammathur/setup-php@f3e473d116dcccaddc5834248c87452386958240 # v2.37.2 + with: + php-version: ${{ steps.versions.outputs.php-available }} + extensions: bz2, ctype, curl, dom, fileinfo, gd, iconv, intl, json, libxml, mbstring, openssl, pcntl, posix, session, simplexml, xmlreader, xmlwriter, zip, zlib, sqlite, pdo_sqlite + coverage: none + ini-file: development + ini-values: disable_functions= + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + + - name: Remove nextcloud/ocp + run: composer remove nextcloud/ocp --dev --no-scripts + + - name: Install composer dependencies + uses: ramsey/composer-install@65e4f84970763564f46a70b8a54b90d033b3bdda # 4.0.0 + + - name: Install nextcloud/ocp:dev-${{ steps.versions.outputs.branches-max }} + run: composer require --dev nextcloud/ocp:dev-${{ steps.versions.outputs.branches-max }} --ignore-platform-reqs --with-dependencies + + - name: Run PHPStan + run: composer run phpstan -- --no-progress diff --git a/.github/workflows/phpunit-mariadb.yml b/.github/workflows/phpunit-mariadb.yml new file mode 100644 index 0000000..fc8b6df --- /dev/null +++ b/.github/workflows/phpunit-mariadb.yml @@ -0,0 +1,128 @@ +# This workflow is based on the Nextcloud organization workflow template. +# +# https://github.com/nextcloud/.github +# SPDX-FileCopyrightText: 2023-2026 Nextcloud GmbH and Nextcloud contributors +# SPDX-License-Identifier: MIT + +name: PHPUnit MariaDB + +on: + pull_request: + +permissions: + contents: read + +concurrency: + group: phpunit-mariadb-${{ github.head_ref || github.run_id }} + cancel-in-progress: true + +jobs: + matrix: + runs-on: ubuntu-latest + outputs: + matrix: ${{ steps.versions.outputs.sparse-matrix }} + steps: + - name: Checkout app + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - name: Get version matrix + id: versions + uses: icewind1991/nextcloud-version-matrix@cd0211ffcef1065e2020cd579e4843b8746e7a58 # v1.3.3 + with: + matrix: '{"mariadb-versions": ["10.6", "11.4"]}' + + changes: + runs-on: ubuntu-latest + permissions: + contents: read + pull-requests: read + outputs: + src: ${{ steps.changes.outputs.src }} + steps: + - uses: dorny/paths-filter@ceb8a2b8f2d89434be7ff52d3de7ec3738c5cc9d # v4.0.3 + id: changes + continue-on-error: true + with: + filters: | + src: + - '.github/workflows/phpunit*' + - 'appinfo/**' + - 'lib/**' + - 'tests/**' + - 'composer.json' + - 'composer.lock' + + phpunit-mariadb: + runs-on: ubuntu-latest + needs: [changes, matrix] + if: needs.changes.outputs.src != 'false' + strategy: + fail-fast: false + matrix: ${{ fromJson(needs.matrix.outputs.matrix) }} + env: + APP_NAME: usage_statistics_server + name: MariaDB ${{ matrix.mariadb-versions }} PHP ${{ matrix.php-versions }} Nextcloud ${{ matrix.server-versions }} + services: + mariadb: + image: ghcr.io/nextcloud/continuous-integration-mariadb-${{ matrix.mariadb-versions }}:latest + ports: + - 4444:3306/tcp + env: + MARIADB_ROOT_PASSWORD: rootpassword + options: --health-cmd="mariadb-admin ping" --health-interval 5s --health-timeout 2s --health-retries 10 + steps: + - name: Checkout server + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + submodules: true + repository: nextcloud/server + ref: ${{ matrix.server-versions }} + - name: Checkout app + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + path: apps/${{ env.APP_NAME }} + - name: Set up PHP ${{ matrix.php-versions }} + uses: shivammathur/setup-php@f3e473d116dcccaddc5834248c87452386958240 # v2.37.2 + with: + php-version: ${{ matrix.php-versions }} + extensions: bz2, ctype, curl, dom, fileinfo, gd, iconv, intl, json, libxml, mbstring, openssl, pcntl, posix, session, simplexml, xmlreader, xmlwriter, zip, zlib, mysql, pdo_mysql + coverage: none + ini-file: development + ini-values: disable_functions= + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + - name: Enable ONLY_FULL_GROUP_BY + run: | + echo "SET GLOBAL sql_mode=(SELECT CONCAT(@@sql_mode,',ONLY_FULL_GROUP_BY'));" | mysql -h 127.0.0.1 -P 4444 -u root -prootpassword + echo 'SELECT @@sql_mode;' | mysql -h 127.0.0.1 -P 4444 -u root -prootpassword + - name: Install app dependencies + working-directory: apps/${{ env.APP_NAME }} + run: | + composer remove nextcloud/ocp --dev --no-scripts + composer install + - name: Set up Nextcloud + run: | + mkdir data + ./occ maintenance:install --verbose --database=mysql --database-name=nextcloud --database-host=127.0.0.1 --database-port=4444 --database-user=root --database-pass=rootpassword --admin-user admin --admin-pass admin + ./occ --version + ./occ app:enable --force ${{ env.APP_NAME }} + - name: Run PHPUnit suites + working-directory: apps/${{ env.APP_NAME }} + run: composer run test:php + - name: Print logs + if: always() + run: cat data/nextcloud.log || true + + summary: + permissions: + contents: none + runs-on: ubuntu-latest + needs: [changes, phpunit-mariadb] + if: always() + name: phpunit-mariadb-summary + steps: + - name: Summary status + run: if ${{ needs.changes.outputs.src != 'false' && needs.phpunit-mariadb.result != 'success' }}; then exit 1; fi diff --git a/.github/workflows/phpunit-mysql.yml b/.github/workflows/phpunit-mysql.yml new file mode 100644 index 0000000..76ebd0c --- /dev/null +++ b/.github/workflows/phpunit-mysql.yml @@ -0,0 +1,94 @@ +# This workflow is based on the Nextcloud organization workflow template. +# +# https://github.com/nextcloud/.github +# SPDX-FileCopyrightText: 2022-2026 Nextcloud GmbH and Nextcloud contributors +# SPDX-License-Identifier: MIT + +name: PHPUnit MySQL + +on: + pull_request: + +permissions: + contents: read + +concurrency: + group: phpunit-mysql-${{ github.head_ref || github.run_id }} + cancel-in-progress: true + +jobs: + matrix: + runs-on: ubuntu-latest + outputs: + matrix: ${{ steps.versions.outputs.sparse-matrix }} + steps: + - name: Checkout app + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - name: Get version matrix + id: versions + uses: icewind1991/nextcloud-version-matrix@cd0211ffcef1065e2020cd579e4843b8746e7a58 # v1.3.3 + with: + matrix: '{"mysql-versions": ["8.4"]}' + + phpunit-mysql: + runs-on: ubuntu-latest + needs: matrix + strategy: + fail-fast: false + matrix: ${{ fromJson(needs.matrix.outputs.matrix) }} + env: + APP_NAME: usage_statistics_server + name: MySQL ${{ matrix.mysql-versions }} PHP ${{ matrix.php-versions }} Nextcloud ${{ matrix.server-versions }} + services: + mysql: + image: ghcr.io/nextcloud/continuous-integration-mysql-${{ matrix.mysql-versions }}:latest + ports: + - 4444:3306/tcp + env: + MYSQL_ROOT_PASSWORD: rootpassword + options: --health-cmd="mysqladmin ping" --health-interval 5s --health-timeout 2s --health-retries 10 + steps: + - name: Checkout server + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + submodules: true + repository: nextcloud/server + ref: ${{ matrix.server-versions }} + - name: Checkout app + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + path: apps/${{ env.APP_NAME }} + - name: Set up PHP ${{ matrix.php-versions }} + uses: shivammathur/setup-php@f3e473d116dcccaddc5834248c87452386958240 # v2.37.2 + with: + php-version: ${{ matrix.php-versions }} + extensions: bz2, ctype, curl, dom, fileinfo, gd, iconv, intl, json, libxml, mbstring, openssl, pcntl, posix, session, simplexml, xmlreader, xmlwriter, zip, zlib, mysql, pdo_mysql + coverage: none + ini-file: development + ini-values: disable_functions= + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + - name: Enable ONLY_FULL_GROUP_BY + run: | + echo "SET GLOBAL sql_mode=(SELECT CONCAT(@@sql_mode,',ONLY_FULL_GROUP_BY'));" | mysql -h 127.0.0.1 -P 4444 -u root -prootpassword + - name: Install app dependencies + working-directory: apps/${{ env.APP_NAME }} + run: | + composer remove nextcloud/ocp --dev --no-scripts + composer install + - name: Set up Nextcloud + run: | + mkdir data + ./occ maintenance:install --verbose --database=mysql --database-name=nextcloud --database-host=127.0.0.1 --database-port=4444 --database-user=root --database-pass=rootpassword --admin-user admin --admin-pass admin + ./occ --version + ./occ app:enable --force ${{ env.APP_NAME }} + - name: Run PHPUnit suites + working-directory: apps/${{ env.APP_NAME }} + run: composer run test:php + - name: Print logs + if: always() + run: cat data/nextcloud.log || true diff --git a/.github/workflows/phpunit-pgsql.yml b/.github/workflows/phpunit-pgsql.yml new file mode 100644 index 0000000..5bee0ad --- /dev/null +++ b/.github/workflows/phpunit-pgsql.yml @@ -0,0 +1,91 @@ +# This workflow is based on the Nextcloud organization workflow template. +# +# https://github.com/nextcloud/.github +# SPDX-FileCopyrightText: 2022-2026 Nextcloud GmbH and Nextcloud contributors +# SPDX-License-Identifier: MIT + +name: PHPUnit PostgreSQL + +on: + pull_request: + +permissions: + contents: read + +concurrency: + group: phpunit-pgsql-${{ github.head_ref || github.run_id }} + cancel-in-progress: true + +jobs: + matrix: + runs-on: ubuntu-latest + outputs: + matrix: ${{ steps.versions.outputs.sparse-matrix }} + steps: + - name: Checkout app + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - name: Get version matrix + id: versions + uses: icewind1991/nextcloud-version-matrix@cd0211ffcef1065e2020cd579e4843b8746e7a58 # v1.3.3 + + phpunit-pgsql: + runs-on: ubuntu-latest + needs: matrix + strategy: + fail-fast: false + matrix: ${{ fromJson(needs.matrix.outputs.matrix) }} + env: + APP_NAME: usage_statistics_server + name: PostgreSQL PHP ${{ matrix.php-versions }} Nextcloud ${{ matrix.server-versions }} + services: + postgres: + image: ghcr.io/nextcloud/continuous-integration-postgres-16:latest + ports: + - 4444:5432/tcp + env: + POSTGRES_USER: root + POSTGRES_PASSWORD: rootpassword + POSTGRES_DB: nextcloud + options: --health-cmd pg_isready --health-interval 5s --health-timeout 2s --health-retries 5 + steps: + - name: Checkout server + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + submodules: true + repository: nextcloud/server + ref: ${{ matrix.server-versions }} + - name: Checkout app + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + path: apps/${{ env.APP_NAME }} + - name: Set up PHP ${{ matrix.php-versions }} + uses: shivammathur/setup-php@f3e473d116dcccaddc5834248c87452386958240 # v2.37.2 + with: + php-version: ${{ matrix.php-versions }} + extensions: bz2, ctype, curl, dom, fileinfo, gd, iconv, intl, json, libxml, mbstring, openssl, pcntl, posix, session, simplexml, xmlreader, xmlwriter, zip, zlib, pgsql, pdo_pgsql + coverage: none + ini-file: development + ini-values: disable_functions= + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + - name: Install app dependencies + working-directory: apps/${{ env.APP_NAME }} + run: | + composer remove nextcloud/ocp --dev --no-scripts + composer install + - name: Set up Nextcloud + run: | + mkdir data + ./occ maintenance:install --verbose --database=pgsql --database-name=nextcloud --database-host=127.0.0.1 --database-port=4444 --database-user=root --database-pass=rootpassword --admin-user admin --admin-pass admin + ./occ --version + ./occ app:enable --force ${{ env.APP_NAME }} + - name: Run PHPUnit suites + working-directory: apps/${{ env.APP_NAME }} + run: composer run test:php + - name: Print logs + if: always() + run: cat data/nextcloud.log || true diff --git a/.github/workflows/phpunit-sqlite.yml b/.github/workflows/phpunit-sqlite.yml new file mode 100644 index 0000000..16e6171 --- /dev/null +++ b/.github/workflows/phpunit-sqlite.yml @@ -0,0 +1,132 @@ +# SPDX-FileCopyrightText: 2022-2024 Nextcloud GmbH and Nextcloud contributors +# SPDX-License-Identifier: MIT + +name: PHPUnit SQLite + +on: + pull_request: + +permissions: + contents: read + +concurrency: + group: phpunit-sqlite-${{ github.head_ref || github.run_id }} + cancel-in-progress: true + +jobs: + matrix: + runs-on: ubuntu-latest + outputs: + matrix: ${{ steps.versions.outputs.sparse-matrix }} + + steps: + - name: Checkout app + uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + with: + persist-credentials: false + + - name: Get version matrix + id: versions + uses: icewind1991/nextcloud-version-matrix@8a7bac6300b2f0f3100088b297995a229558ddba # v1.3.2 + + changes: + runs-on: ubuntu-latest + permissions: + contents: read + pull-requests: read + + outputs: + src: ${{ steps.changes.outputs.src }} + + steps: + - uses: dorny/paths-filter@fbd0ab8f3e69293af611ebaee6363fc25e6d187d # v4.0.1 + id: changes + continue-on-error: true + with: + filters: | + src: + - '.github/workflows/phpunit*' + - 'appinfo/**' + - 'lib/**' + - 'tests/**' + - 'composer.json' + - 'composer.lock' + + phpunit-sqlite: + runs-on: ubuntu-latest + needs: [changes, matrix] + if: needs.changes.outputs.src != 'false' + + strategy: + fail-fast: false + matrix: ${{ fromJson(needs.matrix.outputs.matrix) }} + + env: + APP_NAME: usage_statistics_server + + name: SQLite PHP ${{ matrix.php-versions }} Nextcloud ${{ matrix.server-versions }} + + steps: + - name: Checkout server + uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + with: + persist-credentials: false + submodules: true + repository: nextcloud/server + ref: ${{ matrix.server-versions }} + + - name: Checkout app + uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + with: + persist-credentials: false + path: apps/${{ env.APP_NAME }} + + - name: Set up php ${{ matrix.php-versions }} + uses: shivammathur/setup-php@accd6127cb78bee3e8082180cb391013d204ef9f # v2.37.0 + with: + php-version: ${{ matrix.php-versions }} + extensions: bz2, ctype, curl, dom, fileinfo, gd, iconv, intl, json, libxml, mbstring, openssl, pcntl, posix, session, simplexml, xmlreader, xmlwriter, zip, zlib, sqlite, pdo_sqlite + coverage: none + ini-file: development + ini-values: disable_functions= + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + + - name: Install app dependencies + working-directory: apps/${{ env.APP_NAME }} + run: | + composer remove nextcloud/ocp --dev --no-scripts + composer install + + - name: Set up Nextcloud + run: | + mkdir data + ./occ maintenance:install \ + --verbose \ + --database=sqlite \ + --database-name=nextcloud \ + --admin-user admin \ + --admin-pass admin + ./occ --version + ./occ app:enable --force ${{ env.APP_NAME }} + + - name: Run PHPUnit suites + working-directory: apps/${{ env.APP_NAME }} + run: composer run test:php + + - name: Print logs + if: always() + run: cat data/nextcloud.log || true + + summary: + permissions: + contents: none + runs-on: ubuntu-latest + needs: [changes, phpunit-sqlite] + if: always() + + name: phpunit-sqlite-summary + + steps: + - name: Summary status + run: if ${{ needs.changes.outputs.src != 'false' && needs.phpunit-sqlite.result != 'success' }}; then exit 1; fi diff --git a/.github/workflows/psalm.yml b/.github/workflows/psalm.yml new file mode 100644 index 0000000..6a7eaaf --- /dev/null +++ b/.github/workflows/psalm.yml @@ -0,0 +1,59 @@ +# This workflow is provided via the organization template repository +# +# https://github.com/nextcloud/.github +# https://docs.github.com/en/actions/learn-github-actions/sharing-workflows-with-your-organization +# +# SPDX-FileCopyrightText: 2022-2024 Nextcloud GmbH and Nextcloud contributors +# SPDX-License-Identifier: MIT + +name: Static analysis + +on: pull_request + +concurrency: + group: psalm-${{ github.head_ref || github.run_id }} + cancel-in-progress: true + +permissions: + contents: read + +jobs: + static-analysis: + runs-on: ubuntu-latest + + name: static-psalm-analysis + steps: + - name: Checkout + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + + - name: Get php version + id: versions + uses: nextcloud-libraries/nextcloud-version-matrix@cd0211ffcef1065e2020cd579e4843b8746e7a58 # v1.3.3 + + - name: Check enforcement of minimum PHP version ${{ steps.versions.outputs.php-min }} in psalm.xml + run: grep 'phpVersion="${{ steps.versions.outputs.php-min }}' psalm.xml + + - name: Set up php${{ steps.versions.outputs.php-available }} + uses: shivammathur/setup-php@f3e473d116dcccaddc5834248c87452386958240 # v2.37.2 + with: + php-version: ${{ steps.versions.outputs.php-available }} + extensions: bz2, ctype, curl, dom, fileinfo, gd, iconv, intl, json, libxml, mbstring, openssl, pcntl, posix, session, simplexml, xmlreader, xmlwriter, zip, zlib, sqlite, pdo_sqlite + coverage: none + ini-file: development + ini-values: disable_functions= + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + + - name: Remove nextcloud/ocp + run: composer remove nextcloud/ocp --dev --no-scripts + + - name: Install composer dependencies + uses: ramsey/composer-install@65e4f84970763564f46a70b8a54b90d033b3bdda # v4.0.0 + + - name: Install nextcloud/ocp:dev-${{ steps.versions.outputs.branches-max }} + run: composer require --dev nextcloud/ocp:dev-${{ steps.versions.outputs.branches-max }} --ignore-platform-reqs --with-dependencies + + - name: Run Psalm + run: composer run psalm -- --threads=1 --monochrome --no-progress --output-format=github diff --git a/.github/workflows/reuse.yml b/.github/workflows/reuse.yml new file mode 100644 index 0000000..e405d5a --- /dev/null +++ b/.github/workflows/reuse.yml @@ -0,0 +1,25 @@ +# This workflow is based on the Nextcloud organization template repository +# +# https://github.com/nextcloud/.github +# +# SPDX-FileCopyrightText: 2022 Free Software Foundation Europe e.V. +# SPDX-License-Identifier: CC0-1.0 + +name: REUSE Compliance Check + +on: [pull_request] + +permissions: + contents: read + +jobs: + reuse-compliance-check: + runs-on: ubuntu-latest + steps: + - name: Checkout + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + + - name: REUSE Compliance Check + uses: fsfe/reuse-action@676e2d560c9a403aa252096d99fcab3e1132b0f5 # v6.0.0 diff --git a/.github/workflows/update-nextcloud-ocp.yml b/.github/workflows/update-nextcloud-ocp.yml new file mode 100644 index 0000000..9b71937 --- /dev/null +++ b/.github/workflows/update-nextcloud-ocp.yml @@ -0,0 +1,65 @@ +# This workflow is based on the Nextcloud organization template repository +# +# https://github.com/nextcloud/.github +# +# SPDX-FileCopyrightText: 2022-2024 Nextcloud GmbH and Nextcloud contributors +# SPDX-License-Identifier: MIT + +name: Update nextcloud/ocp + +on: + workflow_dispatch: + schedule: + - cron: '5 2 * * 0' + +permissions: + contents: write + pull-requests: write + +jobs: + update-nextcloud-ocp: + runs-on: ubuntu-latest + + steps: + - name: Checkout + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + + - name: Get version matrix + id: versions + uses: nextcloud-libraries/nextcloud-version-matrix@cd0211ffcef1065e2020cd579e4843b8746e7a58 # v1.3.3 + + - name: Set up PHP ${{ steps.versions.outputs.php-min }} + uses: shivammathur/setup-php@f3e473d116dcccaddc5834248c87452386958240 # v2.37.2 + with: + php-version: ${{ steps.versions.outputs.php-min }} + extensions: bz2, ctype, curl, dom, fileinfo, gd, iconv, intl, json, libxml, mbstring, openssl, pcntl, posix, session, simplexml, xmlreader, xmlwriter, zip, zlib, sqlite, pdo_sqlite + coverage: none + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + + - name: Install composer dependencies + uses: ramsey/composer-install@65e4f84970763564f46a70b8a54b90d033b3bdda # 4.0.0 + + - name: Update nextcloud/ocp + env: + OCP_BRANCH: ${{ steps.versions.outputs.branches-min }} + run: composer require --dev nextcloud/ocp:dev-$OCP_BRANCH --with-dependencies + + - name: Create pull request + uses: peter-evans/create-pull-request@5f6978faf089d4d20b00c7766989d076bb2fc7f1 # v8.1.1 + with: + token: ${{ secrets.GITHUB_TOKEN }} + commit-message: 'chore(dev-deps): bump nextcloud/ocp package' + committer: GitHub + author: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> + signoff: true + branch: automated/noid/update-nextcloud-ocp + delete-branch: true + title: 'chore(dev-deps): bump nextcloud/ocp package' + add-paths: | + composer.json + composer.lock + body: | + Auto-generated update of the `nextcloud/ocp` development dependency for the minimum supported Nextcloud branch. diff --git a/.gitignore b/.gitignore index e1da34f..fd1ac1d 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,6 @@ +# SPDX-FileCopyrightText: 2026 LibreCode coop and contributors +# SPDX-License-Identifier: AGPL-3.0-or-later + /vendor/ /var/ /.phpunit.cache/ diff --git a/LICENSES/AGPL-3.0-or-later.txt b/LICENSES/AGPL-3.0-or-later.txt new file mode 100644 index 0000000..87cac37 --- /dev/null +++ b/LICENSES/AGPL-3.0-or-later.txt @@ -0,0 +1,232 @@ +GNU AFFERO GENERAL PUBLIC LICENSE +Version 3, 19 November 2007 + +Copyright (C) 2007 Free Software Foundation, Inc. + +Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. + + Preamble + +The GNU Affero General Public License is a free, copyleft license for software and other kinds of works, specifically designed to ensure cooperation with the community in the case of network server software. + +The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, our General Public Licenses are intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. + +When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. + +Developers that use our General Public Licenses protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License which gives you legal permission to copy, distribute and/or modify the software. + +A secondary benefit of defending all users' freedom is that improvements made in alternate versions of the program, if they receive widespread use, become available for other developers to incorporate. Many developers of free software are heartened and encouraged by the resulting cooperation. However, in the case of software used on network servers, this result may fail to come about. The GNU General Public License permits making a modified version and letting the public access it on a server without ever releasing its source code to the public. + +The GNU Affero General Public License is designed specifically to ensure that, in such cases, the modified source code becomes available to the community. It requires the operator of a network server to provide the source code of the modified version running there to the users of that server. Therefore, public use of a modified version, on a publicly accessible server, gives the public access to the source code of the modified version. + +An older license, called the Affero General Public License and published by Affero, was designed to accomplish similar goals. This is a different license, not a version of the Affero GPL, but Affero has released a new version of the Affero GPL which permits relicensing under this license. + +The precise terms and conditions for copying, distribution and modification follow. + + TERMS AND CONDITIONS + +0. Definitions. + +"This License" refers to version 3 of the GNU Affero General Public License. + +"Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. + +"The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. + +To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. + +A "covered work" means either the unmodified Program or a work based on the Program. + +To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. + +To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. + +An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. + +1. Source Code. +The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. + +A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. + +The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce it, or an object code interpreter used to run it. + +The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. + +The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. + +The Corresponding Source for a work in source code form is that same work. + +2. Basic Permissions. +All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. + +You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running them, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running them must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. + +Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. + +3. Protecting Users' Legal Rights From Anti-Circumvention Law. +No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. + +When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. + +4. Conveying Verbatim Copies. +You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. + +You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. + +5. Conveying Modified Source Versions. +You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". + + c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make it do so. + +A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. + +6. Conveying Non-Source Forms. +You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: + + a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. + + d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. + + e) Convey individual copies of the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. + +A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. + +A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of that class of product. + +"Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. + +If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). + +The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. + +Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. + +7. Additional Terms. +"Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. + +When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify them.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. + +Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or authors of the material; or + + e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. + +All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. + +If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. + +Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. + +8. Termination. + +You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). + +However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. + +Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. + +Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. + +9. Acceptance Not Required for Having Copies. + +You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. + +10. Automatic Licensing of Downstream Recipients. + +Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. + +An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. + +You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. + +11. Patents. + +A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". + +A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. + +Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. + +In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. + +If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. + +If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. + +A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. + +Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. + +12. No Surrender of Others' Freedom. + +If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. + +13. Remote Network Interaction; Use with the GNU General Public License. + +Notwithstanding any other provision of this License, if you modify the Program, your modified version must prominently offer all users interacting with it remotely through a computer network (if your version supports such interaction) an opportunity to receive the Corresponding Source of your version by providing access to the Corresponding Source from a network server at no charge, through some standard or customary means of facilitating copying of software. This Corresponding Source shall include the Corresponding Source for any work covered by version 3 of the GNU General Public License that is incorporated pursuant to the following paragraph. + +Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the work with which it is combined will remain governed by version 3 of the GNU General Public License. + +14. Revised Versions of this License. + +The Free Software Foundation may publish revised and/or new versions of the GNU Affero General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. + +Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU Affero General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU Affero General Public License, you may choose any version ever published by the Free Software Foundation. + +If the Program specifies that a proxy can decide which future versions of the GNU Affero General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. + +Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. + +15. Disclaimer of Warranty. + +THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + +16. Limitation of Liability. + +IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. + +17. Interpretation of Sections 15 and 16. + +If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. + +END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + +If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. + +To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. + + This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + +If your software can interact with users remotely through a computer network, you should also make sure that it provides a way for users to get its source. For example, if your program is a web application, its interface could display a "Source" link that leads users to an archive of the code. There are many ways you could offer source, and different solutions will be better for different programs; see section 13 for the specific requirements. + +You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU AGPL, see . diff --git a/LICENSES/CC0-1.0.txt b/LICENSES/CC0-1.0.txt new file mode 100644 index 0000000..0e259d4 --- /dev/null +++ b/LICENSES/CC0-1.0.txt @@ -0,0 +1,121 @@ +Creative Commons Legal Code + +CC0 1.0 Universal + + CREATIVE COMMONS CORPORATION IS NOT A LAW FIRM AND DOES NOT PROVIDE + LEGAL SERVICES. DISTRIBUTION OF THIS DOCUMENT DOES NOT CREATE AN + ATTORNEY-CLIENT RELATIONSHIP. CREATIVE COMMONS PROVIDES THIS + INFORMATION ON AN "AS-IS" BASIS. CREATIVE COMMONS MAKES NO WARRANTIES + REGARDING THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS + PROVIDED HEREUNDER, AND DISCLAIMS LIABILITY FOR DAMAGES RESULTING FROM + THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS PROVIDED + HEREUNDER. + +Statement of Purpose + +The laws of most jurisdictions throughout the world automatically confer +exclusive Copyright and Related Rights (defined below) upon the creator +and subsequent owner(s) (each and all, an "owner") of an original work of +authorship and/or a database (each, a "Work"). + +Certain owners wish to permanently relinquish those rights to a Work for +the purpose of contributing to a commons of creative, cultural and +scientific works ("Commons") that the public can reliably and without fear +of later claims of infringement build upon, modify, incorporate in other +works, reuse and redistribute as freely as possible in any form whatsoever +and for any purposes, including without limitation commercial purposes. +These owners may contribute to the Commons to promote the ideal of a free +culture and the further production of creative, cultural and scientific +works, or to gain reputation or greater distribution for their Work in +part through the use and efforts of others. + +For these and/or other purposes and motivations, and without any +expectation of additional consideration or compensation, the person +associating CC0 with a Work (the "Affirmer"), to the extent that he or she +is an owner of Copyright and Related Rights in the Work, voluntarily +elects to apply CC0 to the Work and publicly distribute the Work under its +terms, with knowledge of his or her Copyright and Related Rights in the +Work and the meaning and intended legal effect of CC0 on those rights. + +1. Copyright and Related Rights. A Work made available under CC0 may be +protected by copyright and related or neighboring rights ("Copyright and +Related Rights"). Copyright and Related Rights include, but are not +limited to, the following: + + i. the right to reproduce, adapt, distribute, perform, display, + communicate, and translate a Work; + ii. moral rights retained by the original author(s) and/or performer(s); +iii. publicity and privacy rights pertaining to a person's image or + likeness depicted in a Work; + iv. rights protecting against unfair competition in regards to a Work, + subject to the limitations in paragraph 4(a), below; + v. rights protecting the extraction, dissemination, use and reuse of data + in a Work; + vi. database rights (such as those arising under Directive 96/9/EC of the + European Parliament and of the Council of 11 March 1996 on the legal + protection of databases, and under any national implementation + thereof, including any amended or successor version of such + directive); and +vii. other similar, equivalent or corresponding rights throughout the + world based on applicable law or treaty, and any national + implementations thereof. + +2. Waiver. To the greatest extent permitted by, but not in contravention +of, applicable law, Affirmer hereby overtly, fully, permanently, +irrevocably and unconditionally waives, abandons, and surrenders all of +Affirmer's Copyright and Related Rights and associated claims and causes +of action, whether now known or unknown (including existing as well as +future claims and causes of action), in the Work (i) in all territories +worldwide, (ii) for the maximum duration provided by applicable law or +treaty (including future time extensions), (iii) in any current or future +medium and for any number of copies, and (iv) for any purpose whatsoever, +including without limitation commercial, advertising or promotional +purposes (the "Waiver"). Affirmer makes the Waiver for the benefit of each +member of the public at large and to the detriment of Affirmer's heirs and +successors, fully intending that such Waiver shall not be subject to +revocation, rescission, cancellation, termination, or any other legal or +equitable action to disrupt the quiet enjoyment of the Work by the public +as contemplated by Affirmer's express Statement of Purpose. + +3. Public License Fallback. Should any part of the Waiver for any reason +be judged legally invalid or ineffective under applicable law, then the +Waiver shall be preserved to the maximum extent permitted taking into +account Affirmer's express Statement of Purpose. In addition, to the +extent the Waiver is so judged Affirmer hereby grants to each affected +person a royalty-free, non transferable, non sublicensable, non exclusive, +irrevocable and unconditional license to exercise Affirmer's Copyright and +Related Rights in the Work (i) in all territories worldwide, (ii) for the +maximum duration provided by applicable law or treaty (including future +time extensions), (iii) in any current or future medium and for any number +of copies, and (iv) for any purpose whatsoever, including without +limitation commercial, advertising or promotional purposes (the +"License"). The License shall be deemed effective as of the date CC0 was +applied by Affirmer to the Work. Should any part of the License for any +reason be judged legally invalid or ineffective under applicable law, such +partial invalidity or ineffectiveness shall not invalidate the remainder +of the License, and in such case Affirmer hereby affirms that he or she +will not (i) exercise any of his or her remaining Copyright and Related +Rights in the Work or (ii) assert any associated claims and causes of +action with respect to the Work, in either case contrary to Affirmer's +express Statement of Purpose. + +4. Limitations and Disclaimers. + + a. No trademark or patent rights held by Affirmer are waived, abandoned, + surrendered, licensed or otherwise affected by this document. + b. Affirmer offers the Work as-is and makes no representations or + warranties of any kind concerning the Work, express, implied, + statutory or otherwise, including without limitation warranties of + title, merchantability, fitness for a particular purpose, non + infringement, or the absence of latent or other defects, accuracy, or + the present or absence of errors, whether or not discoverable, all to + the greatest extent permissible under applicable law. + c. Affirmer disclaims responsibility for clearing rights of other persons + that may apply to the Work or any use thereof, including without + limitation any person's Copyright and Related Rights in the Work. + Further, Affirmer disclaims responsibility for obtaining any necessary + consents, permissions or other rights required for any use of the + Work. + d. Affirmer understands and acknowledges that Creative Commons is not a + party to this document and has no duty or obligation with respect to + this CC0 or use of the Work. diff --git a/LICENSES/MIT.txt b/LICENSES/MIT.txt new file mode 100644 index 0000000..d817195 --- /dev/null +++ b/LICENSES/MIT.txt @@ -0,0 +1,18 @@ +MIT License + +Copyright (c) + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and +associated documentation files (the "Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the +following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial +portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT +LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO +EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/README.md b/README.md index 55fb13c..ae633f1 100644 --- a/README.md +++ b/README.md @@ -1,45 +1,54 @@ + + # Usage Statistics Server -A generic server for receiving, storing, aggregating, and exposing privacy-preserving usage statistics from participating applications. +A generic Nextcloud app for receiving, storing, aggregating, and exposing privacy-preserving usage statistics from participating applications. -This project is intentionally application-agnostic. LibreSign is expected to be its first real consumer, but the protocol and storage model must not depend on LibreSign-specific concepts. +LibreSign is expected to be its first real consumer, but the protocol and storage model are application-agnostic so other Nextcloud apps can use the same server. ## Goals - Receive opt-in, self-reported usage statistics from applications. - Preserve historical reports instead of only the latest snapshot. - Support both current-state and time-series aggregations. -- Keep the ingestion protocol small, versioned, and implementation-independent. +- Keep the ingestion protocol small and versioned. - Provide strict schema and payload validation. - Make repeated submissions for the same reporting period idempotent. - Treat submitted data as voluntary self-reported statistics, not as an authoritative census. - Provide operational abuse protection without pretending to solve client-side data falsification. +- Use native Nextcloud APIs for persistence, migrations, routing, administration, and background processing. ## Non-goals - Collect personal data or user-level event streams. - Prove that a self-hosted client reports truthful values. - Require a central registration or handshake before a client can submit a report. -- Couple the protocol to Nextcloud, LibreSign, or any specific frontend framework. +- Depend on LibreSign-specific concepts in the protocol or database model. + +## Architecture -## Planned architecture +The server is a native Nextcloud app supporting Nextcloud 35 and 36. -The initial design separates reports from their individual metric values: +The storage model separates current installation state from immutable report history: -- `applications`: logical producers of statistics; -- `reports`: immutable reporting-period submissions associated with an installation; -- `metrics`: typed values belonging to a report; -- aggregation/query services for latest-state and historical views. +- `usage_stats_installations`: materialized current state for each application/installation pair; +- `usage_stats_reports`: immutable reporting-period submissions; +- `usage_stats_metrics`: typed metric values belonging to reports. -The exact persistence and application framework will be selected after the v1 protocol and threat model are reviewed. +This allows current-state queries to use only the latest report for each installation while historical queries continue to use all reports. ## Protocol -The protocol specification lives in [`docs/protocol-v1.md`](docs/protocol-v1.md). +The ingestion protocol specification lives in [`docs/protocol-v1.md`](docs/protocol-v1.md). + +Administrative query endpoints are documented in [`docs/admin-api.md`](docs/admin-api.md). ## Data reliability -Reports are self-declared by participating installations. Server-side validation can verify protocol conformance, reject malformed values, make retries idempotent, limit abuse, and identify statistical anomalies. It cannot prove that software running on infrastructure controlled by the sender reported truthful application data. +Reports are self-declared by participating installations. Server-side validation can verify protocol conformance, reject malformed values, make retries idempotent, limit operational abuse, and identify statistical anomalies. It cannot prove that software running on infrastructure controlled by the sender reported truthful application data. Public or product-facing statistics must therefore be described as statistics reported by participating installations, not as an audited count of all installations. diff --git a/REUSE.toml b/REUSE.toml new file mode 100644 index 0000000..15928ba --- /dev/null +++ b/REUSE.toml @@ -0,0 +1,31 @@ +# SPDX-FileCopyrightText: 2026 Vitor Mattos +# SPDX-License-Identifier: AGPL-3.0-or-later + +version = 1 +SPDX-PackageName = "usage-statistics-server" +SPDX-PackageDownloadLocation = "https://github.com/vitormattos/usage-statistics-server/" + +default-license = "AGPL-3.0-or-later" +default-copyright = "2026 Vitor Mattos" + +[[annotations]] +path = [ + "composer.json", + "composer.lock", + "openapi*.json", + "package.json", + "package-lock.json", + "phpstan.neon", + "psalm.xml", + "tests/integration/composer.json", + "tests/integration/composer.lock", + "tests/integration/features/api/schema_aggregation.feature", + "tests/integration/features/api/usage_statistics.feature", + "tests/php/phpunit.xml", + "tsconfig.json", + "vendor-bin/**/composer.json", + "vendor-bin/**/composer.lock" +] +precedence = "aggregate" +SPDX-FileCopyrightText = "2026 Vitor Mattos" +SPDX-License-Identifier = "AGPL-3.0-or-later" diff --git a/appinfo/info.xml b/appinfo/info.xml new file mode 100644 index 0000000..790b908 --- /dev/null +++ b/appinfo/info.xml @@ -0,0 +1,29 @@ + + + + + + usage_statistics_server + Usage Statistics Server + Receive and aggregate privacy-preserving usage statistics. + + 0.1.0 + agpl + LibreCode + UsageStatisticsServer + tools + https://github.com/vitormattos/usage-statistics-server/issues + https://github.com/vitormattos/usage-statistics-server + + + + + OCA\UsageStatisticsServer\BackgroundJob\CleanupOldData + + diff --git a/composer.json b/composer.json index 730a4ba..c638f3e 100644 --- a/composer.json +++ b/composer.json @@ -1,50 +1,58 @@ { "name": "vitormattos/usage-statistics-server", - "description": "Generic server for privacy-preserving usage statistics.", + "description": "Nextcloud app for receiving and aggregating privacy-preserving usage statistics.", "type": "project", "license": "AGPL-3.0-or-later", "require": { - "php": ">=8.4", - "ext-ctype": "*", - "ext-iconv": "*", - "ext-pdo": "*", - "doctrine/dbal": "^4.2", - "doctrine/doctrine-bundle": "^3.0", - "doctrine/doctrine-migrations-bundle": "^4.0", - "symfony/console": "8.1.*", - "symfony/dotenv": "8.1.*", - "symfony/framework-bundle": "8.1.*", - "symfony/runtime": "8.1.*", - "symfony/yaml": "8.1.*" + "php": ">=8.3" }, "require-dev": { + "bamarni/composer-bin-plugin": "^1.8", + "nextcloud/ocp": "dev-master", "phpunit/phpunit": "^11.5", - "symfony/browser-kit": "8.1.*", - "symfony/css-selector": "8.1.*" + "roave/security-advisories": "dev-latest" }, "autoload": { "psr-4": { - "App\\": "src/", - "DoctrineMigrations\\": "migrations/" + "OCA\\UsageStatisticsServer\\": "lib/" } }, "autoload-dev": { "psr-4": { - "App\\Tests\\": "tests/" + "OCP\\": "vendor/nextcloud/ocp/OCP", + "OCA\\UsageStatisticsServer\\Tests\\": "tests/php/" } }, "scripts": { - "test": "phpunit" + "lint": "find . -name \\*.php -not -path './vendor/*' -not -path './vendor-bin/*' -not -path './node_modules/*' -not -path './build/*' -print0 | xargs -0 -n1 php -l", + "mutation:test": "php vendor-bin/infection/vendor/infection/infection/bin/infection --configuration=infection.json5", + "openapi": "generate-spec --verbose && npm run typescript:generate", + "phpstan": "php vendor-bin/phpstan/vendor/phpstan/phpstan/phpstan analyse -c phpstan.neon", + "psalm": "psalm --no-cache --threads=$(nproc)", + "test:unit": "phpunit -c tests/php/phpunit.xml --testsuite unit --no-coverage --colors=always --fail-on-warning --fail-on-risky --display-deprecations --display-phpunit-deprecations", + "test:php": "phpunit -c tests/php/phpunit.xml --no-coverage --colors=always --fail-on-warning --fail-on-risky --display-deprecations --display-phpunit-deprecations", + "post-install-cmd": [ + "@composer bin all install --ansi", + "composer dump-autoload -o" + ], + "post-update-cmd": [ + "composer dump-autoload" + ] + }, + "extra": { + "bamarni-bin": { + "bin-links": true, + "forward-command": true + } }, "config": { "allow-plugins": { - "symfony/runtime": true + "bamarni/composer-bin-plugin": true }, - "sort-packages": true - }, - "extra": { - "symfony": { - "require": "8.1.*" + "optimize-autoloader": true, + "sort-packages": true, + "platform": { + "php": "8.3" } } } diff --git a/config/bundles.php b/config/bundles.php deleted file mode 100644 index 3d084b4..0000000 --- a/config/bundles.php +++ /dev/null @@ -1,9 +0,0 @@ - ['all' => true], - Doctrine\Bundle\DoctrineBundle\DoctrineBundle::class => ['all' => true], - Doctrine\Bundle\MigrationsBundle\DoctrineMigrationsBundle::class => ['all' => true], -]; diff --git a/config/packages/doctrine.yaml b/config/packages/doctrine.yaml deleted file mode 100644 index 365248d..0000000 --- a/config/packages/doctrine.yaml +++ /dev/null @@ -1,4 +0,0 @@ -doctrine: - dbal: - url: '%env(resolve:DATABASE_URL)%' - use_savepoints: true diff --git a/config/packages/doctrine_migrations.yaml b/config/packages/doctrine_migrations.yaml deleted file mode 100644 index 7a17beb..0000000 --- a/config/packages/doctrine_migrations.yaml +++ /dev/null @@ -1,4 +0,0 @@ -doctrine_migrations: - migrations_paths: - 'DoctrineMigrations': '%kernel.project_dir%/migrations' - enable_profiler: false diff --git a/config/packages/framework.yaml b/config/packages/framework.yaml deleted file mode 100644 index 3f12fc9..0000000 --- a/config/packages/framework.yaml +++ /dev/null @@ -1,11 +0,0 @@ -framework: - secret: '%env(APP_SECRET)%' - handle_all_throwables: true - router: - utf8: true - php_errors: - log: true - -test: - framework: - test: true diff --git a/config/routes.yaml b/config/routes.yaml deleted file mode 100644 index 2d0ef99..0000000 --- a/config/routes.yaml +++ /dev/null @@ -1,5 +0,0 @@ -controllers: - resource: - path: ../src/Controller/ - namespace: App\Controller - type: attribute diff --git a/config/services.yaml b/config/services.yaml deleted file mode 100644 index ada9508..0000000 --- a/config/services.yaml +++ /dev/null @@ -1,9 +0,0 @@ -services: - _defaults: - autowire: true - autoconfigure: true - - App\: - resource: '../src/' - exclude: - - '../src/Kernel.php' diff --git a/docs/admin-api.md b/docs/admin-api.md new file mode 100644 index 0000000..cb34d1e --- /dev/null +++ b/docs/admin-api.md @@ -0,0 +1,127 @@ + + +# Administrative statistics API + +The administrative API exposes aggregated usage statistics to authenticated Nextcloud administrators. These endpoints are not public by default. + +All endpoints use the OCS namespace of the `usage_statistics_server` app. + +The API intentionally exposes aggregates rather than individual installation reports. Normalized reports remain internal so later privacy thresholds and abuse filtering can be applied without changing the public contract. The server does not retain the arbitrary raw JSON request body after validation. + +## Summary + +`GET /ocs/v2.php/apps/usage_statistics_server/api/v1/admin/applications/{application}` + +Returns the number of installations that submitted a valid report during the active window. + +The active window is currently fixed at 45 days. + +Example response data: + +```json +{ + "application": "libresign", + "activeWindowDays": 45, + "activeInstallations": 142 +} +``` + +`activeInstallations` means installations reporting usage statistics within the last 45 days. It must not be presented as the total number of installations of the application. + +## Current distribution + +`GET /ocs/v2.php/apps/usage_statistics_server/api/v1/admin/applications/{application}/metrics/{category}/{key}/distribution` + +Returns a categorical distribution using only the latest report for every known installation. + +Example: + +```json +{ + "application": "libresign", + "category": "server", + "key": "version", + "values": [ + {"value": "12.0.0", "count": 80}, + {"value": "11.0.2", "count": 45} + ] +} +``` + +This endpoint represents current state. Older reports from the same installation do not contribute to the distribution. + +## Current numerical evaluation + +`GET /ocs/v2.php/apps/usage_statistics_server/api/v1/admin/applications/{application}/metrics/{category}/{key}/numerical` + +Returns the standard numerical evaluation for a numeric metric using only the latest report from each installation. + +The shape follows the same useful aggregation set used by Nextcloud's `survey_server`: count, average, minimum, maximum, and total. + +```json +{ + "application": "libresign", + "category": "usage", + "key": "requests_completed", + "statistics": { + "count": 142, + "average": 26.34, + "min": 0, + "max": 820, + "total": 3740 + } +} +``` + +## Numerical history + +`GET /ocs/v2.php/apps/usage_statistics_server/api/v1/admin/applications/{application}/metrics/{category}/{key}/numerical/history` + +Optional query parameters: + +- `from`: ISO 8601 timestamp; +- `to`: ISO 8601 timestamp. + +When omitted, `to` defaults to the current time and `from` defaults to one year before `to`. + +Reports are grouped by their reporting period. Individual installation values are not returned by this endpoint. + +```json +{ + "application": "libresign", + "category": "usage", + "key": "requests_completed", + "from": "2026-01-01T00:00:00+00:00", + "to": "2026-09-01T00:00:00+00:00", + "periods": [ + { + "periodStart": "2026-07-01 00:00:00", + "periodEnd": "2026-08-01 00:00:00", + "count": 120, + "average": 22.4, + "min": 0, + "max": 820, + "total": 2688 + } + ] +} +``` + +## Reference to survey_server + +The Nextcloud `survey_server` is used as prior art for OCS ingestion and aggregation conventions. In particular, its distinction between diagram-like categorical statistics and numerical evaluation is useful and is retained here. + +This app differs intentionally in important areas: + +- historical reports are preserved instead of replacing the previous report from an installation; +- latest installation state is materialized separately from report history; +- metrics are explicitly typed by the protocol and stored in typed columns; +- application schemas are versioned; +- individual report values are not exposed through the administrative statistics API. + +## Interpretation + +Reports are voluntary self-reported data. These APIs provide usage indicators and operational statistics, not an authenticated census. Consumers must preserve this distinction when displaying or publishing derived numbers. diff --git a/docs/application-schemas.md b/docs/application-schemas.md new file mode 100644 index 0000000..b5b0847 --- /dev/null +++ b/docs/application-schemas.md @@ -0,0 +1,94 @@ + + +# Application metric schemas + +The server uses versioned application schemas as an allowlist and interpretation contract for submitted metrics. + +This is inspired by the role of `data.json` in Nextcloud's `survey_server`, but the schema is scoped to an application and version so unrelated applications can evolve independently. + +## Definition + +Example: + +```json +{ + "application": "libresign", + "schemaVersion": 1, + "metrics": [ + { + "category": "server", + "key": "version", + "type": "string", + "kind": "snapshot", + "aggregation": "distribution", + "description": "LibreSign version", + "required": true + }, + { + "category": "usage", + "key": "requests_completed", + "type": "integer", + "kind": "period", + "aggregation": "numerical", + "description": "Completed signing requests during the reporting period", + "required": true + } + ] +} +``` + +## Metric fields + +- `category`: stable metric namespace; +- `key`: stable metric identifier inside the category; +- `type`: `integer`, `number`, `boolean`, or `string`; +- `kind`: `snapshot`, `period`, `counter`, or `categorical`; +- `aggregation`: `distribution`, `numerical`, or `none`; +- `description`: human-readable meaning; +- `required`: whether every report using this schema version must contain the metric. + +`numerical` aggregation is only valid for `integer` and `number` metrics. + +## Registration + +Schemas are registered by a Nextcloud administrator: + +```text +POST /ocs/v2.php/apps/usage_statistics_server/api/v1/admin/schemas +``` + +The request body is the schema definition JSON. + +A stored schema can be inspected with: + +```text +GET /ocs/v2.php/apps/usage_statistics_server/api/v1/admin/schemas/{application}/{schemaVersion} +``` + +Registration is idempotent when the same definition is submitted again. + +A schema version is immutable after it is registered. Reusing the same `(application, schemaVersion)` with a different definition returns a conflict. Applications must increment `schemaVersion` when the contract changes. + +## Ingestion behavior + +A report is accepted only when its `(application, schemaVersion)` is registered. + +The server rejects a report when: + +- its schema is not registered; +- it contains a metric not present in the schema; +- a metric type does not match the schema; +- a required metric is missing. + +This makes the schema an explicit allowlist rather than allowing arbitrary metric names into storage. + +## Evolution + +Schemas are immutable so historical reports keep the interpretation they had when received. + +If a metric meaning or type changes incompatibly, prefer both a new `schemaVersion` and a new metric key. This keeps historical aggregates unambiguous when a query spans multiple schema versions. + +Adding an optional metric or changing presentation metadata still requires a new `schemaVersion`; the client and server contract should never depend on silently changing a registered definition. diff --git a/docs/protocol-v1.md b/docs/protocol-v1.md index 6cedb8a..7b608bc 100644 --- a/docs/protocol-v1.md +++ b/docs/protocol-v1.md @@ -1,3 +1,8 @@ + + # Usage Statistics Protocol v1 ## Purpose @@ -18,6 +23,16 @@ POST /api/v1/reports The server SHOULD support idempotent resubmission of the same logical report. +A successful submission, including an idempotent retry, returns the same application-level response: + +```json +{ + "status": "accepted" +} +``` + +The protocol does not expose internal database identifiers and does not require the server to tell the client whether a successful submission created a row or matched an existing report. + ## Report Example: @@ -79,6 +94,10 @@ Version of the metric schema defined by the sending application. The server stores this value so historical reports remain interpretable after an application evolves its metrics. +The `usage_statistics_server` implementation requires the `(application, schemaVersion)` definition to be registered by an administrator before reports using it are accepted. Registered schema versions are immutable. + +A schema version is report content, not part of report identity. Applications SHOULD activate a new schema at a reporting-period boundary. A second submission for the same installation and period using another schema version is a conflict, not another report. + ### `period` The reporting interval represented by period metrics. @@ -120,26 +139,47 @@ Application schemas SHOULD document whether each metric is one of: Servers MUST NOT blindly sum repeated snapshots across periods. +The `usage_statistics_server` application schema also declares the allowed aggregation for each metric (`distribution`, `numerical`, or `none`). + ## Idempotency The logical identity of a report is: ```text -(application, installationId, period.start, period.end, schemaVersion) +(application, installationId, period.start, period.end) ``` A server MUST prevent accidental duplicate storage for the same logical report. +`schemaVersion` is intentionally excluded from this identity. Otherwise a schema transition during one period could create two reports and double-count that installation. + Protocol v1 does not require a preliminary handshake or server-issued report token. -A repeated submission MAY: +The `usage_statistics_server` implementation keeps the first accepted report immutable: + +- a retry using the same schema version is accepted idempotently; +- a retry for the same logical period using another schema version is rejected as a conflict; +- neither case creates a second logical report. + +## Current installation state + +Historical reports can arrive out of order, so receive order MUST NOT decide which report represents the current state of an installation. -- replace the existing report for that logical identity; or -- be rejected as already received; +The `usage_statistics_server` implementation orders reports by reporting period: -but it MUST NOT create a second logical report that would double-count statistics. +1. the report with the later `period.end` is newer; +2. when `period.end` is equal, the report with the later `period.start` is newer; +3. the current report pointer only moves forward according to that ordering. -The server implementation MUST document which behavior it uses. +`last_seen_at` is independent from the current report pointer and records recent valid reporting activity. This means an older delayed report can refresh the installation activity timestamp without replacing its current metric snapshot. + +The current-state update is performed with a conditional database update rather than a read-then-write decision, so concurrent submissions cannot make the pointer move backwards. + +## Storage guidance + +Servers SHOULD persist normalized validated fields rather than the arbitrary request body. + +The `usage_statistics_server` implementation does not retain the raw JSON payload. Metric values are stored in typed columns according to their declared type, with exactly one value column populated for each metric. ## Validation @@ -153,8 +193,9 @@ The server MUST validate at least: - metric count per report; - category/key format and length; - metric type/value compatibility; -- scalar value size; -- application-specific schema when configured. +- scalar value size. + +The `usage_statistics_server` implementation additionally requires a registered application schema and rejects unknown metrics, type mismatches, and missing required metrics. Invalid reports MUST NOT be partially persisted. diff --git a/docs/retention.md b/docs/retention.md new file mode 100644 index 0000000..ab16ed0 --- /dev/null +++ b/docs/retention.md @@ -0,0 +1,54 @@ + + +# Historical data retention + +The server preserves report history so usage trends can be recomputed and compared over time. Historical data is not retained indefinitely by default. + +## Default + +The default retention period is 1095 days (three years). + +A daily, time-insensitive Nextcloud background job removes data older than the configured retention period. + +Cleanup removes: + +- stale installation state whose last report is older than the cutoff; +- metrics belonging to expired reports; +- expired reports. + +Registered application schemas are preserved because they define how retained and externally referenced report versions are interpreted. + +## Limits + +Retention can be configured between 45 and 3650 days. + +The minimum matches the active-installation window. Allowing a shorter retention period would make the server forget installations that should still qualify as reporting within the last 45 days. + +## Administrative API + +Read the current value: + +```text +GET /ocs/v2.php/apps/usage_statistics_server/api/v1/admin/settings +``` + +Update it: + +```text +PUT /ocs/v2.php/apps/usage_statistics_server/api/v1/admin/settings +``` + +with `retentionDays` as an integer value. + +The setting is stored using Nextcloud `IAppConfig` as an integer. + +## Operational behavior + +Report deletion is performed in batches of 500 reports to avoid a single large cleanup transaction. Metrics are deleted before their parent reports in the same transaction. + +Retention is based on the server-side `received_at` timestamp, not on a client-provided timestamp. This prevents a client-controlled period value from extending server retention. + +The approach is inspired by the configurable cleanup in Nextcloud's `survey_server`, but this application uses a finite default because it intentionally preserves historical reports rather than replacing each installation's previous snapshot. diff --git a/eslint.config.mjs b/eslint.config.mjs new file mode 100644 index 0000000..0502f0c --- /dev/null +++ b/eslint.config.mjs @@ -0,0 +1,19 @@ +/* + * SPDX-FileCopyrightText: 2026 LibreCode coop and contributors + * SPDX-License-Identifier: AGPL-3.0-or-later + */ + +import { recommended } from '@nextcloud/eslint-config' + +export default [ + ...recommended, + { + name: 'usage-statistics-server/ignores', + ignores: [ + 'build/*', + 'node_modules/*', + 'src/types/openapi/*', + 'openapi*.json', + ], + }, +] diff --git a/infection.json5 b/infection.json5 new file mode 100644 index 0000000..16f2640 --- /dev/null +++ b/infection.json5 @@ -0,0 +1,24 @@ +// SPDX-FileCopyrightText: 2026 LibreCode coop and contributors +// SPDX-License-Identifier: AGPL-3.0-or-later + +{ + "$schema": "https://raw.githubusercontent.com/infection/infection/0.35.2/resources/schema.json", + "source": { + "directories": [ + "lib" + ], + "excludes": [ + "AppInfo", + "Migration" + ] + }, + "bootstrap": "tests/php/infection-bootstrap.php", + "phpUnit": { + "configDir": "tests/php" + }, + "minMsi": 97, + "minCoveredMsi": 97, + "mutators": { + "@default": true + } +} diff --git a/lib/AppInfo/Application.php b/lib/AppInfo/Application.php new file mode 100644 index 0000000..4974793 --- /dev/null +++ b/lib/AppInfo/Application.php @@ -0,0 +1,32 @@ +setInterval(60 * 60 * 24); + $this->setTimeSensitivity(self::TIME_INSENSITIVE); + } + + #[\Override] + protected function run(mixed $argument): void { + $retentionDays = $this->settings->getRetentionDays(); + $cutoff = (new \DateTimeImmutable('@' . ($this->time->getTime() - ($retentionDays * 86400)))) + ->setTimezone(new \DateTimeZone('UTC')); + + $this->retention->cleanupBefore($cutoff); + } +} diff --git a/lib/Controller/ReportController.php b/lib/Controller/ReportController.php new file mode 100644 index 0000000..1a7aee0 --- /dev/null +++ b/lib/Controller/ReportController.php @@ -0,0 +1,95 @@ + $metrics Aggregate metric values + * + * @return DataResponse|DataResponse + * + * 200: Report accepted + * 400: Invalid report + * 409: Conflicting report for the reporting period + */ + #[PublicPage] + #[NoCSRFRequired] + #[AnonRateLimit(limit: 60, period: 3600)] + #[ApiRoute(verb: 'POST', url: '/api/{apiVersion}/reports', requirements: ['apiVersion' => '(v1)'])] + public function create( + int $protocolVersion, + string $application, + string $installationId, + int $schemaVersion, + array $period, + array $metrics, + ): DataResponse { + try { + $report = $this->factory->fromPayload([ + 'protocolVersion' => $protocolVersion, + 'application' => $application, + 'installationId' => $installationId, + 'schemaVersion' => $schemaVersion, + 'period' => $period, + 'metrics' => $metrics, + ]); + $schema = $this->schemas->find($report->application, $report->schemaVersion); + if ($schema === null) { + throw new InvalidReport('Application schema is not registered.'); + } + $this->schemaValidator->validateReport($report, $schema); + $this->repository->store($report); + } catch (InvalidReport $e) { + return new DataResponse(['error' => 'invalid_report', 'message' => $e->getMessage()], Http::STATUS_BAD_REQUEST); + } catch (ConflictingReport $e) { + return new DataResponse(['error' => 'conflicting_report', 'message' => $e->getMessage()], Http::STATUS_CONFLICT); + } + + return new DataResponse(['status' => 'accepted'], Http::STATUS_OK); + } +} diff --git a/lib/Controller/SchemaController.php b/lib/Controller/SchemaController.php new file mode 100644 index 0000000..37c3981 --- /dev/null +++ b/lib/Controller/SchemaController.php @@ -0,0 +1,101 @@ + $metrics Metric definitions + * + * @return DataResponse|DataResponse + * + * 200: Schema was already registered with the same definition + * 201: Schema registered + * 400: Invalid schema definition + * 409: Schema version already exists with another definition + */ + #[ApiRoute(verb: 'POST', url: '/api/{apiVersion}/admin/schemas', requirements: ['apiVersion' => '(v1)'])] + public function create(string $application, int $schemaVersion, array $metrics): DataResponse { + try { + $definition = $this->validator->validateDefinition([ + 'application' => $application, + 'schemaVersion' => $schemaVersion, + 'metrics' => $metrics, + ]); + $created = $this->schemas->store( + $definition['application'], + $definition['schemaVersion'], + $definition, + ); + } catch (InvalidReport $e) { + return new DataResponse([ + 'error' => 'invalid_schema', + 'message' => $e->getMessage(), + ], Http::STATUS_BAD_REQUEST); + } catch (\LogicException $e) { + return new DataResponse([ + 'error' => 'schema_conflict', + 'message' => $e->getMessage(), + ], Http::STATUS_CONFLICT); + } + + return new DataResponse([ + 'application' => $definition['application'], + 'schemaVersion' => $definition['schemaVersion'], + 'status' => $created ? 'created' : 'already_registered', + ], $created ? Http::STATUS_CREATED : Http::STATUS_OK); + } + + /** + * Get one registered application metric schema + * + * @param string $application Stable application identifier + * @param int $schemaVersion Schema version + * + * @return DataResponse, array{}>|DataResponse + * + * 200: Registered schema definition + * 404: Schema not found + */ + #[ApiRoute(verb: 'GET', url: '/api/{apiVersion}/admin/schemas/{application}/{schemaVersion}', requirements: ['apiVersion' => '(v1)'])] + public function get(string $application, int $schemaVersion): DataResponse { + $definition = $this->schemas->find($application, $schemaVersion); + if ($definition === null) { + return new DataResponse([ + 'error' => 'schema_not_found', + ], Http::STATUS_NOT_FOUND); + } + + return new DataResponse($definition); + } +} diff --git a/lib/Controller/SettingsController.php b/lib/Controller/SettingsController.php new file mode 100644 index 0000000..7be2175 --- /dev/null +++ b/lib/Controller/SettingsController.php @@ -0,0 +1,69 @@ + + * + * 200: Current server settings + */ + #[ApiRoute(verb: 'GET', url: '/api/{apiVersion}/admin/settings', requirements: ['apiVersion' => '(v1)'])] + public function get(): DataResponse { + return new DataResponse([ + 'retentionDays' => $this->settings->getRetentionDays(), + 'minimumRetentionDays' => SettingsService::MIN_RETENTION_DAYS, + 'maximumRetentionDays' => SettingsService::MAX_RETENTION_DAYS, + ]); + } + + /** + * Update usage statistics server settings + * + * @param int $retentionDays Number of days to retain reports + * + * @return DataResponse|DataResponse + * + * 200: Server settings updated + * 400: Invalid retention value + */ + #[ApiRoute(verb: 'PUT', url: '/api/{apiVersion}/admin/settings', requirements: ['apiVersion' => '(v1)'])] + public function update(int $retentionDays): DataResponse { + try { + $retentionDays = $this->settings->setRetentionDays($retentionDays); + } catch (\InvalidArgumentException $e) { + return new DataResponse([ + 'error' => 'invalid_retention', + 'message' => $e->getMessage(), + ], Http::STATUS_BAD_REQUEST); + } + + return new DataResponse(['retentionDays' => $retentionDays]); + } +} diff --git a/lib/Controller/StatisticsController.php b/lib/Controller/StatisticsController.php new file mode 100644 index 0000000..02d99c2 --- /dev/null +++ b/lib/Controller/StatisticsController.php @@ -0,0 +1,235 @@ + + * + * 200: Application usage statistics summary + */ + #[ApiRoute(verb: 'GET', url: '/api/{apiVersion}/admin/applications/{application}', requirements: ['apiVersion' => '(v1)'])] + public function summary(string $application): DataResponse { + $since = new \DateTimeImmutable( + sprintf('-%d days', self::ACTIVE_WINDOW_DAYS), + new \DateTimeZone('UTC'), + ); + + return new DataResponse([ + 'application' => $application, + 'activeWindowDays' => self::ACTIVE_WINDOW_DAYS, + 'activeInstallations' => $this->statistics->countActiveInstallations($application, $since), + ]); + } + + /** + * Get the current distribution for a metric + * + * @param string $application Stable application identifier + * @param string $category Metric category + * @param string $key Metric key + * + * @return DataResponse}, array{}>|DataResponse + * + * 200: Current metric distribution + * 400: Metric does not support distribution aggregation + * 404: Metric is not registered + */ + #[ApiRoute(verb: 'GET', url: '/api/{apiVersion}/admin/applications/{application}/metrics/{category}/{key}/distribution', requirements: ['apiVersion' => '(v1)'])] + public function distribution(string $application, string $category, string $key): DataResponse { + $type = $this->metricTypeForAggregation($application, $category, $key, 'distribution'); + if ($type instanceof DataResponse) { + return $type; + } + + return new DataResponse([ + 'application' => $application, + 'category' => $category, + 'key' => $key, + 'values' => $this->statistics->currentDistribution($application, $category, $key), + ]); + } + + /** + * Get the current numerical evaluation for a metric + * + * @param string $application Stable application identifier + * @param string $category Metric category + * @param string $key Metric key + * + * @return DataResponse|DataResponse + * + * 200: Current numerical metric evaluation + * 400: Metric does not support numerical aggregation + * 404: Metric is not registered + */ + #[ApiRoute(verb: 'GET', url: '/api/{apiVersion}/admin/applications/{application}/metrics/{category}/{key}/numerical', requirements: ['apiVersion' => '(v1)'])] + public function numerical(string $application, string $category, string $key): DataResponse { + $type = $this->metricTypeForAggregation($application, $category, $key, 'numerical'); + if ($type instanceof DataResponse) { + return $type; + } + + return new DataResponse([ + 'application' => $application, + 'category' => $category, + 'key' => $key, + 'statistics' => $this->statistics->currentNumericalEvaluation($application, $category, $key, $type), + ]); + } + + /** + * Get historical numerical evaluation for a metric + * + * @param string $application Stable application identifier + * @param string $category Metric category + * @param string $key Metric key + * @param string $from Optional RFC3339 lower bound + * @param string $to Optional RFC3339 upper bound + * + * @return DataResponse}, array{}>|DataResponse + * + * 200: Historical numerical metric evaluation + * 400: Invalid date range or metric aggregation + * 404: Metric is not registered + */ + #[ApiRoute(verb: 'GET', url: '/api/{apiVersion}/admin/applications/{application}/metrics/{category}/{key}/numerical/history', requirements: ['apiVersion' => '(v1)'])] + public function numericalHistory( + string $application, + string $category, + string $key, + string $from = '', + string $to = '', + ): DataResponse { + $type = $this->metricTypeForAggregation($application, $category, $key, 'numerical'); + if ($type instanceof DataResponse) { + return $type; + } + + try { + $range = $this->parseRange($from, $to); + } catch (\InvalidArgumentException $e) { + return new DataResponse([ + 'error' => 'invalid_range', + 'message' => $e->getMessage(), + ], Http::STATUS_BAD_REQUEST); + } + + return new DataResponse([ + 'application' => $application, + 'category' => $category, + 'key' => $key, + 'from' => $range['from']->format(DATE_ATOM), + 'to' => $range['to']->format(DATE_ATOM), + 'periods' => $this->statistics->numericalHistory( + $application, + $category, + $key, + $type, + $range['from'], + $range['to'], + ), + ]); + } + + /** @return string|DataResponse */ + private function metricTypeForAggregation(string $application, string $category, string $key, string $aggregation): string|DataResponse { + $metric = $this->schemas->findMetric($application, $category, $key); + if ($metric === null) { + return new DataResponse([ + 'error' => 'metric_not_found', + 'message' => 'Metric is not registered for this application.', + ], Http::STATUS_NOT_FOUND); + } + + if (($metric['aggregation'] ?? null) !== $aggregation) { + return new DataResponse([ + 'error' => 'invalid_aggregation', + 'message' => "Metric does not support {$aggregation} aggregation.", + ], Http::STATUS_BAD_REQUEST); + } + + $type = $metric['type'] ?? null; + if (!is_string($type)) { + throw new \LogicException('Registered metric type must be a string.'); + } + + return $type; + } + + /** @return array{from:\DateTimeImmutable,to:\DateTimeImmutable} */ + private function parseRange(string $from, string $to): array { + $utc = new \DateTimeZone('UTC'); + $rangeTo = $to === '' ? new \DateTimeImmutable('now', $utc) : $this->parseDate($to); + $rangeFrom = $from === '' ? $rangeTo->modify('-1 year') : $this->parseDate($from); + + if ($rangeFrom > $rangeTo) { + throw new \InvalidArgumentException('The from value must be before or equal to the to value.'); + } + + return ['from' => $rangeFrom, 'to' => $rangeTo]; + } + + private function parseDate(string $value): \DateTimeImmutable { + if (preg_match(self::RFC3339_PATTERN, $value, $matches) !== 1) { + throw new \InvalidArgumentException('Dates must use RFC3339.'); + } + + $year = (int)$matches[1]; + $month = (int)$matches[2]; + $day = (int)$matches[3]; + $hour = (int)$matches[4]; + $minute = (int)$matches[5]; + $second = (int)$matches[6]; + if (!checkdate($month, $day, $year) || $hour > 23 || $minute > 59 || $second > 59) { + throw new \InvalidArgumentException('Dates must use RFC3339.'); + } + + $timezone = $matches[8]; + if ($timezone !== 'Z') { + [$timezoneHour, $timezoneMinute] = array_map('intval', explode(':', substr($timezone, 1))); + if ($timezoneHour > 23 || $timezoneMinute > 59) { + throw new \InvalidArgumentException('Dates must use RFC3339.'); + } + } + + try { + return (new \DateTimeImmutable($value))->setTimezone(new \DateTimeZone('UTC')); + } catch (\Exception) { + throw new \InvalidArgumentException('Dates must use RFC3339.'); + } + } +} diff --git a/lib/Db/ReportRepository.php b/lib/Db/ReportRepository.php new file mode 100644 index 0000000..7065311 --- /dev/null +++ b/lib/Db/ReportRepository.php @@ -0,0 +1,209 @@ +storeWithRetry($report, true); + } + + /** @return array{id:int,created:bool} */ + private function storeWithRetry(Report $report, bool $allowRetry): array { + $existing = $this->findByLogicalIdentity($report); + if ($existing !== null) { + $this->assertSameSchema($report, $existing['schemaVersion']); + return ['id' => $existing['id'], 'created' => false]; + } + + try { + return $this->insertReport($report); + } catch (Exception $e) { + if (!in_array($e->getReason(), [Exception::REASON_CONSTRAINT_VIOLATION, Exception::REASON_UNIQUE_CONSTRAINT_VIOLATION], true)) { + throw $e; + } + + $existing = $this->findByLogicalIdentity($report); + if ($existing !== null) { + $this->assertSameSchema($report, $existing['schemaVersion']); + return ['id' => $existing['id'], 'created' => false]; + } + + if ($allowRetry) { + return $this->storeWithRetry($report, false); + } + + throw $e; + } + } + + /** @return array{id:int,created:true} */ + private function insertReport(Report $report): array { + $receivedAt = new \DateTimeImmutable('now', new \DateTimeZone('UTC')); + + $this->db->beginTransaction(); + try { + $qb = $this->db->getQueryBuilder(); + $qb->insert('usage_stats_reports')->values([ + 'protocol_version' => $qb->createNamedParameter($report->protocolVersion, IQueryBuilder::PARAM_INT), + 'application' => $qb->createNamedParameter($report->application), + 'installation_id' => $qb->createNamedParameter($report->installationId), + 'schema_version' => $qb->createNamedParameter($report->schemaVersion, IQueryBuilder::PARAM_INT), + 'period_start' => $qb->createNamedParameter($this->formatDateTime($report->periodStart)), + 'period_end' => $qb->createNamedParameter($this->formatDateTime($report->periodEnd)), + 'received_at' => $qb->createNamedParameter($this->formatDateTime($receivedAt)), + ])->executeStatement(); + $reportId = $qb->getLastInsertId(); + + foreach ($report->metrics as $metric) { + $this->insertMetric($reportId, $metric); + } + + $this->updateInstallation($report, $reportId, $receivedAt); + + $this->db->commit(); + return ['id' => $reportId, 'created' => true]; + } finally { + if ($this->db->inTransaction()) { + $this->db->rollBack(); + } + } + } + + private function insertMetric(int $reportId, Metric $metric): void { + $qb = $this->db->getQueryBuilder(); + $values = [ + 'report_id' => $qb->createNamedParameter($reportId, IQueryBuilder::PARAM_INT), + 'category' => $qb->createNamedParameter($metric->category), + 'metric_key' => $qb->createNamedParameter($metric->key), + 'metric_type' => $qb->createNamedParameter($metric->type), + 'value_integer' => $qb->createNamedParameter(null), + 'value_number' => $qb->createNamedParameter(null), + 'value_boolean' => $qb->createNamedParameter(null), + 'value_string' => $qb->createNamedParameter(null), + ]; + + switch ($metric->type) { + case 'integer': + $values['value_integer'] = $qb->createNamedParameter((int)$metric->value, IQueryBuilder::PARAM_INT); + break; + case 'number': + $values['value_number'] = $qb->createNamedParameter((float)$metric->value); + break; + case 'boolean': + $values['value_boolean'] = $qb->createNamedParameter((bool)$metric->value, IQueryBuilder::PARAM_BOOL); + break; + case 'string': + $values['value_string'] = $qb->createNamedParameter((string)$metric->value); + break; + } + + $qb->insert('usage_stats_metrics')->values($values)->executeStatement(); + } + + private function updateInstallation(Report $report, int $reportId, \DateTimeImmutable $receivedAt): void { + $receivedAtValue = $this->formatDateTime($receivedAt); + $periodStart = $this->formatDateTime($report->periodStart); + $periodEnd = $this->formatDateTime($report->periodEnd); + + $seenQb = $this->db->getQueryBuilder(); + $seenQb->update('usage_stats_installations') + ->set('last_seen_at', $seenQb->createNamedParameter($receivedAtValue)) + ->where($seenQb->expr()->eq('application', $seenQb->createNamedParameter($report->application))) + ->andWhere($seenQb->expr()->eq('installation_id', $seenQb->createNamedParameter($report->installationId))) + ->andWhere($seenQb->expr()->lt('last_seen_at', $seenQb->createNamedParameter($receivedAtValue))) + ->executeStatement(); + + $currentQb = $this->db->getQueryBuilder(); + $currentQb->update('usage_stats_installations') + ->set('last_report_id', $currentQb->createNamedParameter($reportId, IQueryBuilder::PARAM_INT)) + ->set('last_period_start', $currentQb->createNamedParameter($periodStart)) + ->set('last_period_end', $currentQb->createNamedParameter($periodEnd)) + ->where($currentQb->expr()->eq('application', $currentQb->createNamedParameter($report->application))) + ->andWhere($currentQb->expr()->eq('installation_id', $currentQb->createNamedParameter($report->installationId))) + ->andWhere($currentQb->expr()->orX( + $currentQb->expr()->lt('last_period_end', $currentQb->createNamedParameter($periodEnd)), + $currentQb->expr()->andX( + $currentQb->expr()->eq('last_period_end', $currentQb->createNamedParameter($periodEnd)), + $currentQb->expr()->lt('last_period_start', $currentQb->createNamedParameter($periodStart)), + ), + )) + ->executeStatement(); + + if ($this->installationExists($report->application, $report->installationId)) { + return; + } + + $insertQb = $this->db->getQueryBuilder(); + $insertQb->insert('usage_stats_installations')->values([ + 'application' => $insertQb->createNamedParameter($report->application), + 'installation_id' => $insertQb->createNamedParameter($report->installationId), + 'last_seen_at' => $insertQb->createNamedParameter($receivedAtValue), + 'last_report_id' => $insertQb->createNamedParameter($reportId, IQueryBuilder::PARAM_INT), + 'last_period_start' => $insertQb->createNamedParameter($periodStart), + 'last_period_end' => $insertQb->createNamedParameter($periodEnd), + ])->executeStatement(); + } + + private function installationExists(string $application, string $installationId): bool { + $qb = $this->db->getQueryBuilder(); + return $qb->select('id') + ->from('usage_stats_installations') + ->where($qb->expr()->eq('application', $qb->createNamedParameter($application))) + ->andWhere($qb->expr()->eq('installation_id', $qb->createNamedParameter($installationId))) + ->executeQuery() + ->fetchOne() !== false; + } + + /** @return array{id:int,schemaVersion:int}|null */ + private function findByLogicalIdentity(Report $report): ?array { + $qb = $this->db->getQueryBuilder(); + $row = $qb->select('id', 'schema_version')->from('usage_stats_reports') + ->where($qb->expr()->eq('application', $qb->createNamedParameter($report->application))) + ->andWhere($qb->expr()->eq('installation_id', $qb->createNamedParameter($report->installationId))) + ->andWhere($qb->expr()->eq('period_start', $qb->createNamedParameter($this->formatDateTime($report->periodStart)))) + ->andWhere($qb->expr()->eq('period_end', $qb->createNamedParameter($this->formatDateTime($report->periodEnd)))) + ->executeQuery() + ->fetchAssociative(); + + if ($row === false) { + return null; + } + + return [ + 'id' => (int)$row['id'], + 'schemaVersion' => (int)$row['schema_version'], + ]; + } + + private function assertSameSchema(Report $report, int $existingSchemaVersion): void { + if ($existingSchemaVersion !== $report->schemaVersion) { + throw new ConflictingReport('A report for this installation and period already exists with a different schema version.'); + } + } + + private function formatDateTime(\DateTimeImmutable $dateTime): string { + return $dateTime + ->setTimezone(new \DateTimeZone('UTC')) + ->format(self::DB_DATETIME_FORMAT); + } +} diff --git a/lib/Db/SchemaRepository.php b/lib/Db/SchemaRepository.php new file mode 100644 index 0000000..9aa7fce --- /dev/null +++ b/lib/Db/SchemaRepository.php @@ -0,0 +1,151 @@ +|null */ + public function find(string $application, int $schemaVersion): ?array { + $qb = $this->db->getQueryBuilder(); + $definition = $qb->select('definition') + ->from('usage_stats_schemas') + ->where($qb->expr()->eq('application', $qb->createNamedParameter($application))) + ->andWhere($qb->expr()->eq('schema_version', $qb->createNamedParameter($schemaVersion, IQueryBuilder::PARAM_INT))) + ->executeQuery() + ->fetchOne(); + + if ($definition === false) { + return null; + } + + return $this->decodeDefinition($definition); + } + + /** @return array|null */ + public function findMetric(string $application, string $category, string $key): ?array { + $identity = MetricIdentity::fromParts($category, $key); + foreach ($this->findAll($application) as $definition) { + foreach ($definition['metrics'] ?? [] as $metric) { + if (!is_array($metric)) { + continue; + } + $metricIdentity = MetricIdentity::fromParts( + (string)($metric['category'] ?? ''), + (string)($metric['key'] ?? ''), + ); + if ($metricIdentity === $identity) { + return $metric; + } + } + } + + return null; + } + + /** + * @param array $definition + * @return bool true when created, false when the same definition already exists + * @throws \LogicException when the version already exists with a different definition + */ + public function store(string $application, int $schemaVersion, array $definition): bool { + $existing = $this->find($application, $schemaVersion); + if ($existing !== null) { + if ($existing === $definition) { + return false; + } + throw new \LogicException('Schema version already exists with a different definition.'); + } + + $this->assertMetricCompatibility($application, $definition); + + $qb = $this->db->getQueryBuilder(); + $qb->insert('usage_stats_schemas')->values([ + 'application' => $qb->createNamedParameter($application), + 'schema_version' => $qb->createNamedParameter($schemaVersion, IQueryBuilder::PARAM_INT), + 'definition' => $qb->createNamedParameter(json_encode($definition, JSON_THROW_ON_ERROR)), + 'created_at' => $qb->createNamedParameter($this->formatDateTime( + new \DateTimeImmutable('now', new \DateTimeZone('UTC')), + )), + ])->executeStatement(); + + return true; + } + + /** @return list> */ + private function findAll(string $application): array { + $qb = $this->db->getQueryBuilder(); + $result = $qb->select('definition') + ->from('usage_stats_schemas') + ->where($qb->expr()->eq('application', $qb->createNamedParameter($application))) + ->orderBy('schema_version', 'ASC') + ->executeQuery(); + + $definitions = []; + foreach ($result->iterateAssociative() as $row) { + $decoded = $this->decodeDefinition($row['definition'] ?? null); + if ($decoded !== null) { + $definitions[] = $decoded; + } + } + + return $definitions; + } + + /** @param array $definition */ + private function assertMetricCompatibility(string $application, array $definition): void { + $existingMetrics = []; + foreach ($this->findAll($application) as $existingDefinition) { + foreach ($existingDefinition['metrics'] ?? [] as $metric) { + if (!is_array($metric)) { + continue; + } + $identity = MetricIdentity::fromParts((string)($metric['category'] ?? ''), (string)($metric['key'] ?? '')); + $existingMetrics[$identity] = $metric; + } + } + + foreach ($definition['metrics'] ?? [] as $metric) { + if (!is_array($metric)) { + continue; + } + $identity = MetricIdentity::fromParts((string)($metric['category'] ?? ''), (string)($metric['key'] ?? '')); + $existing = $existingMetrics[$identity] ?? null; + if (!is_array($existing)) { + continue; + } + + foreach (['type', 'kind', 'aggregation'] as $field) { + if (($existing[$field] ?? null) !== ($metric[$field] ?? null)) { + throw new \LogicException("Metric {$metric['category']}:{$metric['key']} changes {$field}; use a new metric key for incompatible semantics."); + } + } + } + } + + /** @return array|null */ + private function decodeDefinition(mixed $definition): ?array { + $decoded = json_decode((string)$definition, true, flags: JSON_THROW_ON_ERROR); + return is_array($decoded) ? $decoded : null; + } + + private function formatDateTime(\DateTimeImmutable $dateTime): string { + return $dateTime + ->setTimezone(new \DateTimeZone('UTC')) + ->format(self::DB_DATETIME_FORMAT); + } +} diff --git a/lib/Db/StatisticsRepository.php b/lib/Db/StatisticsRepository.php new file mode 100644 index 0000000..ebd6b37 --- /dev/null +++ b/lib/Db/StatisticsRepository.php @@ -0,0 +1,192 @@ +db->getQueryBuilder(); + $result = $qb->select($qb->func()->count()) + ->from('usage_stats_installations') + ->where($qb->expr()->eq('application', $qb->createNamedParameter($application))) + ->andWhere($qb->expr()->gte('last_seen_at', $qb->createNamedParameter($this->formatDateTime($since)))) + ->executeQuery() + ->fetchOne(); + + return (int)$result; + } + + /** @return list */ + public function currentDistribution(string $application, string $category, string $key): array { + $qb = $this->db->getQueryBuilder(); + $result = $qb + ->select( + 'm.metric_type', + 'm.value_integer', + 'm.value_number', + 'm.value_boolean', + 'm.value_string', + $qb->func()->count('', 'value_count'), + ) + ->from('usage_stats_installations', 'i') + ->innerJoin('i', 'usage_stats_metrics', 'm', $qb->expr()->eq('m.report_id', 'i.last_report_id')) + ->where($qb->expr()->eq('i.application', $qb->createNamedParameter($application))) + ->andWhere($qb->expr()->eq('m.category', $qb->createNamedParameter($category))) + ->andWhere($qb->expr()->eq('m.metric_key', $qb->createNamedParameter($key))) + ->groupBy('m.metric_type', 'm.value_integer', 'm.value_number', 'm.value_boolean', 'm.value_string') + ->executeQuery(); + + $distribution = []; + foreach ($result->iterateAssociative() as $row) { + $distribution[] = [ + 'value' => $this->readTypedValue($row), + 'count' => (int)$row['value_count'], + ]; + } + + usort($distribution, static function (array $left, array $right): int { + $countComparison = $right['count'] <=> $left['count']; + if ($countComparison !== 0) { + return $countComparison; + } + + return $left['value'] <=> $right['value']; + }); + + return $distribution; + } + + /** @return array{count:int,average:float|null,min:float|null,max:float|null,total:float|null} */ + public function currentNumericalEvaluation(string $application, string $category, string $key, string $type): array { + $column = $this->numericalColumn($type); + $qb = $this->db->getQueryBuilder(); + $row = $qb + ->select( + $qb->func()->count($column), + $qb->func()->sum($column), + $qb->func()->min($column), + $qb->func()->max($column), + ) + ->from('usage_stats_installations', 'i') + ->innerJoin('i', 'usage_stats_metrics', 'm', $qb->expr()->eq('m.report_id', 'i.last_report_id')) + ->where($qb->expr()->eq('i.application', $qb->createNamedParameter($application))) + ->andWhere($qb->expr()->eq('m.category', $qb->createNamedParameter($category))) + ->andWhere($qb->expr()->eq('m.metric_key', $qb->createNamedParameter($key))) + ->andWhere($qb->expr()->eq('m.metric_type', $qb->createNamedParameter($type))) + ->executeQuery() + ->fetchNumeric(); + + if ($row === false || (int)$row[0] === 0) { + return ['count' => 0, 'average' => null, 'min' => null, 'max' => null, 'total' => null]; + } + + $count = (int)$row[0]; + $total = (float)$row[1]; + + return [ + 'count' => $count, + 'average' => round($total / $count, 2), + 'min' => (float)$row[2], + 'max' => (float)$row[3], + 'total' => $total, + ]; + } + + /** @return list */ + public function numericalHistory( + string $application, + string $category, + string $key, + string $type, + \DateTimeImmutable $from, + \DateTimeImmutable $to, + ): array { + $column = $this->numericalColumn($type); + $qb = $this->db->getQueryBuilder(); + $result = $qb + ->select( + 'r.period_start', + 'r.period_end', + $qb->func()->count($column), + $qb->func()->sum($column), + $qb->func()->min($column), + $qb->func()->max($column), + ) + ->from('usage_stats_reports', 'r') + ->innerJoin('r', 'usage_stats_metrics', 'm', $qb->expr()->eq('m.report_id', 'r.id')) + ->where($qb->expr()->eq('r.application', $qb->createNamedParameter($application))) + ->andWhere($qb->expr()->eq('m.category', $qb->createNamedParameter($category))) + ->andWhere($qb->expr()->eq('m.metric_key', $qb->createNamedParameter($key))) + ->andWhere($qb->expr()->eq('m.metric_type', $qb->createNamedParameter($type))) + ->andWhere($qb->expr()->gte('r.period_end', $qb->createNamedParameter($this->formatDateTime($from)))) + ->andWhere($qb->expr()->lte('r.period_end', $qb->createNamedParameter($this->formatDateTime($to)))) + ->groupBy('r.period_start', 'r.period_end') + ->executeQuery(); + + $history = []; + foreach ($result->iterateNumeric() as $row) { + $count = (int)$row[2]; + $total = (float)$row[3]; + $history[] = [ + 'periodStart' => (string)$row[0], + 'periodEnd' => (string)$row[1], + 'count' => $count, + 'average' => round($total / $count, 2), + 'min' => (float)$row[4], + 'max' => (float)$row[5], + 'total' => $total, + ]; + } + + usort($history, static fn (array $left, array $right): int => $left['periodEnd'] <=> $right['periodEnd']); + return $history; + } + + private function numericalColumn(string $type): string { + return match ($type) { + 'integer' => 'value_integer', + 'number' => 'value_number', + default => throw new \InvalidArgumentException('Numerical metrics must use integer or number type.'), + }; + } + + /** @param array $row */ + private function readTypedValue(array $row): mixed { + /** @var 'integer'|'number'|'boolean'|'string' $type */ + $type = $row['metric_type']; + + return match ($type) { + 'integer' => (int)$row['value_integer'], + 'number' => (float)$row['value_number'], + 'boolean' => $this->readBoolean($row['value_boolean']), + 'string' => (string)$row['value_string'], + }; + } + + private function readBoolean(mixed $value): bool { + if (is_bool($value)) { + return $value; + } + + return in_array($value, [1, '1', 't', 'true'], true); + } + + private function formatDateTime(\DateTimeImmutable $dateTime): string { + return $dateTime + ->setTimezone(new \DateTimeZone('UTC')) + ->format(self::DB_DATETIME_FORMAT); + } +} diff --git a/lib/Migration/Version010000Date20260908001000.php b/lib/Migration/Version010000Date20260908001000.php new file mode 100644 index 0000000..de9bc01 --- /dev/null +++ b/lib/Migration/Version010000Date20260908001000.php @@ -0,0 +1,83 @@ +hasTable('usage_stats_schemas')) { + $schemas = $schema->createTable('usage_stats_schemas'); + $schemas->addColumn('id', Types::BIGINT, ['autoincrement' => true, 'unsigned' => true]); + $schemas->addColumn('application', Types::STRING, ['length' => 128]); + $schemas->addColumn('schema_version', Types::INTEGER, ['unsigned' => true]); + $schemas->addColumn('definition', Types::TEXT); + $schemas->addColumn('created_at', Types::DATETIME_IMMUTABLE); + $schemas->setPrimaryKey(['id']); + $schemas->addUniqueIndex(['application', 'schema_version'], 'usage_stats_schema_identity'); + } + + if (!$schema->hasTable('usage_stats_installations')) { + $installations = $schema->createTable('usage_stats_installations'); + $installations->addColumn('id', Types::BIGINT, ['autoincrement' => true, 'unsigned' => true]); + $installations->addColumn('application', Types::STRING, ['length' => 128]); + $installations->addColumn('installation_id', Types::STRING, ['length' => 128]); + $installations->addColumn('last_seen_at', Types::DATETIME_IMMUTABLE); + $installations->addColumn('last_report_id', Types::BIGINT, ['unsigned' => true]); + $installations->addColumn('last_period_start', Types::DATETIME_IMMUTABLE); + $installations->addColumn('last_period_end', Types::DATETIME_IMMUTABLE); + $installations->setPrimaryKey(['id']); + $installations->addUniqueIndex(['application', 'installation_id'], 'usage_stats_installation_identity'); + $installations->addIndex(['application', 'last_seen_at'], 'usage_stats_active_installations'); + } + + if (!$schema->hasTable('usage_stats_reports')) { + $reports = $schema->createTable('usage_stats_reports'); + $reports->addColumn('id', Types::BIGINT, ['autoincrement' => true, 'unsigned' => true]); + $reports->addColumn('protocol_version', Types::INTEGER, ['unsigned' => true]); + $reports->addColumn('application', Types::STRING, ['length' => 128]); + $reports->addColumn('installation_id', Types::STRING, ['length' => 128]); + $reports->addColumn('schema_version', Types::INTEGER, ['unsigned' => true]); + $reports->addColumn('period_start', Types::DATETIME_IMMUTABLE); + $reports->addColumn('period_end', Types::DATETIME_IMMUTABLE); + $reports->addColumn('received_at', Types::DATETIME_IMMUTABLE); + $reports->setPrimaryKey(['id']); + $reports->addUniqueIndex(['application', 'installation_id', 'period_start', 'period_end'], 'usage_stats_report_identity'); + $reports->addIndex(['application', 'received_at'], 'usage_stats_recent_reports'); + } + + if (!$schema->hasTable('usage_stats_metrics')) { + $metrics = $schema->createTable('usage_stats_metrics'); + $metrics->addColumn('id', Types::BIGINT, ['autoincrement' => true, 'unsigned' => true]); + $metrics->addColumn('report_id', Types::BIGINT, ['unsigned' => true]); + $metrics->addColumn('category', Types::STRING, ['length' => 128]); + $metrics->addColumn('metric_key', Types::STRING, ['length' => 512]); + $metrics->addColumn('metric_type', Types::STRING, ['length' => 16]); + $metrics->addColumn('value_integer', Types::BIGINT, ['notnull' => false]); + $metrics->addColumn('value_number', Types::FLOAT, ['notnull' => false]); + $metrics->addColumn('value_boolean', Types::BOOLEAN, ['notnull' => false]); + $metrics->addColumn('value_string', Types::TEXT, ['notnull' => false]); + $metrics->setPrimaryKey(['id']); + $metrics->addUniqueIndex(['report_id', 'category', 'metric_key'], 'usage_stats_metric_identity'); + $metrics->addIndex(['category', 'metric_key'], 'usage_stats_metric_lookup'); + } + + return $schema; + } +} diff --git a/lib/Service/ConflictingReport.php b/lib/Service/ConflictingReport.php new file mode 100644 index 0000000..6005e72 --- /dev/null +++ b/lib/Service/ConflictingReport.php @@ -0,0 +1,13 @@ + $metrics */ public function __construct( public int $protocolVersion, diff --git a/lib/Service/ReportFactory.php b/lib/Service/ReportFactory.php new file mode 100644 index 0000000..f637dd1 --- /dev/null +++ b/lib/Service/ReportFactory.php @@ -0,0 +1,135 @@ +\d{4}-(?:0[1-9]|1[0-2])-(?:0[1-9]|[12]\d|3[01]))T(?